【发布时间】:2020-06-12 02:01:23
【问题描述】:
我使用 scikit-learn 的 LogisticRegression 分类器(多项式/多类)训练了一个模型。然后我将模型中的系数保存到文件中。接下来,我将系数加载到我自己的 softmax 实现中,这就是 scikit-learn's documentation 声称的用于多项式情况的逻辑回归分类器。但是,预测不一致。
- 使用 scikit-learn 训练 mlogit 模型
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import json
# Split data into train-test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# Train model
mlr = LogisticRegression(random_state=21, multi_class='multinomial', solver='newton-cg')
mlr.fit(X_train, y_train)
y_pred = mlr.predict(X_test)
# Save test data and coefficients
json.dump(X_test.tolist(), open('X_test.json'), 'w'), indent=4)
json.dump(y_pred.tolist(), open('y_pred.json'), 'w'), indent=4)
json.dump(mlr.classes_.tolist(), open('classes.json'), 'w'), indent=4)
json.dump(mlr.coef_.tolist(), open('weights.json'), 'w'), indent=4)
- 通过Scipy自行实现softmax
from scipy.special import softmax
import numpy as np
import json
def predict(x, w, classes):
z = np.dot(x, np.transpose(w))
sm = softmax(z)
return [classes[i] for i in sm.argmax(axis=1)]
x = json.load(open('X_test.json'))
w = json.load(open('weights.json'))
classes = json.load(open('classes.json'))
y_pred_self = predict(x, w, classes)
- 结果不匹配
本质上,当我比较
y_pred_self和y_pred时,它们并不相同(大约 85% 相似)。
所以我的问题是 scikit-learn softmax 或 predict implementation 是否有一些非标准/隐藏的调整?
旁注:我也在 Ruby 中尝试了自我实现,它也给出了不正确的预测。
【问题讨论】:
标签: python scikit-learn mlogit