梯度下降法预测weight以及bais,python版本

使用梯度下降法模拟预测线性函数y=ax^2+b,代码为python

import torch
import matplotlib.pyplot as plt

torch.manual_seed(1314)
t_weight,t_bais = 1,10
weight,bais =  torch.rand(2)

x_train = torch.linspace(0,5,1000)
y_train = t_weight*x_train**2 + t_bais + torch.randn(1000)*0.01

plt.plot(x_train,y_train)
plt.show()

lr = 0.001
print("true weight:%d true bais:%d"%(t_weight,t_bais))
print("origin weight:%.4f origin bais:%.4f"%(weight,bais))

min_epoch = -1
mini_loss = torch.inf
pred_weight = 0
pred_bais   = 0
loss = 0
nepoch=100
for epoch in range(nepoch):
    for index in range(len(x_train)):
        pred = weight*x_train[index]**2+bais
        loss = 1/2*(y_train[index]-pred)**2

        grad_weight = -(y_train[index]-pred)*(x_train[index])**2
        grad_bais   = -(y_train[index]-pred)

        weight-=lr*grad_weight
        bais-=lr*grad_bais
    if loss < mini_loss:
        mini_loss = loss
        min_epoch = epoch
        pred_weight = weight
        pred_bais   = bais
    print("loss:%5.5f min_loss:%5.5f"%(loss,mini_loss))
    print("epoch:%5d  min_epoch%5d"%(epoch,min_epoch))
    print("best-> weight:%5.3f bais:%5.3f"%(pred_weight,pred_bais))
    print("now--> weight:%5.3f bais:%5.3f"%(weight,bais))
    print("----------------------------------------")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值