您需要通过调整参数来优化模型。
- 由于您的数据集很小,您需要指定好的算法进行优化。对于小数据集
lbfgs 是一个不错的选择。
- 另一个重要的参数是
inverse of regularization strength,在sklearn中是C。在sklearn中C的默认值是1.0。如果你像这样对不同的C值运行一个小测试
例如
from sklearn.linear_model import LogisticRegression
import numpy as np
import matplotlib.pyplot as plt
hours1= [0.50,0.75,1.00,
1.25,1.50,1.75,1.75,2.00,2.25,
2.50,2.75,3.00,3.25,3.50,4.00,
4.25,4.50,
4.75,5.00,5.50]
len(hours1)
pass1=[0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1]
len(pass1)
X_train=np.array([hours1])
y_train=np.array([pass1])
X_train.shape=(20,1)
y_train.shape=(20,)
param_grid = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
coef = []
intc = []
param = []
for p in param_grid:
clf = LogisticRegression(C=p,random_state=0,solver='lbfgs',fit_intercept=True)
clf.fit(X_train, y_train)
coef.append(clf.coef_[0])
intc.append(clf.intercept_)
param.append(p)
coef = np.array(coef)
intc = np.array(intc)
plt.plot(param, coef[:, 0], color='blue', marker='x', label='coefficient')
plt.plot(param, intc[:, 0], color='green', marker='o', label='intercept')
plt.ylabel('intercept/coefficient')
plt.xlabel('C')
plt.legend(loc='right')
plt.xscale('log')
plt.show()
如果你在不同的 C 值上绘制截距和系数,你可以看到当 C=1000 或附近时你得到了预期的输出。
现在您可以使用 C as 1000( 1e3 == 1000) 拟合模型
clf = LogisticRegression(C=1e3,random_state=0,solver='lbfgs',fit_intercept=True)
clf.fit(X_train, y_train)
print("coef_ is", clf.coef_)
print("intercept_ is" ,clf.intercept_)
#output
coef_ is [[1.50405093]]
intercept_ is [-4.07616221]