#encoding=utf8 import torch import torch.nn as nn from torch.autograd import Variable import torch.utils.data as Data import torchvision import os if os.path.exists('/data/workspace/course/step3/cnn.pkl'): os.remove('/data/workspace/course/step3/cnn.pkl') #加载数据 train_data = torchvision.datasets.MNIST( root='/data/workspace/course/step3/mnist', train=True, # this is training data transform=torchvision.transforms.ToTensor(), # Converts a PIL.Image or numpy.ndarray to download=False, ) #取6000个样本为训练集 train_data_tiny = [] for i in range(6000): train_data_tiny.append(train_data[i]) train_data = train_data_tiny #********* Begin *********# #********* End *********# #保存模型 torch.save(cnn.state_dict(), '/data/workspace/course/step3/cnn.pkl') 帮我补全Begin-End区域代码,实现使用pytorch搭建出卷积神经网络模型,再对模型进行训练
时间: 2023-06-27 09:02:12 浏览: 319
#encoding=utf8
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as Data
import torchvision
import os
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(
in_channels=1,
out_channels=16,
kernel_size=5,
stride=1,
padding=2,
),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
)
self.conv2 = nn.Sequential(
nn.Conv2d(16, 32, 5, 1, 2),
nn.ReLU(),
nn.MaxPool2d(2),
)
self.out = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0), -1)
output = self.out(x)
return output
#加载数据
train_data = torchvision.datasets.MNIST(
root='/data/workspace/course/step3/mnist',
train=True,
transform=torchvision.transforms.ToTensor(),
download=False,
)
#取6000个样本为训练集
train_data_tiny = []
for i in range(6000):
train_data_tiny.append(train_data[i])
train_data = train_data_tiny
#实例化CNN模型
cnn = CNN()
#定义损失函数
loss_func = nn.CrossEntropyLoss()
#定义优化器
optimizer = torch.optim.Adam(cnn.parameters(), lr=0.01)
#定义数据加载器
train_loader = Data.DataLoader(dataset=train_data, batch_size=64, shuffle=True)
#开始训练
for epoch in range(10):
for step, (x, y) in enumerate(train_loader):
b_x = Variable(x)
b_y = Variable(y)
output = cnn(b_x)
loss = loss_func(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step % 50 == 0:
test_output = cnn(torch.unsqueeze(train_data_tiny[0][0], dim=0))
pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()
accuracy = sum(pred_y == train_data_tiny[0][1]) / float(train_data_tiny[0][1].shape[0])
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
#保存模型
torch.save(cnn.state_dict(), '/data/workspace/course/step3/cnn.pkl')
阅读全文