基于梯度的学习
简单来说,它是一种通过计算损失函数的梯度来优化模型参数的方法。这种方法可以帮助我们找到损失函数的最小值,从而使模型在训练数据上达到更好的性能。梯度下降是一种优化算法,用于寻找函数的最小值。机器学习中,我们通常使用梯度下降来训练模型,使其更好地适应数据。通过不断地迭代和调整模型的参数,使得损失函数逐渐减少,最终找到最优解。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 
 | import torchimport torch.nn as nn
 import torch.optim as optim
 
 
 class SimpleModel(nn.Module):
 def __init__(self):
 super(SimpleModel, self).__init__()
 
 self.layer1 = nn.Linear(in_features=10, out_features=5)
 self.layer2 = nn.Linear(in_features=5, out_features=2)
 
 def forward(self, x):
 x = torch.relu(self.layer1(x))
 x = self.layer2(x)
 
 return x
 
 
 model = SimpleModel()
 
 
 criterion = nn.CrossEntropyLoss()
 optimizer = optim.SGD(model.parameters(), lr=0.01)
 
 
 inputs = torch.randn(64, 10)
 targets = torch.randint(0,2, (64,))
 
 
 ouputs = model(inputs)
 loss = criterion(ouputs, targets)
 
 
 optimizer.zero_grad()
 loss.backward()
 optimizer.step()
 
 print('Loss after backward propagation: ', loss.item())
 
 |