基于PyTorch,如何构建一个简单的神经网络
建立神经网络
import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
加载训练设备
device = 'cuda' if torch.cuda.is_available() else 'cpu' #检测gpu是否可用,不可用使用cpu
print('Using {} device'.format(device)) #输出使用设备类型
定义类
class NeuralNetwork(nn.Module):
def __init__(self): #定义网络结构
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
nn.ReLU()
)
def forward(self, x): #前向传播
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork().to(device) #实例化模型
print(model)
X = torch.rand(1, 28, 28, device=device) #生成(1,28,28)的数据
logits = model(X) #向模型输入数据
pred_probab = nn.Softmax(dim=1)(logits) #调用softmax 将预测值映射为(0,1)间的概率
y_pred = pred_probab.argmax(1) #最大概率对应分类
print(f"Predicted class: {y_pred}")
神经网络各层说明
input_image = torch.rand(3,28,28) #生成(3,28,28)的数据
print(input_image.size())
nn.Flatten 层
flatten = nn.Flatten()
flat_image = flatten(input_image) #(3,28,28)转换为(3,784)
print(flat_image.size())
nn.Linear 层
layer1 = nn.Linear(in_features=28*28, out_features=20) #输入(3,28*28) 输出(3,20)
hidden1 = layer1(flat_image)
print(hidden1.size())
nn.ReLU 层
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
nn.Sequential 层
softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
输出模型结构
print("Model structure: ", model, "\n\n")
for name, param in model.named_parameters():
print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")

关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 总书记深情寄望电影工作者 7904824
- 2 高考604分女生被一所高职录取 7809187
- 3 山东一地凌晨数十人蒙眼列队湖边走 7711853
- 4 气温预报图肉眼可见变热了 7617553
- 5 越来越多空姐不用穿高跟鞋 7522709
- 6 孙颖莎王曼昱无缘女双冠军 7424436
- 7 误删微信聊天记录可以撤销了 7328286
- 8 蔡国庆点评19岁选手怼了4分钟 7235270
- 9 庞麦郎演唱会来了约400名听众 7140755
- 10 国足对阵日本现场观众仅1661人 7046222