pytorch白话入门笔记1.9-CNN卷积神经网络

1.CNN卷积神经网络

(1)代码

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision      # 数据库模块
import matplotlib.pyplot as plt

torch.manual_seed(1)    # reproducible

# Hyper Parameters
EPOCH = 1           # 训练整批数据多少次, 为了节约时间, 我们只训练一次
BATCH_SIZE = 50
LR = 0.001          # 学习率
DOWNLOAD_MNIST = True  # 如果你已经下载好了mnist数据就写上 False


# Mnist 手写数字
train_data = torchvision.datasets.MNIST(
    root='./mnist/',    # 保存或者提取位置
    train=True,  # this is training data
    transform=torchvision.transforms.ToTensor(),    # 转换 PIL.Image or numpy.ndarray 成
                                                    # torch.FloatTensor (C x H x W), 训练的时候 normalize 成 [0.0, 1.0] 区间
    download=DOWNLOAD_MNIST,          # 没下载就下载, 下载了就不用再下了
)

#plot one example
print(train_data.train_data.size)
print(train_data.train_labels.size())
plt.imshow(train_data.train_data[0].numpy(),cmap='gray')
plt.title('%i'%train_data.train_labels[0])
plt.show()

(2)运行结果

torch.Size([60000])

Process finished with exit code 0

2.打印CNN

(1)代码

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision      # 数据库模块
import matplotlib.pyplot as plt
from torch.autograd import Variable

torch.manual_seed(1)    # reproducible

# Hyper Parameters
EPOCH = 1           # 训练整批数据多少次, 为了节约时间, 我们只训练一次
BATCH_SIZE = 50
LR = 0.001          # 学习率
DOWNLOAD_MNIST = False  # 如果你已经下载好了mnist数据就写上 False


# Mnist 手写数字
train_data = torchvision.datasets.MNIST(
    root='./mnist/',    # 保存或者提取位置
    train=True,  # this is training data
    transform=torchvision.transforms.ToTensor(),    # 转换 PIL.Image or numpy.ndarray 成
                                                    # torch.FloatTensor (C x H x W), 训练的时候 normalize 成 [0.0, 1.0] 区间
    download=DOWNLOAD_MNIST,          # 没下载就下载, 下载了就不用再下了
)

#plot one example
# print(train_data.train_data.size)
# print(train_data.train_labels.size())
# plt.imshow(train_data.train_data[0].numpy(),cmap='gray')
# plt.title('%i'%train_data.train_labels[0])
# plt.show()

train_loader = Data.DataLoader(dataset=train_data,batch_size=BATCH_SIZE,shuffle=True,num_workers=2)

test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)#意味着不是train_data,而是testdata

# # 批训练 50samples, 1 channel, 28x28 (50, 1, 28, 28)
# train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

# # 为了节约时间, 测试时只测试前2000个
test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000]/255.   # shape from (2000, 28, 28) to (2000, 1, 28, 28), value in range(0,1)
# test_x = Variable(torch.unsqueeze(test_data.test_data,dim=1),volatile=True).type(torch.FloatTensor)[:2000]/255.#运行不通
test_y = test_data.test_labels[:2000]


# 建立CNN神经网络
class CNN(nn.Module):
    def __init__(self):
        super(CNN,self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(  #(1,28,28)
                in_channels=1,#输入图片层灰度图1层,RGB3
                out_channels=16,#16个特征,即高度16
                kernel_size=5,#filter 长宽为5个像素点
                stride=1,#每隔多少像素跳动一下
                padding=2,#原始图片周围围上0,为了不丢失边缘数据
                #if strid = 1,padding = (kernel_size-1)/2 = (5-1)/2=2
                # wn+1=(wn+p*2-k)/s+1
            ),#卷积层——过滤器 filter ;(16,28,28)
            nn.ReLU(),#神经网络--非线性激活层
            nn.MaxPool2d(kernel_size=2),#池化层,若不池化,数据大,需stride>1;(16,14,14)
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(16,32,5,1,2),#(32,14,14)32= 28+2*2-5/1+1
            nn.ReLU(),#(32,14,14)
            nn.MaxPool2d(2)  #(32,7,7)
        )
        self.out = nn.Linear(32*7*7,10)

    def forward(self,x):
        x = self.conv1(x)
        x = self.conv2(x)#batch,32,7,7
        x = x.view(x.size(0),-1) #batch,32*7*7
        output=self.out(x)
        return output


cnn = CNN()
print(cnn)

(2)运行结果

