1.3神经网络
import torch
# 神经网络的包,仅支持小批量样本的训练,不支持单个样本(可以input.unsqueeze(0)来模拟批量[1])
import torch.nn as nn
import torch.nn.functional as F # 一些常用的函数
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 3) # 卷积核
self.conv2 = nn.Conv2d(6, 16, 3) # 卷积核
# Linear是简单的映射函数,第一个参数w的维度,第二个参数b的维度
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6是图片的长宽
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10) # 最后输出10个分类
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # 最大二维池化层:2*2格子内取最大
x = F.max_pool2d(F.relu(self.conv2(x)), 2) # 第一个参数的结果是笔直的向量
x = x.view(-1, self.num_flat_features(x)) # -1表示自动计算,view是改变形状
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x): # 每个输入变平后的数量大小
size = x.size()[1:] # 获得除了批量大小的所有维度
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net) # 获取当前模型的数据最后更新于
这有帮助吗?