【问题标题】:Python: Serialization of Logistic Regression to JSON and loading JSON [duplicate]Python:将逻辑回归序列化为 JSON 并加载 JSON [重复]
【发布时间】:2019-01-31 19:20:20
【问题描述】:

我正在测试下面的代码,以使用 JSON 对逻辑回归模型进行序列化。似乎可以写入 JSON 文件,但我无法成功读取 JSON 文件。

我收到以下有关 lr.predict(X) 的错误消息。 "AttributeError: 'list' 对象没有属性 'shape'"

任何意见将不胜感激。

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)

【问题讨论】:

  • numpy 数组的列表和形状需要使用len()
  • 谢谢大赏!刚刚编辑过,它来自 lr.predict(X),所以我猜我的 b_new 里面的某个地方不正确......
  • 注意,New_attr = attr 除了创建一个引用与attr 相同的对象的新变量之外,实际上并没有做任何事情

标签: python json logistic-regression


【解决方案1】:

刚刚成功。

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)

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 2012-07-18
    • 2021-11-09
    • 2020-03-22
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多