线性回归模型

3
以下是我使用SGD实现的线性回归,但得到的直线并不是最佳拟合线。我该如何改进呢?enter image description here
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()

由于我必须最小化误差,即对误差函数关于m的偏导数产生(猜测-y),关于x和关于c的偏导数给出一个常数。

1个回答

4
你正在进行随机梯度下降,对每个数据点进行拟合评估。因此,最终的mc给出了拟合关系的参数。你绘制的线是拟合线的“演变”。
这是我如何绘制它的,还有一些调整你的代码,因为我弄清楚你在做什么:
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()

我对代码进行的主要修改如下:跳过压缩的 XY,这样你就可以直接使用它们而不需要对它们进行索引。我还将它们变为一维数组以方便操作。如果你直接使用梯度,而不是 abs,那么你不需要区分正负情况的不同路径。

enter image description here


我在这里做错了什么?你也做了同样的事情,但你的代码行是最适合的,而我的不是。 - Om Sharma
1
你并没有做错什么,只是mc是你的最终参数,而不是gues - Matt Hall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接