我尝试使用Logistic回归模型FRO SCIKIT学习解决Andrew Ng从机器学习课程到Coursera的ExcCISE 2。但我得到的结果是错误的:
1)结果系数与答案不匹配:
我能从模特身上得到什么
根据答案我应该得到什么
[-25.16,0.21,0.20]
你可以在图上看到(错误的图形),凭直觉,决策边界似乎略低于决策边界。在
2)图形结果似乎错误
如您所见,决策边界在下面
回答
我的代码:
% matplotlib notebook
# IMPORT DATA
ex2_folder = 'machine-learning-ex2/ex2'
input_1 = pd.read_csv(folder + ex2_folder +'/ex2data1.txt', header = None)
X = input_1[[0,1]]
y = input_1[2]
# IMPORT AND FIT MODEL
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(fit_intercept = True)
model.fit(X,y)
print('Intercept (Theta 0: {}). Coefficients: {}'.format(model.intercept_, model.coef_))
# CALCULATE GRID
n = 5
xx1, xx2 = np.mgrid[25:101:n, 25:101:n]
grid = np.c_[xx1.ravel(), xx2.ravel()]
probs = model.predict_proba(grid)[:, 1]
probs = probs.reshape(xx1.shape)
# PLOTTING
f = plt.figure()
ax = plt.gca()
for outcome in [0,1]:
xo = 'yo' if outcome == 0 else 'k+'
selection = y == outcome
plt.plot(X.loc[selection, 0],X.loc[selection,1],xo, mec = 'k')
plt.xlim([25,100])
plt.ylim([25,100])
plt.xlabel('Exam 1 Score')
plt.ylabel('Exam 2 Score')
plt.title('Exam 1 & 2 and admission outcome')
contour = ax.contourf(xx1,xx2, probs, 100, cmap="RdBu",
vmin=0, vmax=1)
ax_c = f.colorbar(contour)
ax_c.set_label("$P(y = 1)$")
ax_c.set_ticks([0, .25, .5, .75, 1])
plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors='b', alpha = 0.3);
plt.plot(xx1[probs > 0.5], xx2[probs > 0.5],'.b', alpha = 0.3)
链接
要获得相同的结果,您需要创建相同的测试条件。在
一个明显的区别是迭代次数。
Sklearn LogisticRegression
分类器的默认迭代计数是100,而andrewng的示例代码运行了400次迭代。这肯定会给你一个不同于阮氏课程的结果。在对于cdl2>的函数,我不确定它是否在使用cross}函数。在
最后一点,在实现更高级别的解决方案(scikitlearn/tensorflow/keras)之前,您应该首先尝试用纯python实现它们,以了解它们是如何工作的。它将更容易(和更有趣)尝试和更高级别的包为您工作。在
相关问题 更多 >
编程相关推荐