莫烦pytorch CNN卷积神经网络

不了解卷积神经网络的,看这篇:
一文教你读懂pytorch+CNN
莫烦pytorch 什么是卷积神经网络CNN(Convlutinoal Neural Network)

我们了解了卷积神经网络之后,开始用python实现该网络,并可视化训练数据。

MNIST手写数据

该数据是一个官方数据,数据中的图片都是手写的数字,这些数据就是我们训练cnn的数据。

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 = True

train_data = torchvision.datasets.MNIST(
	root='./MNIST',
	train=True,
	transform=torchvision.transforms.ToTensor(), #转换PIL.Image or numpy.ndarray 成 torch.FloatTensor(C x H x W),训练的时候normalize成[0.0, 1.0]区间
	download=DOWNLOAD_MNIST,
)

莫烦pytorch CNN卷积神经网络_第1张图片
黑色的地方的值都是0,白色的地方值大于0。

函数剖析:

class torchvision.transforms.ToTensor

把一个取值范围是[0, 255]的PIL.Image或者shape为(H, W, C)的numpy.ndarray,转换成形状为[C, H, W],取值范围是[0,1,0]的torch.FloadTensor
call(pic)
#参数:pic(PIL.Image or numpy.ndarray) - 图片转换张量
#返回结果 - 转换后的图像
#返回样式 - PIL.Image

class torchvision.tranforms.Normallize(mean, std)

给定均值:(R, G, B)方差:(R, G, B),将会把Tensor正则化。即:Normalized_iamge=(image-mean)/std.
参数说明:
#mean(sequence) - 序列R, G, B的均值。
#std(sequence) - 序列R, G, B的平均标准偏差

call(tensor)参数:tensor(Tensor) - 规范化的大小(c, h, w)的张量图像。返回结果:规范化的图片。返回样式:Tensor张量

dset.MNIST(root, train=True, tansform=None, target_transform=None, download=False)

参数说明:
#root - 数据集,存在于根目录processed/training.pt和processed/test.pt中
#train - True = 训练集, False = 测试集
#download - 如果为True,请从Internet下载数据集并将其放在根目录中。如果数据集已经下载,则不会再次下载。
#transform - 接受PIL映像并返回转换版本的函数/变换。例如:tranforms.RandomCrop
#target_transform - 一个接受目标并转换它的函数/变换.

同样,我们除了训练数据,还给了一些测试数据,测试看看它们有没有训练好。

test_data = torchvision.datasets.MNIST(root='./mnist', train=False)

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

test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:2000]/255
test_y = test_data.test_labels[:2000]

CNN模型

和以前一样,我们用一个class来建立CNN模型。这个CNN整体流程是
卷积(Conv2d) -> 激励函数(ReLU) -> 池化,向下采样(MaxPooling) -> 再来一遍 -> 展平多维的卷积成的特征图 -> 接入全连接层(Linear) -> 输出

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.RuLU(),
			nn.Maxpool2d(kernel_size=2),
		)
		self.output = nn.Linear(32 * 7 * 7, 10)
	def forward(self, x):
		out = self.conv1(x)
		out = self.conv2(out)
		out = out.view(out.size(0), -1) #展开多维的卷积图成(batch_size, 32 * 7 * 7)
		out = self.output(out)
		return out

cnn = CNN()
print(cnn)

结果:

"""
CNN (
  (conv1): Sequential (
    (0): Conv2d(1, 16, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): ReLU ()
    (2): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
  )
  (conv2): Sequential (
    (0): Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): ReLU ()
    (2): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
  )
  (out): Linear (1568 -> 10)
)
"""

函数剖析:

class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

二维卷积层,输入的尺度(N, C_in, H, W),输出尺度(N, C_out, W_out)的计算方式:
o u t ( N i , C o u t j ) = b i a s ( C o u t j ) + ∑ C i n − 1 k = 0 w e i g h t ( C o u t j , k ) ⨂ i n p u t ( N i , k ) out(Ni, C{outj})=bias(C{outj})+\sum^{C{in}-1}{k=0}weight(C{out_j},k)\bigotimes input(N_i,k) out(Ni,Coutj)=bias(Coutj)+Cin1k=0weight(Coutj,k)input(Ni,k)

