Search code examples
pythonjsonlogistic-regression

Python: Serialization of Logistic Regression to JSON and loading JSON


I am testing the code below for serialization of a Logistic Regression model using JSON. It seems to write the JSON file OK, but I am unable to read the JSON file successfully.

I got the following error message for lr.predict(X). "AttributeError: 'list' object has no attribute 'shape'"

Any input would be highly appreciated.

from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
import os
import json
import codecs
import numpy as np

iris = load_iris()
X, y = iris.data, iris.target

lr = LogisticRegression()
lr.fit(X, y)

attr = lr.__dict__
New_attr = attr 
keys = New_attr.keys()


# --------------------
# Converting array to list  
# --------------------
New_attr['coef_'] = attr['coef_'].tolist()
New_attr['classes_'] = attr['classes_'].tolist()
New_attr['n_iter_'] = attr['n_iter_'].tolist()
New_attr['intercept_'] = attr['intercept_'].tolist()

# --------------------
# Writing the JSON file... 
# --------------------
json_file = "file.json" 
json.dump(New_attr, codecs.open(json_file, 'w', encoding='utf-8'), 
    sort_keys=True, indent=4)


# --------------------
# Reading the JSON file... 
# --------------------
obj_text = codecs.open(json_file, 'r', encoding='utf-8').read()
b_new = json.loads(obj_text)

lr = LogisticRegression()
print(b_new)
lr.__dict__ = dict(b_new)
lr.predict(X)

Solution

  • Just made it work.

    lr.coef_ = np.array(lr.coef_)
    lr.classes_ = np.array(lr.classes_)
    lr.n_iter_ = np.array(lr.n_iter_)
    lr.intercept_ = np.array(lr.intercept_)
    lr.predict(X)