莫烦pytorch教程的CNN代码的一些笔记

莫烦pytorch教程的CNN代码的一些旧版的修改

作为一个代码小白,最近在学习莫烦的pytorch教程,因为时间比较长了,有些地方需要做一些修改,写个日记记录下我的笔记。

导入包和数据预处理

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt

torch.manual_seed(1)
#超参数设置
EPOCH = 1
BATCH_SIZE = 50
LR = 0.001
DOWNLOAD_MNIST = False

train_data = torchvision.datasets.MNIST(
    root = './mnist',
    train=True,
    #mnist是灰度图像,把(0,255)转化成(0,1)
    transform=torchvision.transforms.ToTensor(), #
    download=DOWNLOAD_MNIST,
)

train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
#数据2000份足够了
test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000]/255.
test_y = test_data.test_labels[:2000]

可以用matplotlib去show MNIST手写集的数字,我这里就省略了,没啥必要,在网上可以可以查看到数据集的信息。

搭建神经网络

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,#filter的像素点5*5
                stride=1,
                padding=2, 
            ),                #image=16*28*28
            nn.ReLU(),
            nn.MaxPool2d(2),  #image=16*14*14
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(16,32,5,1,2),#image=32*14*14
            nn.ReLU(),
            nn.MaxPool2d(2)        #image=32*7*7
        )
        self.out = nn.Linear(32 * 7 * 7, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        #x作为可视化的输入,这句话的意思就是把卷积核的输出flatten为一行,50*(32*7*7)= 50*1568这样的形式
        x = x.view(x.size(0), -1)
        output = self.out(x)
        return output, x

cnn = CNN()
print(cnn)
optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)
loss_func = nn.CrossEntropyLoss()

做可视化

#可视化,把三维图像进行降维
from matplotlib import cm
try: from sklearn.manifold import TSNE; HAS_SK = True
except: HAS_SK = False; print('Please install sklearn for layer visualization')
def plot_with_labels(lowDWeights, labels):
    plt.cla()
    X, Y = lowDWeights[:,0], lowDWeights[:,1]
    for x, y ,s in zip(X, Y, labels):
       c = cm.rainbow(int(255 * s / 9))
       plt.text(x, y, s, backgroundcolor=c, fontsize=9)
    plt.xlim(X.min(), X.max())
    plt.ylim(Y.min(), Y.max())
    plt.title('可视化')
    plt.show() 
    plt.pause(0.01)
#把图变成交互式的
plt.ion()

训练和可视化输入

#训练和测试
for epoch in range(EPOCH):
    for step, (b_x,b_y) in enumerate(train_loader):
        #不加aux好像会把output变成tuple
        output, aux = cnn(b_x)
        #loss_func=nn.CrossEntropyLoss()的输入不能是tuple,巨坑。
        loss = loss_func(output, b_y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        #每训练100步测试一下
        if step % 100 == 0:
            test_output, last_layer = cnn(test_x)
            pred_y = torch.max(test_output, 1)[1].data.squeeze()
            accuracy = (pred_y == test_y).sum().item() / float(test_y.size(0))
            #loss.data[0]是旧版本的做法,要改成loss.item()
            print('Epoch: ', epoch, '| train loss: %.4f' % loss.item(), '| test accuracy: %.2f' % accuracy)
            if HAS_SK:
                tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
                plot_only = 500
                low_dim_embs = tsne.fit_transform(last_layer.data.numpy()[:plot_only, :])
                labels = test_y.numpy()[:plot_only]
                plot_with_labels(low_dim_embs, labels)
#要加上,不然图片不会停留
plt.ioff()

参考文献:
[1] https://github.com/MorvanZhou/PyTorch-Tutorial/blob/master/tutorial-contents-notebooks/401_CNN.ipynb

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页