【机器学习】python基础实现线性回归

手写梯度下降的实现y=kx+b的线性回归

算法步骤:

(1)构造数据,y=3*x+5;

(2)随机初始化\hat{k}\hat{b},任意数值,例如\hat{k}=9,\hat{b}=10;

(3)计算\hat{y}\hat{y}=\hat{k}x+\hat{b},并计算loss=(y-\hat{y})^{^{2}}=(y-(\hat{k}x+\hat{b}))^{2}

(4)分别对\hat{k}\hat{b}求导数,\hat{k}=\hat{k}-\Delta \hat{k}\hat{b}=\hat{b}-\Delta \hat{b}

        其中

      \Delta \hat{k}={\frac{\partial loss}{\partial \hat{k}}}=-2(y-({\hat{k}x+\hat{b})})\cdot x

\Delta \hat{b}={\frac{\partial loss}{\partial \hat{b}}}=-2(y-({\hat{k}x+\hat{b})})

重复循环n次后停止

构造线性函数:

      y=kx+b\ \ (k=3,b=5)

 代码实现:

X=[i for i in range(0,15)]

k=3
b=5
Y=[k*i+b for i in X]

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

# 在同一个图形中绘制散点图和折线图
ax.scatter(X, Y, color='blue', label='scatter')
ax.plot(X, Y, color='red', label='line')

# 添加图例
ax.legend()

# 显示图形
plt.show()

MSE损失函数:

loss=(y-\hat{y})^{^{2}}=(y-(\hat{k}x+\hat{b}))^{2}

loss.append((Y[i]-y_[i])**2)  #公式对应代码

分别对k和b求导结果如图所示:

{\frac{\partial loss}{\partial \hat{k}}}=-2(y-({\hat{k}x+\hat{b})})\cdot x

{\frac{\partial loss}{\partial \hat{b}}}=-2(y-({\hat{k}x+\hat{b})})

#公式对应代码
delta_K_sum.append((Y[i]-y_[i])*(-2)*X[i])
delta_B_sum.append((Y[i]-y_[i])*(-2))

全部代码:

X=[i for i in range(0,15)]
X
k=3
b=5
Y=[k*i+b for i in X]
Y
import matplotlib.pyplot as plt
# 创建散点图
plt.scatter(X, Y)

# 显示图形
plt.show()
#随机初始化要求的k和b
K=8
B=10
#k和b是正确答案,根据数据和随机初始化的K和B去拟合函数,找到最优的k和b
#y=Kx+B
loss=[]

#计算预测值
for i in range(1000):
    y_=[K*i+B for i in X]

    loss=[]
    for i in range(len(X)):
        loss.append((Y[i]-y_[i])**2)
    print(sum(loss)/len(loss))
    # cha=loss.sum()/len(loss)
    #计算loss

    #根据最小二乘法  对y_求导,等我用纸写一下,利用loss对K求梯度,去更新K的值,对B求梯度,求更新B的值
    #直到K和B基本拟合图像
    delta_K_sum=[]
    delta_B_sum=[]
    for i in range(len(X)):
        delta_K_sum.append((Y[i]-y_[i])*(-2)*X[i])
        delta_B_sum.append((Y[i]-y_[i])*(-2))
    delta_K=sum(delta_K_sum)/len(delta_K_sum)

    delta_B=sum(delta_B_sum)/len(delta_B_sum)
    #0.01是学习率,保证稳定收敛
    K=K-0.01*delta_K
    B=B-0.01*delta_B
    print(K,B)
print(K,B)

结果图像:

X=[i for i in range(0,15)]

Y=[K*i+B for i in X]

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

# 在同一个图形中绘制散点图和折线图
ax.scatter(X, Y, color='blue', label='scatter')
ax.plot(X, Y, color='red', label='line')

# 添加图例
ax.legend()

# 显示图形
plt.show()

猜你喜欢

转载自blog.csdn.net/qq_46644680/article/details/132437179