CNN(
  (conv1): Sequential(
    (0): Conv2d(1, 16, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): ReLU()
    (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (conv2): Sequential(
    (0): Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): ReLU()
    (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (out): Linear(in_features=1568, out_features=10, bias=True)
)

Process finished with exit code 0

3.训练CNN

(1)代码

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision      # 数据库模块
import matplotlib.pyplot as plt
from torch.autograd import Variable

torch.manual_seed(1)    # reproducible

# Hyper Parameters
EPOCH = 1           # 训练整批数据多少次, 为了节约时间, 我们只训练一次
BATCH_SIZE = 50  # 批训练的数据个数
LR = 0.001          # 学习率
DOWNLOAD_MNIST = False  # 如果你已经下载好了mnist数据就写上 False


# Mnist 手写数字
train_data = torchvision.datasets.MNIST(
    root='./mnist/',    # 保存或者提取位置
    train=True,  # this is training data
    transform=torchvision.transforms.ToTensor(),    # 转换 PIL.Image or numpy.ndarray 成
                                                    # torch.FloatTensor (C x H x W), 训练的时候 normalize 成 [0.0, 1.0] 区间
    download=DOWNLOAD_MNIST,          # 没下载就下载, 下载了就不用再下了
)

#plot one example
# print(train_data.train_data.size)
# print(train_data.train_labels.size())
# plt.imshow(train_data.train_data[0].numpy(),cmap='gray')
# plt.title('%i'%train_data.train_labels[0])
# plt.show()

train_loader = Data.DataLoader(dataset=train_data,batch_size=BATCH_SIZE,shuffle=True)## num_workers=2,多线程来读数据 windows删除此行

test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)#意味着不是train_data,而是testdata

# # 批训练 50samples, 1 channel, 28x28 (50, 1, 28, 28)
# train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

# # 为节约时间, 测试前2000个
test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000]/255.   # shape from (2000, 28, 28) to (2000, 1, 28, 28), value in range(0,1)

test_y = test_data.test_labels[:2000]


# 建立CNN神经网络
class CNN(nn.Module):
    def __init__(self):
        super(CNN,self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(  #(1,28,28)
                in_channels=1,#输入图片层灰度图1层,RGB3
                out_channels=16,#16个特征,即高度16 filter
                kernel_size=5,#filter size 长宽为5个像素点
                stride=1,#每隔多少像素跳动一下
                padding=2,#原始图片周围围上0,为了不丢失边缘数据
                #if strid = 1,padding = (kernel_size-1)/2 = (5-1)/2=2
                # wn+1=(wn+p*2-k)/s+1
            ),#卷积层——过滤器 filter ;(16,28,28)
            nn.ReLU(),#神经网络--非线性激活层
            nn.MaxPool2d(kernel_size=2),#池化层,若不池化,数据大,需stride>1;(16,14,14)
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(16,32,5,1,2),#(32,14,14)32= 28+2*2-5/1+1
            nn.ReLU(),#(32,14,14)
            nn.MaxPool2d(2)  #(32,7,7)
        )
        self.out = nn.Linear(32*7*7,10)

    def forward(self,x):
        x = self.conv1(x)
        x = self.conv2(x)#batch,32,7,7
        x = x.view(x.size(0),-1) #batch,32*7*7
        output=self.out(x)
        return output,x


cnn = CNN()
print(cnn)

optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)   # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss()

# following function (plot_with_labels) is for visualization, can be ignored if not interested
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('Visualize last layer'); plt.show(); plt.pause(0.01)

plt.ion()
# training and testing
for epoch in range(EPOCH):
    for step, (b_x, b_y) in enumerate(train_loader):   # gives batch data, normalize x when iterate train_loader

        output = cnn(b_x)[0]               # cnn output
        loss = loss_func(output, b_y)   # cross entropy loss
        optimizer.zero_grad()           # clear gradients for this training step
        loss.backward()                 # backpropagation, compute gradients
        optimizer.step()                # apply gradients

        if step % 50 == 0:
            test_output, last_layer = cnn(test_x)
            pred_y = torch.max(test_output, 1)[1].data.numpy()
            accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size(0))
            print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
            if HAS_SK:
                # Visualization of trained flatten layer (T-SNE)
                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()

# print 10 predictions from test data
test_output, _ = cnn(test_x[:10])
pred_y = torch.max(test_output, 1)[1].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:10].numpy(), 'real number')

(2)运行结果

CNN(
  (conv1): Sequential(
    (0): Conv2d(1, 16, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): ReLU()
    (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (conv2): Sequential(
    (0): Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): ReLU()
    (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (out): Linear(in_features=1568, out_features=10, bias=True)
)
Epoch:  0 | train loss: 2.3105 | test accuracy: 0.06
Epoch:  0 | train loss: 0.6184 | test accuracy: 0.83
Epoch:  0 | train loss: 0.1290 | test accuracy: 0.87
Epoch:  0 | train loss: 0.2371 | test accuracy: 0.91
Epoch:  0 | train loss: 0.4058 | test accuracy: 0.93
Epoch:  0 | train loss: 0.0850 | test accuracy: 0.94
Epoch:  0 | train loss: 0.1956 | test accuracy: 0.94
Epoch:  0 | train loss: 0.1087 | test accuracy: 0.95
Epoch:  0 | train loss: 0.1238 | test accuracy: 0.96
Epoch:  0 | train loss: 0.0703 | test accuracy: 0.96
Epoch:  0 | train loss: 0.2217 | test accuracy: 0.96
Epoch:  0 | train loss: 0.2101 | test accuracy: 0.96
Epoch:  0 | train loss: 0.0237 | test accuracy: 0.97
Epoch:  0 | train loss: 0.0844 | test accuracy: 0.97
Epoch:  0 | train loss: 0.2158 | test accuracy: 0.97
Epoch:  0 | train loss: 0.1007 | test accuracy: 0.97
Epoch:  0 | train loss: 0.0433 | test accuracy: 0.97
Epoch:  0 | train loss: 0.0923 | test accuracy: 0.98
Epoch:  0 | train loss: 0.0564 | test accuracy: 0.98
Epoch:  0 | train loss: 0.1006 | test accuracy: 0.98
Epoch:  0 | train loss: 0.0320 | test accuracy: 0.98
Epoch:  0 | train loss: 0.0229 | test accuracy: 0.98
Epoch:  0 | train loss: 0.0233 | test accuracy: 0.98
Epoch:  0 | train loss: 0.1208 | test accuracy: 0.98
[7 2 1 0 4 1 4 9 5 9] prediction number
[7 2 1 0 4 1 4 9 5 9] real number

Process finished with exit code 0

原创文章 23 获赞 1 访问量 722

猜你喜欢

转载自blog.csdn.net/BSZJYAJ/article/details/105216714
今日推荐