说明
bigotimes: 表示二维的相关系数计算
stride: 控制相关系数的计算步长
dilation: 用于控制内核点之间的距离,详细描述在这里
groups: 控制输入和输出之间的连接:group=1,输出是所有的输入的卷积;group=2,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出时输出通道的一半,随后将这两个输出连接起来。

参数kernel_size, stride, padding, dilation也可以是一个int的数据,此时卷积height和width值相同;也可以是一个tuple数组,tuple的第一维度表示height的数值,tuple的第二维度表示width的数值

参数:
#in_channels(int) - 输入信号的通道数
#out_channels(int) - 卷积产生的通道数
#kerner_size(int or tuple) - 卷积核的大小
#stride(int or tuple, optional) - 卷积步长
#padding(int or tuple, optional) - 输入的每一条边补充0的层数
#output_padding(int or tuple, optional) - 输出的每一条边补充0的层数
#dilation(int, optional) - 卷积核元素之间的间距
#groups(int, optional) - 从输入通道到输出通道的阻塞连接数
#bias(bool, optional) - 如果bias=True, 添加偏置

shape:
input: (N,C_in,H_in,W_in)
output: (N,C_out,H_out,Wout)
H o u t = f l o o r ( ( H i n + 2 p a d d i n g [ 0 ] − d i l a t i o n [ 0 ] ( k e r n e r l s i z e [ 0 ] − 1 ) − 1 ) / s t r i d e [ 0 ] + 1 ) H{out}=floor((H_{in}+2padding[0]-dilation[0](kernerl_size[0]-1)-1)/stride[0]+1) Hout=floor((Hin+2padding[0]dilation[0](kernerlsize[0]1)1)/stride[0]+1)

W o u t = f l o o r ( ( W i n + 2 p a d d i n g [ 1 ] − d i l a t i o n [ 1 ] ( k e r n e r l s i z e [ 1 ] − 1 ) − 1 ) / s t r i d e [ 1 ] + 1 ) W{out}=floor((W{in}+2padding[1]-dilation[1](kernerl_size[1]-1)-1)/stride[1]+1) Wout=floor((Win+2padding[1]dilation[1](kernerlsize[1]1)1)/stride[1]+1)

变量:
#weight(tensor) - 卷积的权重,大小是(in_channels, in_channels, kernel_size)
#bias(tensor) - 卷积的偏置系数,大小是(out_channel)

example:

>>> # With square kernels and equal stride
>>> m = nn.Conv2d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
>>> # non-square kernels and unequal stride and with padding and dilation
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
>>> input = autograd.Variable(torch.randn(20, 16, 50, 100))
>>> output = m(input)
class torch.nn.MaxPool2d(kernel_size, stride=None, padding0, dilation=1, return_indices=False, ceil_mode=False)

对于输入信号的输入通道,提供2维最大池化操作
如果输入的大小是(N,C,H,W),那么输出的大小是(N,C,H_out,W_out)和池化窗口大小(kH, kW)的关系是:
o u t ( N i , C j , k ) = m a x k H − 1 m = 0 m a x k W − 1 m = 0 i n p u t ( N i , C j , s t r i d e [ 0 ] h + m , s t r i d e [ 1 ] w + n ) out(N_i, Cj,k)=max^{kH-1}{m=0}max^{kW-1}{m=0}input(N{i},C_j,stride[0]h+m,stride[1]w+n) out(Ni,Cj,k)=maxkH1m=0maxkW1m=0input(Ni,Cj,stride[0]h+m,stride[1]w+n)

如果padding不是0,会在输入的每一边添加相应数目0
dilation用于控制内核点之间的距离

参数kernel_size, stride, padding, dilation也可以是一个int的数据,此时卷积height和width值相同;也可以是一个tuple数组,tuple的第一维度表示height的数值,tuple的第二维度表示width的数值

