逻辑回归无法拟合我的数据

数据挖掘 机器学习 Python 逻辑回归
2021-09-30 13:44:17

我正在尝试拟合我的数据,但我无法拟合它。数据集

0.50,0
0.75,0
1.00,0
1.25,0
1.50,0
1.75,0
1.75,1
2.00,0
2.25,1
2.50,0
2.75,1
3.00,0
3.25,1
3.50,0
4.00,1
4.25,1
4.50,1
4.75,1
5.00,1
5.50,1

和我的代码

data = np.loadtxt('dat', delimiter=',',dtype=None);

x=data[:,0:1];
y=data[:,1].reshape(x.size/x[0].size,1);
a=np.ones(shape=(y.size,x[0].size+1));
a[:,1:2]=x;
q=np.ones(shape=(a.shape[1],1));
alpha=0.003

for i in range(500000):
    h=1/(1+np.exp(-np.dot(a,q)))
    for j in range(q.size):
        q[j][0]=q[j][0]-alpha*np.sum((h-y)*a[:,j]);
plt.axis((-1,10,-1,5))
plt.plot(x,y,'x',x,h);
plt.show();

所以我尝试了不同的学习率(alpha),尝试了不同的迭代次数,但我的拟合数据看起来像这样在此处输入图像描述 ,但它应该看起来像这样在此处输入链接描述

我错过了什么?是否有任何逻辑错误或类似的东西?谢谢你的交易。

2个回答

问题出在以下行:

q[j][0]=q[j][0]-alpha*np.sum((h-y)*a[:,j]);

(h-y)has shape (20, 1)a[:,j]has shape (20),将它们相乘会导致 shape (20, 20),这是错误的。

尝试a[:,j:j+1]代替,a[:,j]它将开始工作:

q[j][0]=q[j][0]-alpha*np.sum((h-y)*a[:,j:j+1]);

这给出了以下情节:

结果

您可以稍微调整变量的形状以使其更容易:

x=data[:,:1]
y=data[:,1]
a=np.hstack([np.ones((len(x), 1)), x])
q=np.ones(a.shape[1])
alpha=0.003

for i in range(10000):
    h=1/(1+np.exp(-np.dot(a,q)))
    for j in range(len(q)):
        q[j]=q[j]-alpha*np.sum((h-y)*a[:,j])

plt.plot(x,y,'x',x,h)
plt.show()

另请注意,在 Python 中您不需要 ; 在每一行的末尾。

我没有写很多 Python 代码,但看起来你是硬编码 alpha,这可以解释你的结果。我建议阅读逻辑回归背后的数学和直觉,以及一般如何估计模型参数。(https://en.wikipedia.org/wiki/Maximum_likelihood_estimation)。

有关实现的指导,这篇文章很好地完成了这些步骤,并且受益于 Python:http ://aimotion.blogspot.com/2011/11/machine-learning-with-python-logistic.html 。

虽然我强烈建议您首先学习如何从头开始编写它,但您可能需要查看 R,它具有非常易于使用的逻辑回归的基本实现。

df = read.csv("~/data.csv", header = T, stringsAsFactors = F)
glm_train = glm(classifier ~ value, data = df, family = "binomial")

library(ggplot2)
binomial_smooth = function(...) {
  geom_smooth(method = "glm", method.args = list(family = "binomial"), ...)
}
ggplot(df, aes(x = value, y = classifier)) + geom_point() + binomial_smooth()

summary(glm_train)
# Deviance Residuals: 
#   Min        1Q    Median        3Q       Max  
# -1.70557  -0.57357  -0.04654   0.45470   1.82008  
# 
# Coefficients:
#   Estimate Std. Error z value Pr(>|z|)  
# (Intercept)  -4.0777     1.7610  -2.316   0.0206 *
#   x             1.5046     0.6287   2.393   0.0167 *
#   ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

在此处输入图像描述