1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python对于一元线性回归模型_Python|机器学习-一元线性回归

python对于一元线性回归模型_Python|机器学习-一元线性回归

时间:2021-03-02 20:55:03

相关推荐

python对于一元线性回归模型_Python|机器学习-一元线性回归

一元线性回归模型很简单

y1=ax+b+ε,y1为实际值,ε为正态的误差。

y2=ax+b,y2为预测值。

ε=y1-y2。def model(a,b,x):

# x is vector,a and b are the common number.

return a*x+b

这里将整组数据的预测结果方差作为损失函数。

J(a,b)=sum((y1-y2)^2)/ndef cost(a,b,x,y):

# x is argu, y is actual result.

n=len(x)

return np.square(y-a*x-b).sum()/n

优化函数则进行使损失函数,即方差最小的方向进行搜索

a=a-theta*(∂J/∂a)

b=b-theta*(∂J/∂b)

这里的解释就是,对影响因素a或b求损失函数J的偏导,如果损失函数随着a或b增大而增大,我们就需要反方向搜索,使得损失函数变小。

对于偏导的求取则看的别人的推导公式

theta为搜索步长,影响速度和精度(我猜的,实际没有验证)def optimize(a,b,x,y):

theta = 1e-1 # settle the step as 0.1

n=len(x)

y_hat = model(a,b,x)

# compute forecast values

da = ((y_hat-y)*x).sum()/n

db = (y_hat-y).sum()/n

a = a - theta*da

b = b - theta*db

return a, b

使用sklearn库,可以使用现成的线性回归模型import numpy as np

from sklearn.linear_model import LinearRegression

import matplotlib.pyplot as plt

x = [1,2,4,5,6,6,7,9]

x = np.reshape(x,newshape=(8,1))

y = [10,9,9,9,7,5,3,1]

y = np.reshape(y,newshape=(8,1))

# create an instance of LinearRegression model

lr = LinearRegression()

# train model

lr.fit(x,y)

lr.score(x,y)

# compute y_hat

y_hat = lr.predict(x)

# show the result

plt.scatter(x,y)

plt.plot(x, y_hat)

plt.show()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。