参数:
#kernel_size(int or tuple) - max pooling的窗口大小
#stride(int or tuple, optional) - max pooling的窗口移动的步长。默认值是kernel_size
#padding(int or tuple, optional) - 输入的每一条边补充0的层数
#dilation(int or tuple, optional) - 一个控制窗口中元素步幅的参数
#return_indices - 如果等于True,会返回输出最大值的序号,对于上采样操作会有帮助
#ceil_mode - 如果True,计算出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

shape:
输入:(N, C, H_{in}, W_in)
输出:(N, C, H_out, Wout)
H o u t = f l o o r ( ( H i n + 2 p a d d i n g [ 0 ] − d i l a t i o n [ 0 ] ( k e r n e l s i z e [ 0 ] − 1 ) − 1 ) / s t r i d e [ 0 ] + 1 H{out}=floor((H_{in} + 2padding[0] - dilation[0](kernel_size[0] - 1) - 1)/stride[0] + 1 Hout=floor((Hin+2padding[0]dilation[0](kernelsize[0]1)1)/stride[0]+1

W o u t = f l o o r ( ( W i n + 2 p a d d i n g [ 1 ] − d i l a t i o n [ 1 ] ( k e r n e l s i z e [ 1 ] − 1 ) − 1 ) / s t r i d e [ 1 ] + 1 W{out}=floor((W{in} + 2padding[1] - dilation[1](kernel_size[1] - 1) - 1)/stride[1] + 1 Wout=floor((Win+2padding[1]dilation[1](kernelsize[1]1)1)/stride[1]+1

example:

>>> # pool of square window of size=3, stride=2
>>> m = nn.MaxPool2d(3, stride=2)
>>> # pool of non-square window
>>> m = nn.MaxPool2d((3, 2), stride=(2, 1))
>>> input = autograd.Variable(torch.randn(20, 16, 50, 32))
>>> output = m(input)

训练

下面我们开始训练,将x,y都用Variable包起来,然后放入cnn中计算output, 最后再计算误差。

optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)
loss_func = torch.nn.CrossEntropyLoss()
for epoch in range(EPOCH):
	for step, (b_x, b_y) in enumerate(train_loader):
		output = cnn(b_x)
		loss = loss_func(ouput, b_y)
		optimizer.zero_grad()
		loss.backward()
		optimizer.step()

结果:

"""
...
Epoch:  0 | train loss: 0.0306 | test accuracy: 0.97
Epoch:  0 | train loss: 0.0147 | test accuracy: 0.98
Epoch:  0 | train loss: 0.0427 | test accuracy: 0.98
Epoch:  0 | train loss: 0.0078 | test accuracy: 0.98
"""

最后我们再来取10个数据,看看预测的值到底对不对

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

结果:

"""
[7 2 1 0 4 1 4 9 5 9] prediction number
[7 2 1 0 4 1 4 9 5 9] real number
"""

全部代码:

import os

# third-party library
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               # train the training data n times, to save time, we just train 1 epoch
BATCH_SIZE = 50
LR = 0.001              # learning rate
DOWNLOAD_MNIST = False


# Mnist digits dataset
if not(os.path.exists('./mnist/')) or not os.listdir('./mnist/'):
    # not mnist dir or mnist is empyt dir
    DOWNLOAD_MNIST = True

train_data = torchvision.datasets.MNIST(
    root='./mnist/',
    train=True,                                     # this is training data
    transform=torchvision.transforms.ToTensor(),    # Converts a PIL.Image or numpy.ndarray to
                                                    # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
    download=DOWNLOAD_MNIST,
)

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

# Data Loader for easy mini-batch return in training, the image batch shape will be (50, 1, 28, 28)
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

# pick 2000 samples to speed up testing
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
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]


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,                  # if want same width and length of this image after Conv2d, padding=(kernel_size-1)/2 if stride=1
            ),                              # 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, x    # return x for visualization


cnn = CNN()
print(cnn)  # net architecture

optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)   # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss()                       # the target label is not one-hotted

# 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')

你可能感兴趣的:(pytorch)