目录

PyTorch-神经网络

PyTorch 神经网络

神经网络是一种模仿人脑神经元链接的计算模型, 由多层节点组成, 用于学习数据之间的复杂模式和关系。神经网络通过调整神经元之间的连接权重来优化预测结果,这个过程可以涉及到向前传播,损失计算,反向传播和参数更新。

PyTorch 提供了一个非常方便的接口来构建神经网络模型。这里记录下我的测试案例。

模型定义

创建了一个名为 SimpleNN 的神经网络类,继承自 nn.Module
网络结构包含两个全连接层:fc1(输入2维,输出2维)和 fc2(输入2维,输出1维),使用ReLU激活函数。


import torch.nn as nn
import torch.optim as optim
from sympy.printing.pytorch import torch


class SimpleNN(nn.Module):
    def __init__(self):
        super(SimpleNN, self).__init__()
        self.fc1 = nn.Linear(2,2)
        self.fc2 = nn.Linear(2,1)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

向前传播

实例化模型 model,生成随机输入数据 x(1个样本,2个特征), 通过 model(x) 执行前向传播,得到输出 output


model = SimpleNN()
print(model)

# 随机输入
x = torch.randn(1, 2)
print("\n随机输入:")
print(x)

# 前向传播
output = model(x)
print("\n前向传播结果:")
print(output)

损失计算

定义均方误差损失函数 MSELoss
生成随机目标值 target
计算模型输出与目标值之间的损失 loss


# 定义损失函数(例如均方误差 MSE)
criterion = nn.MSELoss()

# 假设目标值为 1
target = torch.randn(1, 1)
print("\n目标值:")
print(target)

# 计算损失
loss = criterion(output, target)
print("\n损失:")
print(loss)

执行结果

https://i-blog.csdnimg.cn/direct/ecf500e94a454fc1b1dbf2e7934b6b11.png