B站刘二大人老师的《PyTorch深度学习实践》Lecture_05 重点回顾+代码复现
import torch
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[2.0], [4.0], [6.0]])
Our model class should be inherit from nn.Module, which is Base class for all neural network modules.
Class nn.Linear has implemented the magic method __call__(), which enable the instance of the class can be called just like a function. Normally the forward() will be called.
class LinearModel(torch.nn.Module):
# Member methods __init__() and forward() have to be implemented.
def __init__(self):
super(LinearModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
# torch.nn.Linear(in_features: int, out_features: int, bias: bool = True)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
model = LinearModel()
class Foobar:
def __init__(self):
pass
def __call__(self,*args,**kwargs):
pass
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
torch.nn.MSELoss(size_average=None, reduce=None, reduction: str = ‘mean’)
torch.optim.SGD(params, lr=, momentum=0, dampening=0, weight_decay=0, nesterov=False)
三个阶段:forward、backward、Update
for epoch in range(50):
# forward
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
print(epoch,loss.item())
# 梯度清零
optimizer.zero_grad()
# backward
loss.backward()
# Update
optimizer.step()
NOTICE:
The grad computed by .backward() will be accumulated. So before backward, remember set the grad to ZERO!!!
import torch
# Prepare dataset
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[2.0],[4.0],[6.0]])
# Design Model
class LinearModel(torch.nn.Module):
def __init__(self):#构造函数
super(LinearModel,self).__init__()
self.linear = torch.nn.Linear(1,1)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
model = LinearModel()
# Construct Loss & Optimizer
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
# Training Cycle
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
print(epoch,loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Test Model
print('w = ',model.linear.weight.item())
print('b = ',model.linear.bias.item())
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)