在Python中绘制逻辑回归曲线时出错

时间:2019-06-15 00:54:00

标签: python scikit-learn

ValueError:操作数不能与形状(6,500)(6,)一起广播

我不知道如何更改变量的形状。只知道clf.coef_与clf.intercept_不同。

from sklearn.linear_model import LogisticRegression

x = np.array(dados['Satisfacao_acess'])
y = np.array(dados['Satisf_usoacess'])

print(y.shape)
print(x.shape)

clf = LogisticRegression(C=1e7)
clf.fit(x.reshape(-1,1), y)

def model(x):
    return 1 / (1 + np.exp(-x))

print(clf.coef_.shape)
print (clf.intercept_.shape)

line = np.linspace(1, 110, 500)
line = model(line * clf.coef_+ clf.intercept_).ravel()


plt.scatter(x, y)
plt.plot(np.linspace(1, 110, 500), line, c='C1')
plt.axvline(x=0.5 - (clf.intercept_/clf.coef_), c='k', ls='dotted', lw=1)
plt.show()

print('Acurácia: %.3f' % clf.score(x.reshape(-1,1), y))
print('Os parâmetros do modelos são: %.3f, %.3f' % (clf.intercept_, clf.coef_))

输出:

(57,)
(57,)
(6, 1)
(6,)
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/logistic.py:432: FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning.
  FutureWarning)
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/logistic.py:469: FutureWarning: Default multi_class will be changed to 'auto' in 0.22. Specify the multi_class option to silence this warning."this warning.", FutureWarning)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-150-da96d96d5c71> in <module>()
     17 
     18 line = np.linspace(1, 110, 500)
---> 19 line = model(line * clf.coef_+ clf.intercept_).ravel()
     20 
     21 
ValueError: operands could not be broadcast together with shapes (6,500) (6,)

1 个答案:

答案 0 :(得分:0)

我认为您对LogisticRegression方法在sci-kit学习中的工作方式有误解。

这是每个attributes的形状的生成方式。

  • coef_-shape(1,n_features)或您的情况下shape(n_classes,n_features)
  • intercept_-shape(1,)或您的情况下shape(n_classes,)

在示例输出中,您似乎只有1个要素和6个类。

因此,您将必须生成6条单独的行。您使用的公式是正确的。

# Repeat line 6 times
line = np.tile(np.linspace(1, 100, 500), (6, 1))

# Reshape intercept to add to each row element
# Generate a (6, 500) matrix
# 6 lines, 500 points each
line = model(line * clf.coef_ + clf.intercept_.reshape(6, 1)).ravel()

这将返回x的{​​{1}}值范围内的6行(每行一个单独的类)的结果值