pytorch梯度下降函数_pytorch入门2:梯度下降算法

原理:

通过梯度下降算法,求解loss的最小值,设置好初始w权重值,不断进行迭代,最后得到最小的loss值

代码:

# Training Data

x_data = [1.0, 2.0, 3.0]

y_data = [2.0, 4.0, 6.0]

w = 1.0 # a random guess: random value

# our model forward pass

def forward(x):

return x * w

# Loss function

def loss(x, y):

y_pred = forward(x)

return (y_pred - y) * (y_pred - y)

# compute gradient

def gradient(x, y): # d_loss/d_w

return 2 * x * (x * w - y)

# Before training

print("Prediction (before training)", 4, forward(4))

# Training loop

for epoch in range(10):

for x_val, y_val in zip(x_data, y_data):

# Compute derivative w.r.t to the learned weights

# Update the weights

# Compute the loss and print progress

grad = gradient(x_val, y_val)

w = w - 0.01 * grad

print("\tgrad: ", x_val, y_val, round(grad, 2))

l = loss(x_val, y_val)

print("progress:", epoch, "w=", round(w, 2), "loss=", round(l, 2))

# After training

print("Predicted score (after training)", "4 hours of studying: ", forward(4))

知识点:

a为学习率,设置为0.01

迭代过程:

运行结果:

大概比起生活的艰辛,我更怕的是,好不容易来这世间走一趟,却把唯一一次的生命,按照别人的意愿,活成了别人的人生。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值