前馈神经网络
简单来说,它是一种模仿人脑神经元结构的计算模型,可以用于解决各种复杂的问题,如图像识别、自然语言处理等。前馈神经网络的工作原理是搭建多级决策流程:输入层接收到数据后,通过隐藏层进行特征提取和转换,最终输出层生成预测结果。这个过程每一层都充满了无限潜能与可能。
1 2 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 40
| import torch import 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.relu = nn.ReLU() 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())
|