以下是我使用 SGD 实现的线性回归,但获得的直线不是最合适的。我该如何改进它?
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
style.use("fivethirtyeight")
x=[[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]]
y=[[3],[5],[9],[9],[11],[13],[16],[17],[19],[21]]
X=np.array(x)
Y=np.array(y)
learning_rate=0.015
m=1
c=2
gues=[]
for i in range(len(x)):
guess=m*x[i][0]+c
error=guess-y[i][0]
if error<0:
m=m+abs(error)*x[i][0]*learning_rate
c=c+abs(error)*learning_rate
if error>0:
m=m-abs(error)*x[i][0]*learning_rate
c=c-abs(error)*learning_rate
gues.append([guess])
t=np.array(gues)
plt.scatter(X,Y)
plt.plot(X,t)
plt.show()
from sklearn.linear_model import LinearRegression
var=LinearRegression()
var.fit(X,Y)
plt.scatter(X,Y)
plt.plot(X,var.predict(X))
plt.show()
因为我必须最小化错误,这是(猜测-y)对错误函数 w.r.t 的偏导数到 m
给出 x
和 w.r.t c
给出一个常量。
最佳答案
您正在进行随机梯度下降,评估每个数据点的拟合度。所以最后的 m
和 c
给你拟合关系的参数。您绘制的线是拟合线的“演变”。
这是我绘制它的方式,当我弄清楚你在做什么时对你的代码进行了一些其他调整:
import numpy as np
import matplotlib.pyplot as plt
X = np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Y = np.array([ 3, 5, 9, 9, 11, 13, 16, 17, 19, 21])
learning_rate = 0.015
m = 1
c = 2
gues = []
for xi, yi in zip(X, Y):
guess = m * xi + c
error = guess - yi
m = m - error * xi * learning_rate
c = c - error * learning_rate
gues.append(guess)
t = np.array(gues)
# Plot the modeled line.
y_hat = m * X + c
plt.figure(figsize=(10,5))
plt.plot(X, y_hat, c='red')
# Plot the data.
plt.scatter(X, Y)
# Plot the evolution of guesses.
plt.plot(X, t)
plt.show()
我在代码中所做的主要修改是:跨过压缩的 X
和 Y
这样您就可以使用 then 而无需索引它们。为了简单起见,我也将它们设为一维数组。如果您直接使用渐变,而不使用 abs
,则 +ve 和 -ve 情况下不需要不同的路径。
关于python - 线性回归模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48607884/