PyTorch深度学习实践(四)---反向传播
(1)Tensor包含data 和 grad
w.data
w.grad.data:数值计算,不构建计算图。
w.grad.item():取出数值。
w.grad.data.zero():清零
(2)w是tensor类型,data和grad也是tensor类型,注意取值时不可直接取成张量
(3)反向传播代码:
1# 2 import torch 3 4 #y=2x 5 x_data=[1.0,2.0,3.0,4.0] 6 y_data=[2.0,4.0,6.0,8.0] 7 8 w=torch.Tensor([1.0]) #tensor类型 9 w.requires_grad=True #需要计算梯度,则设为true 10 11 def forward(x): 12 return w*x #以为w是tensor类型,x自动转化为tensor,返回为tensor类型 13 14 def loss(x,y): #构建计算图 15 y_pred=forward(x) 16 return (y_pred-y)**2 17 18 for epoch in range(100): 19 for x,y in zip(x_data,y_data): 20 l=loss(x,y) #l也是tensor类型 21 l.backward() #反向传播计算梯度 22 print("\t",x,y,w.grad.item()) #取得是grad的值 23 w.data=w.data-0.01*w.grad.data #取grad的值 24 w.grad.data.zero_() #释放之前计算的梯度 25 print("epoch:",epoch,"loss:",l.item())
(4)y=w1*x+w2*x+b
1 # 2 import torch 3 4 x_data=[1.0,2.0,3.0] 5 y_data=[2.0,4.0,6.0] 6 7 #y 8 w1=torch.Tensor([1.0]) 9 w1.requires_grad=True 10 w2=torch.Tensor([1.0]) 11 w2.requires_grad=True 12 b=torch.Tensor([1.0]) 13 b.requires_grad=True 14 15 def forward(x): 16 return w1*x+w2*x+b 17 18 def loss(x,y): 19 y_pred=forward(x) 20 return (y_pred-y)**2 21 22 for epoch in range(100): 23 for x,y in zip(x_data,y_data): 24 l=loss(x,y) 25 l.backward() 26 print("\t",x,y,w1.grad.item(),w2.grad.item(),b.grad.item()) 27 w1.data-=0.01*w1.grad.data 28 w1.grad.data.zero_() 29 w2.data-=0.01*w2.grad.data 30 w2.grad.data.zero_() 31 b.data-=0.01*b.grad.data 32 b.grad.data.zero_() 33 print('Epoch:', epoch, l.item())