线性回归模型

时间:2018-02-04 12:09:12

标签: python python-3.x numpy machine-learning regression

以下是我使用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()

由于我必须最小化误差,即误差函数wrt的偏导数为m给出x,而wrt c给出一个常数。

1 个答案:

答案 0 :(得分:4)

您正在进行随机梯度下降,评估每个数据点的拟合度。因此,最终的mc会为您提供拟合关系的参数。您正在绘制的线条是&#39; evolution&#39;拟合线。

以下是我绘制它的方式,并对您的代码进行了一些其他调整,因为我发现了您正在做的事情:

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()

enter image description here

我在代码中创建的主要模式是:单步执行压缩XY,这样您就可以使用它而无需编入索引。为简单起见,我也为它们制作了一维数组。如果您直接使用渐变而不使用abs,则不需要+ ve和-ve情况的不同路径。

相关问题