sys.path.append(os.pardir) import os import sys import numpy as np from dataset.mnist import load_mnist from PIL import Image def img_show(img): pil_img = Image.fromarray(np.uint8(img)) pil_img.show() (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False) img = x_train[0] label = t_train[0] print(label) print(img.shape)#784 img = img.reshape(28, 28)#把图像形状变为原来的尺寸 print(img.shape)#(28,28) img_show(img)
时间: 2023-05-11 17:03:50 浏览: 176
这段代码的作用是导入需要的模块和数据集,然后定义了一个函数img_show用于显示图像。load_mnist函数用于加载MNIST数据集,其中flatten=True表示将图像展开成一维数组,normalize=False表示不对图像进行归一化处理。接着从训练集中取出第一张图像和对应的标签,并打印出来。最后,调用img_show函数显示图像。
相关问题
#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区域代码
# 定义卷积神经网络模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential( # input shape (1, 28, 28)
nn.Conv2d(
in_channels=1, # input height
out_channels=16, # n_filters
kernel_size=5, # filter size
stride=1, # filter movement/step
padding=2,
), # output shape (16, 28, 28)
nn.ReLU(), # activation
nn.MaxPool2d(kernel_size=2), # choose max value in 2x2 area, output shape (16, 14, 14)
)
self.conv2 = nn.Sequential( # input shape (16, 14, 14)
nn.Conv2d(16, 32, 5, 1, 2), # output shape (32, 14, 14)
nn.ReLU(), # activation
nn.MaxPool2d(2), # output shape (32, 7, 7)
)
self.out = nn.Linear(32 * 7 * 7, 10) # fully connected layer, output 10 classes
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0), -1) # flatten the output of conv2 to (batch_size, 32 * 7 * 7)
output = self.out(x)
return output
# 实例化卷积神经网络模型
cnn = CNN()
# 定义损失函数和优化器
loss_func = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(cnn.parameters(), lr=0.001)
# 定义数据集和数据加载器
train_loader = Data.DataLoader(dataset=train_data, batch_size=64, shuffle=True)
# 训练模型
for epoch in range(1):
for step, (x, y) in enumerate(train_loader):
b_x = Variable(x) # batch x
b_y = Variable(y) # batch y
output = cnn(b_x)
loss = loss_func(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step % 100 == 0:
test_output = cnn(torch.unsqueeze(train_data_tiny[0][0], dim=0))
pred_y = torch.max(test_output, 1)[1].data.squeeze()
accuracy = sum(pred_y == train_data_tiny[0][1]) / float(train_data_tiny[0][1].size)
print('Epoch:', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
# 保存模型
torch.save(cnn.state_dict(), '/data/workspace/course/step3/cnn.pkl')
阅读全文
相关推荐










