Python神经网络搭建示例 - PyTorch入门
当然可以为您提供一个简单的神经网络的搭建代码示例,以下是一个基于Python和PyTorch的简单神经网络的搭建示例:
import torch
import torch.nn as nn
# 定义神经网络模型
class SimpleNet(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
# 设置参数
input_size = 784 # 输入大小,即MNIST手写数字的像素数量
hidden_size = 500 # 隐藏层大小
num_classes = 10 # 类别数量,即0-9的数字
# 实例化模型
model = SimpleNet(input_size, hidden_size, num_classes)
# 打印模型结构
print(model)
# 输入数据
input_data = torch.randn(1, input_size) # 生成一个随机输入数据
# 使用模型进行预测
output = model(input_data)
print(output)
这个示例中,'SimpleNet'定义了一个简单的神经网络模型,包含一个线性层和一个ReLU激活函数,最后输出层为线性层。'forward'方法定义了模型的前向传播过程。然后,我们实例化了这个模型,并使用随机生成的输入数据进行了预测。
希望这个示例能帮助到您,如果您有其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/qmMQ 著作权归作者所有。请勿转载和采集!