一、网络构建
import torch#导入PyTorch库。它提供了张量操作、自动微分等基础功能。
import torch.nn as nn#定义神经网络层 这个模块包含了构建神经网络所需的各种层和函数。
class SimpleNN(nn.Module):#这里定义了一个名为 SimpleNN 的新类,它继承自 nn.Module。在PyTorch中,所有的神经网络模型都应继承自 nn.Module,这样可以利用到该基类中的很多功能,如参数管理和模块化。
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(784, 128) #784个输入特征的数量
self.fc2 = nn.Linear(128, 128) #128个(可以使用不同数量的单元)隐藏单元
self.output = nn.Linear(128, 10) #self.output 是输出层,接收来自上一层的128个特征的输出,并将其映射到10个输出,通常表示分类任务中的类别数量。
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))#通过ReLU激活函数进行非线性变换。
x = self.output(x)
return x
device = torch.device('cuda' if torch.cu