第三讲 梯度下降

#准备训练集数据
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
#设初始权重为1
w = 1.0
#定义模型
def forward(x):
    return x * w
#定义均方差
def cost(xs,ys):
    #设初始均方差为0
    cost = 0
    #用zip拼装送给x,y
    for x,y in zip(xs,ys):
        #计算y的预测值
        y_pred = forward(x)
        #计算方差的和
        cost += (y_pred - y) ** 2
    #方差和除以样本数求出均方差
    return cost / len(xs)

#定义梯度
def gradient(xs,ys):
    #设初始梯度为0
    grad = 0
    #用zip拼装送给x,y
    for x,y in zip(xs,ys):
        #先用梯度公式,再求和
        grad += 2 * x * (x * w - y)
    #梯度和除以样本数求出梯度
    return grad / len(xs)

#输出训练之前预测x=4,y=4
print('Predict (before training)',4,forward(4))
#设循环次数为100次
for epoch in range(100):
    #计算均方差
    cost_val = cost(x_data,y_data)
    #计算梯度
    grad_val = gradient(x_data,y_data)
    #计算权重w,w=w-学习率*梯度
    w -= 0.01 * grad_val
    #输出循环次数,权重,损失
    print('Epoch:',epoch,'w=',w,'loss=',cost_val)
#输出训练后预测x=4,y=4
print('Predict (after training)',4,forward(4))

猜你喜欢

转载自blog.csdn.net/m0_46166352/article/details/114271265