首页 > 其他分享 >pytorch 简简单单求个值

pytorch 简简单单求个值

时间:2022-10-08 19:34:15浏览次数:36  
标签:loss tensor tt torch det 简简单单 pytorch 求个值 grad

能用张量处理就用张量,不要使用for in 跑循环,一个是容易出错,一个是比较浪费时间,应用广播机制的话去做很容易的
1.5
使用mean处理平均值
2.
在处理梯度的时候无法更改自身,因此使用的办法是with
一个简单的例子:
import torch as tt

x=tt.tensor(range(20))

y=x+3

w=tt.tensor([1.0],requires_grad=True)

b=tt.tensor([1.0],requires_grad=True)

def loss_fn(x,y,w,b):
det=0.5(y-wx-b)**2
det=det.mean()
return det

def training_loop(n_epochs, learning_rate, w,b,x, y):
for epoch in range(1, n_epochs + 1):
if w.grad is not None:
w.grad.zero_()
b.grad.zero_()
y=w*x+b
loss = loss_fn(x,y,w,b)
loss.backward()
with torch.no_grad():
w -= learning_rate * w.grad
return w,b
training_loop(10,1e-2,w,b,x,y)

这里的with是切换上下文,后面的torch.no_grad()是强制断图,在需要对叶子节点本身进行修改的时候使用

标签:loss,tensor,tt,torch,det,简简单单,pytorch,求个值,grad
From: https://www.cnblogs.com/mitudesk/p/16769923.html

相关文章