这个代码实现了预测和可视化
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() # reproducible # Hyper Parameters
EPOCH = # train the training data n times, to save time, we just train epoch
BATCH_SIZE =
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(), # 把数据压缩到0到1之间的numpy数据
# 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()) # (, , )
print(train_data.train_labels.size()) # ()
plt.imshow(train_data.train_data[].numpy(), cmap='gray')
plt.title('%i' % train_data.train_labels[])
plt.show() # Data Loader for easy mini-batch return in training, the image batch shape will be (, , , )
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True) # pick samples to speed up testing
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
test_x = torch.unsqueeze(test_data.test_data, dim=).type(torch.FloatTensor)[:]/. # shape from (, , ) to (, , , ), value in range(,)
test_y = test_data.test_labels[:] class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential( # input shape (, , )
nn.Conv2d(
in_channels=, # input height
out_channels=, # n_filters
kernel_size=, # filter size
stride=, # filter movement/step
padding=, # if want same width and length of this image after Conv2d, padding=(kernel_size-)/ if stride=
), # output shape (, , )
nn.ReLU(), # activation
nn.MaxPool2d(kernel_size=), # choose max value in 2x2 area, output shape (, , )
)
self.conv2 = nn.Sequential( # input shape (, , )
nn.Conv2d(, , , , ), # output shape (, , )
nn.ReLU(), # activation
nn.MaxPool2d(), # output shape (, , )
)
self.out = nn.Linear( * * , ) # fully connected layer, output classes def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(), -) # flatten the output of conv2 to (batch_size, * * )
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[:, ], lowDWeights[:, ]
for x, y, s in zip(X, Y, labels):
c = cm.rainbow(int( * s / )); plt.text(x, y, s, backgroundcolor=c, fontsize=)
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)[] # 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 % == :
test_output, last_layer = cnn(test_x)
pred_y = torch.max(test_output, )[].data.numpy()
accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size())
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=, n_components=, init='pca', n_iter=)
plot_only =
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 predictions from test data
test_output, _ = cnn(test_x[:])
pred_y = torch.max(test_output, )[].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:].numpy(), '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 EPOCH = # train the training data n times, to save time, we just train epoch
BATCH_SIZE =
LR = 0.001 # learning rate train_data = torchvision.datasets.MNIST(
root='./mnist/', #下载后的存放目录
train=True, # this is training data
transform=torchvision.transforms.ToTensor(), # 把数据压缩到0到1之间的numpy数据,如果原始数据是rgb数据(-)则变为黑白数据,并使numpy数据变为tensor数据 # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
download=True#不存在该数据就设置为True进行下载,存在则改为False
) # plot one example
print(train_data.train_data.size()) # (, , ),六万图片
print(train_data.train_labels.size()) # (),六万标签
plt.imshow(train_data.train_data[].numpy(), cmap='gray')#展现第一个训练数据图片
plt.title('%i' % train_data.train_labels[])
plt.show() # Data Loader for easy mini-batch return in training, the image batch shape will be (, , , )
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True) # pick samples to speed up testing
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
test_x = torch.unsqueeze(test_data.test_data, dim=).type(torch.FloatTensor)[:]/. # shape from (, , ) to (, , , ), value in range(,)
test_y = test_data.test_labels[:] class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential( # input shape (, , ),考虑batch是(batch,,,)
nn.Conv2d(
in_channels=, # input height
out_channels=, # n_filters
kernel_size=, # filter size
stride=, # filter movement/step
padding=, # if want same width and length of this image after Conv2d, padding=(kernel_size-)/ if stride=
), # output shape (, , )
nn.ReLU(), # activation
nn.MaxPool2d(kernel_size=), # choose max value in 2x2 area, output shape (, , )
)
self.conv2 = nn.Sequential( # input shape (, , )
nn.Conv2d(, , , , ), # output shape (, , )
nn.ReLU(), # activation
nn.MaxPool2d(), # output shape (, , )
)
self.out = nn.Linear( * * , ) # fully connected layer, output classes def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(), -) # flatten the output of conv2 to (batch_size, * * ),只有tensor对象才可以使用x.size()
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 # 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)[] # 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 % == :
test_output = cnn(test_x)[]
print("----------------")
#print(test_output.shape) #*
#print(torch.max(test_output, )) #返回的每一行中最大值和其下标
pred_y = torch.max(test_output, )[].data.numpy() #返回的是每个样本对应0-9数字可能性最大的概率对应的下标
accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size())
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy) # print predictions from test data
test_output, _ = cnn(test_x[:])
pred_y = torch.max(test_output, )[].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:].numpy(), 'real number')