梯度下降是机器学习以及深度学习最常用的方法,通过对二元线性回归模型预测进行预测模拟批量梯度下降的过程
代码如下:
#导包
import numpy as np
#随即构造真实值
X=np.random.randn(20,2)
w=np.random.randint(1,10,size=(2,1))
b=np.random.randint(1,10,size=1)
y=X.dot(w)+b+np.random.randn(20,1)
print('真实值为:',y)
#使用批量梯度下降算法
X1=np.concatenate([X,np.ones((20,1))],axis=1) #重新构造X,置偏置项即包含截距的系数
#迭代次数
epoches=10000
#调整学习率
t0,t1=5,1000
def learning_rate_schedule(t):
return t0/(t+t1)
#随机给theta赋初值
theta=np.random.randn(3,1)
for i in range(epoches):
#计算梯度
g=X1.T.dot(X1.dot(theta)-y)
#更新theta
eta=learning_rate_schedule(i)
theta=theta-eta*g
print('通过批量梯度下降算法计算的斜率和截距分别为:',theta)
print('通过批量梯度下降算法计算的预测值为:',X1.dot(theta))
Python实现批量梯度下降
于 2022-03-31 22:14:39 首次发布