阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
import torch
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
import math
from torch.utils.data.sampler import SubsetRandomSampler# Multi-Layer Perceptron Model
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.fc1 = nn.Linear(28*28, 500)
self.fc2 = nn.Linear(500, 256)
self.fc3 = nn.Linear(256, 10)
def forward(self, x):
x = x.view(-1, 28*28)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
MLP_network = MLP()# loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(MLP_network.parameters(), lr=0.001, betas=(0.9,0.99), eps=1e-08, weight_decay=0.001)# transforms to apply to the Fashion mnist data
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])
# Fashion MNIST dataset
fashion_trainset = datasets.FashionMNIST(root='./fmnist/', train=True, download=True, transform=transform)Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to ./fmnist/FashionMNIST\raw\train-images-idx3-ubyte.gz
0%| | 0/26421880 [00:00<?, ?it/s]
Extracting ./fmnist/FashionMNIST\raw\train-images-idx3-ubyte.gz to ./fmnist/FashionMNIST\raw
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz to ./fmnist/FashionMNIST\raw\train-labels-idx1-ubyte.gz
0%| | 0/29515 [00:00<?, ?it/s]
Extracting ./fmnist/FashionMNIST\raw\train-labels-idx1-ubyte.gz to ./fmnist/FashionMNIST\raw
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz to ./fmnist/FashionMNIST\raw\t10k-images-idx3-ubyte.gz
0%| | 0/4422102 [00:00<?, ?it/s]
Extracting ./fmnist/FashionMNIST\raw\t10k-images-idx3-ubyte.gz to ./fmnist/FashionMNIST\raw
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz to ./fmnist/FashionMNIST\raw\t10k-labels-idx1-ubyte.gz
0%| | 0/5148 [00:00<?, ?it/s]
Extracting ./fmnist/FashionMNIST\raw\t10k-labels-idx1-ubyte.gz to ./fmnist/FashionMNIST\raw
C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\torchvision\datasets\mnist.py:498: UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors. This means you can write to the underlying (supposedly non-writeable) NumPy array using the tensor. You may want to copy the array to protect its data or make it writeable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at ..\torch\csrc\utils\tensor_numpy.cpp:180.)
return torch.from_numpy(parsed.astype(m[2], copy=False)).view(*s)
labels_map = ('T-Shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt','Sneaker', 'Bag', 'Ankle Boot')
fig = plt.figure(figsize=(10,10));
columns = 4;
rows = 5;
for i in range(1, 10):
fig.add_subplot(rows, columns, i)
fig.tight_layout()
plt.imshow(fashion_trainset.train_data[i].numpy(), cmap='gray')
plt.title('Training Label : %s' % labels_map[fashion_trainset.train_labels[i]])
plt.show()C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\torchvision\datasets\mnist.py:62: UserWarning: train_data has been renamed data
warnings.warn("train_data has been renamed data")
C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\torchvision\datasets\mnist.py:52: UserWarning: train_labels has been renamed targets
warnings.warn("train_labels has been renamed targets")
<Figure size 720x720 with 9 Axes>
输出图整理: 原图为FashionMNIST九张样本照片,改为类别说明:T-shirt、Trouser、Pullover、Dress、Coat、Sandal、Shirt、Sneaker、Bag、Ankle Boot;不再分发来源照片。
num_train = len(fashion_trainset)
indices = list(range(num_train))
#Splitting the Dataset into 10% Training set and 90% Validation Set
split = 54000
# Random, non-contiguous split
validation_idx = np.random.choice(indices, size=split, replace=False)
train_idx = list(set(indices) - set(validation_idx))
# Contiguous split
# train_idx, validation_idx = indices[split:], indices[:split]
## define our samplers -- we use a SubsetRandomSampler because it will return
## a random subset of the split defined by the given indices without replaf
train_sampler = SubsetRandomSampler(train_idx)
validation_sampler = SubsetRandomSampler(validation_idx)
train_loader1 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=train_sampler)
validation_loader1 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=validation_sampler)整理注: 本实验有意使用10%训练、90%验证,随后增加训练占比;验证集不是独立测试集。
#MLP on 10% of the Training Dataset
num_epochs = 20
total_step = len(train_loader1)
Loss_f1 = []
print('----------------------------------------------------')
for epoch in range(num_epochs): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader1, 0):
# get the inputs
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = MLP_network(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
print('Epoch {} | Loss : {:.4f}'.format(epoch+1, running_loss / total_step))
print('----------------------------------------------------')
Loss_f1.append(running_loss / total_step)
print('Finished Training')----------------------------------------------------
Epoch 1 | Loss : 0.7003
----------------------------------------------------
Epoch 2 | Loss : 0.4997
----------------------------------------------------
Epoch 3 | Loss : 0.4574
----------------------------------------------------
Epoch 4 | Loss : 0.4232
----------------------------------------------------
Epoch 5 | Loss : 0.3852
----------------------------------------------------
Epoch 6 | Loss : 0.3520
----------------------------------------------------
Epoch 7 | Loss : 0.3376
----------------------------------------------------
Epoch 8 | Loss : 0.3230
----------------------------------------------------
Epoch 9 | Loss : 0.3080
----------------------------------------------------
Epoch 10 | Loss : 0.2947
----------------------------------------------------
Epoch 11 | Loss : 0.2842
----------------------------------------------------
Epoch 12 | Loss : 0.2790
----------------------------------------------------
Epoch 13 | Loss : 0.2680
----------------------------------------------------
Epoch 14 | Loss : 0.2539
----------------------------------------------------
Epoch 15 | Loss : 0.2419
----------------------------------------------------
Epoch 16 | Loss : 0.2414
----------------------------------------------------
Epoch 17 | Loss : 0.2481
----------------------------------------------------
Epoch 18 | Loss : 0.2261
----------------------------------------------------
Epoch 19 | Loss : 0.2207
----------------------------------------------------
Epoch 20 | Loss : 0.2177
----------------------------------------------------
Finished Training
#Accuracy of 90% of the Validation Test Dataset
correct = 0
total = 0
with torch.no_grad():
for data in validation_loader1:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 54000 test images: %d %%' % (100 * correct / total))Accuracy of the network on the 54000 test images: 83 %
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in validation_loader1:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(10):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of class %5s : %2d %%' % (
labels_map[i], 100 * class_correct[i] / class_total[i]))Accuracy of class T-Shirt : 90 %
Accuracy of class Trouser : 95 %
Accuracy of class Pullover : 81 %
Accuracy of class Dress : 88 %
Accuracy of class Coat : 79 %
Accuracy of class Sandal : 85 %
Accuracy of class Shirt : 37 %
Accuracy of class Sneaker : 96 %
Accuracy of class Bag : 93 %
Accuracy of class Ankle Boot : 87 %
num_train = len(fashion_trainset)
indices = list(range(num_train))
#Splitting the Dataset into 20% Training set and 80% Validation Set
split = 48000
# Random, non-contiguous split
validation_idx = np.random.choice(indices, size=split, replace=False)
train_idx = list(set(indices) - set(validation_idx))
# Contiguous split
# train_idx, validation_idx = indices[split:], indices[:split]
## define our samplers -- we use a SubsetRandomSampler because it will return
## a random subset of the split defined by the given indices without replaf
train_sampler = SubsetRandomSampler(train_idx)
validation_sampler = SubsetRandomSampler(validation_idx)
train_loader2 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=train_sampler)
validation_loader2 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=validation_sampler)#MLP on 20% of the Training Dataset
num_epochs = 20
total_step = len(train_loader2)
Loss_f2 = []
print('----------------------------------------------------')
for epoch in range(num_epochs): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader2, 0):
# get the inputs
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = MLP_network(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
print('Epoch {} | Loss : {:.4f}'.format(epoch+1, running_loss / total_step))
print('----------------------------------------------------')
Loss_f2.append(running_loss / total_step)
print('Finished Training')----------------------------------------------------
Epoch 1 | Loss : 0.4313
----------------------------------------------------
Epoch 2 | Loss : 0.3822
----------------------------------------------------
Epoch 3 | Loss : 0.3564
----------------------------------------------------
Epoch 4 | Loss : 0.3436
----------------------------------------------------
Epoch 5 | Loss : 0.3250
----------------------------------------------------
Epoch 6 | Loss : 0.3242
----------------------------------------------------
Epoch 7 | Loss : 0.3123
----------------------------------------------------
Epoch 8 | Loss : 0.3073
----------------------------------------------------
Epoch 9 | Loss : 0.2940
----------------------------------------------------
Epoch 10 | Loss : 0.2955
----------------------------------------------------
Epoch 11 | Loss : 0.2870
----------------------------------------------------
Epoch 12 | Loss : 0.2801
----------------------------------------------------
Epoch 13 | Loss : 0.2802
----------------------------------------------------
Epoch 14 | Loss : 0.2756
----------------------------------------------------
Epoch 15 | Loss : 0.2693
----------------------------------------------------
Epoch 16 | Loss : 0.2607
----------------------------------------------------
Epoch 17 | Loss : 0.2624
----------------------------------------------------
Epoch 18 | Loss : 0.2593
----------------------------------------------------
Epoch 19 | Loss : 0.2590
----------------------------------------------------
Epoch 20 | Loss : 0.2531
----------------------------------------------------
Finished Training
整理注: 原实验沿用同一模型与优化器继续训练,并非各训练比例从相同初始化独立重启,因此不能把曲线差异只归因于训练数据比例。保留历史曲线与日志。
#Accuracy of 80% of the Validation Test Dataset
correct = 0
total = 0
with torch.no_grad():
for data in validation_loader2:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 48000 test images: %d %%' % (100 * correct / total))Accuracy of the network on the 48000 test images: 86 %
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in validation_loader2:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(10):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of class %5s : %2d %%' % (
labels_map[i], 100 * class_correct[i] / class_total[i]))Accuracy of class T-Shirt : 81 %
Accuracy of class Trouser : 96 %
Accuracy of class Pullover : 70 %
Accuracy of class Dress : 87 %
Accuracy of class Coat : 82 %
Accuracy of class Sandal : 91 %
Accuracy of class Shirt : 69 %
Accuracy of class Sneaker : 95 %
Accuracy of class Bag : 96 %
Accuracy of class Ankle Boot : 91 %
num_train = len(fashion_trainset)
indices = list(range(num_train))
#Splitting the Dataset into 30% Training set and 70% Validation Set
split = 42000
# Random, non-contiguous split
validation_idx = np.random.choice(indices, size=split, replace=False)
train_idx = list(set(indices) - set(validation_idx))
# Contiguous split
# train_idx, validation_idx = indices[split:], indices[:split]
## define our samplers -- we use a SubsetRandomSampler because it will return
## a random subset of the split defined by the given indices without replaf
train_sampler = SubsetRandomSampler(train_idx)
validation_sampler = SubsetRandomSampler(validation_idx)
train_loader3 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=train_sampler)
validation_loader3 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=validation_sampler)#MLP on 30% of the Training Dataset
num_epochs = 20
total_step = len(train_loader3)
Loss_f3 = []
print('----------------------------------------------------')
for epoch in range(num_epochs): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader3, 0):
# get the inputs
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = MLP_network(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
print('Epoch {} | Loss : {:.4f}'.format(epoch+1, running_loss / total_step))
print('----------------------------------------------------')
Loss_f3.append(running_loss / total_step)
print('Finished Training')----------------------------------------------------
Epoch 1 | Loss : 0.3861
----------------------------------------------------
Epoch 2 | Loss : 0.3467
----------------------------------------------------
Epoch 3 | Loss : 0.3352
----------------------------------------------------
Epoch 4 | Loss : 0.3210
----------------------------------------------------
Epoch 5 | Loss : 0.3183
----------------------------------------------------
Epoch 6 | Loss : 0.3121
----------------------------------------------------
Epoch 7 | Loss : 0.3087
----------------------------------------------------
Epoch 8 | Loss : 0.3040
----------------------------------------------------
Epoch 9 | Loss : 0.3019
----------------------------------------------------
Epoch 10 | Loss : 0.2939
----------------------------------------------------
Epoch 11 | Loss : 0.2982
----------------------------------------------------
Epoch 12 | Loss : 0.2946
----------------------------------------------------
Epoch 13 | Loss : 0.2931
----------------------------------------------------
Epoch 14 | Loss : 0.2871
----------------------------------------------------
Epoch 15 | Loss : 0.2845
----------------------------------------------------
Epoch 16 | Loss : 0.2827
----------------------------------------------------
Epoch 17 | Loss : 0.2824
----------------------------------------------------
Epoch 18 | Loss : 0.2805
----------------------------------------------------
Epoch 19 | Loss : 0.2838
----------------------------------------------------
Epoch 20 | Loss : 0.2763
----------------------------------------------------
Finished Training
#Accuracy of 70% of the Validation Test Dataset
correct = 0
total = 0
with torch.no_grad():
for data in validation_loader3:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 42000 test images: %d %%' % (100 * correct / total))Accuracy of the network on the 42000 test images: 84 %
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in validation_loader3:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(10):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of class %5s : %2d %%' % (
labels_map[i], 100 * class_correct[i] / class_total[i]))Accuracy of class T-Shirt : 62 %
Accuracy of class Trouser : 95 %
Accuracy of class Pullover : 71 %
Accuracy of class Dress : 91 %
Accuracy of class Coat : 79 %
Accuracy of class Sandal : 95 %
Accuracy of class Shirt : 77 %
Accuracy of class Sneaker : 90 %
Accuracy of class Bag : 89 %
Accuracy of class Ankle Boot : 93 %
num_train = len(fashion_trainset)
indices = list(range(num_train))
#Splitting the Dataset into 40% Training set and 60% Validation Set
split = 36000
# Random, non-contiguous split
validation_idx = np.random.choice(indices, size=split, replace=False)
train_idx = list(set(indices) - set(validation_idx))
# Contiguous split
# train_idx, validation_idx = indices[split:], indices[:split]
## define our samplers -- we use a SubsetRandomSampler because it will return
## a random subset of the split defined by the given indices without replaf
train_sampler = SubsetRandomSampler(train_idx)
validation_sampler = SubsetRandomSampler(validation_idx)
train_loader4 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=train_sampler)
validation_loader4 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=validation_sampler)#MLP on 40% of the Training Dataset
num_epochs = 20
total_step = len(train_loader4)
Loss_f4 = []
print('----------------------------------------------------')
for epoch in range(num_epochs): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader4, 0):
# get the inputs
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = MLP_network(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
print('Epoch {} | Loss : {:.4f}'.format(epoch+1, running_loss / total_step))
print('----------------------------------------------------')
Loss_f4.append(running_loss / total_step)
print('Finished Training')----------------------------------------------------
Epoch 1 | Loss : 0.3688
----------------------------------------------------
Epoch 2 | Loss : 0.3451
----------------------------------------------------
Epoch 3 | Loss : 0.3302
----------------------------------------------------
Epoch 4 | Loss : 0.3281
----------------------------------------------------
Epoch 5 | Loss : 0.3233
----------------------------------------------------
Epoch 6 | Loss : 0.3196
----------------------------------------------------
Epoch 7 | Loss : 0.3139
----------------------------------------------------
Epoch 8 | Loss : 0.3108
----------------------------------------------------
Epoch 9 | Loss : 0.3144
----------------------------------------------------
Epoch 10 | Loss : 0.3111
----------------------------------------------------
Epoch 11 | Loss : 0.3057
----------------------------------------------------
Epoch 12 | Loss : 0.3061
----------------------------------------------------
Epoch 13 | Loss : 0.3078
----------------------------------------------------
Epoch 14 | Loss : 0.3076
----------------------------------------------------
Epoch 15 | Loss : 0.3022
----------------------------------------------------
Epoch 16 | Loss : 0.3041
----------------------------------------------------
Epoch 17 | Loss : 0.3016
----------------------------------------------------
Epoch 18 | Loss : 0.3008
----------------------------------------------------
Epoch 19 | Loss : 0.2997
----------------------------------------------------
Epoch 20 | Loss : 0.2950
----------------------------------------------------
Finished Training
#Accuracy of 60% of the Validation Test Dataset
correct = 0
total = 0
with torch.no_grad():
for data in validation_loader4:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 36000 test images: %d %%' % (100 * correct / total))Accuracy of the network on the 36000 test images: 85 %
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in validation_loader4:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(10):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of class %5s : %2d %%' % (
labels_map[i], 100 * class_correct[i] / class_total[i]))Accuracy of class T-Shirt : 71 %
Accuracy of class Trouser : 97 %
Accuracy of class Pullover : 56 %
Accuracy of class Dress : 88 %
Accuracy of class Coat : 85 %
Accuracy of class Sandal : 95 %
Accuracy of class Shirt : 80 %
Accuracy of class Sneaker : 84 %
Accuracy of class Bag : 94 %
Accuracy of class Ankle Boot : 97 %
num_train = len(fashion_trainset)
indices = list(range(num_train))
#Splitting the Dataset into 50% Training set and 50% Validation Set
split = 30000
# Random, non-contiguous split
validation_idx = np.random.choice(indices, size=split, replace=False)
train_idx = list(set(indices) - set(validation_idx))
# Contiguous split
# train_idx, validation_idx = indices[split:], indices[:split]
## define our samplers -- we use a SubsetRandomSampler because it will return
## a random subset of the split defined by the given indices without replaf
train_sampler = SubsetRandomSampler(train_idx)
validation_sampler = SubsetRandomSampler(validation_idx)
train_loader5 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=train_sampler)
validation_loader5 = torch.utils.data.DataLoader(fashion_trainset, batch_size=10, sampler=validation_sampler)#MLP on 50% of the Training Dataset
num_epochs = 20
total_step = len(train_loader5)
Loss_f5 = []
print('----------------------------------------------------')
for epoch in range(num_epochs): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader5, 0):
# get the inputs
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = MLP_network(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
print('Epoch {} | Loss : {:.4f}'.format(epoch+1, running_loss / total_step))
print('----------------------------------------------------')
Loss_f5.append(running_loss / total_step)
print('Finished Training')----------------------------------------------------
Epoch 1 | Loss : 0.3518
----------------------------------------------------
Epoch 2 | Loss : 0.3377
----------------------------------------------------
Epoch 3 | Loss : 0.3297
----------------------------------------------------
Epoch 4 | Loss : 0.3275
----------------------------------------------------
Epoch 5 | Loss : 0.3219
----------------------------------------------------
Epoch 6 | Loss : 0.3176
----------------------------------------------------
Epoch 7 | Loss : 0.3180
----------------------------------------------------
Epoch 8 | Loss : 0.3170
----------------------------------------------------
Epoch 9 | Loss : 0.3156
----------------------------------------------------
Epoch 10 | Loss : 0.3141
----------------------------------------------------
Epoch 11 | Loss : 0.3152
----------------------------------------------------
Epoch 12 | Loss : 0.3145
----------------------------------------------------
Epoch 13 | Loss : 0.3103
----------------------------------------------------
Epoch 14 | Loss : 0.3102
----------------------------------------------------
Epoch 15 | Loss : 0.3118
----------------------------------------------------
Epoch 16 | Loss : 0.3108
----------------------------------------------------
Epoch 17 | Loss : 0.3118
----------------------------------------------------
Epoch 18 | Loss : 0.3119
----------------------------------------------------
Epoch 19 | Loss : 0.3082
----------------------------------------------------
Epoch 20 | Loss : 0.3087
----------------------------------------------------
Finished Training
#Accuracy of 50% of the Validation Test Dataset
correct = 0
total = 0
with torch.no_grad():
for data in validation_loader5:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 30000 test images: %d %%' % (100 * correct / total))Accuracy of the network on the 30000 test images: 87 %
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in validation_loader5:
images, labels = data
outputs = MLP_network(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(10):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of class %5s : %2d %%' % (
labels_map[i], 100 * class_correct[i] / class_total[i]))Accuracy of class T-Shirt : 78 %
Accuracy of class Trouser : 96 %
Accuracy of class Pullover : 67 %
Accuracy of class Dress : 90 %
Accuracy of class Coat : 86 %
Accuracy of class Sandal : 92 %
Accuracy of class Shirt : 74 %
Accuracy of class Sneaker : 98 %
Accuracy of class Bag : 95 %
Accuracy of class Ankle Boot : 92 %
plt.plot(Loss_f1, 'r--', label = "10% Training Data")
plt.plot(Loss_f2, 'b--', label = "20% Training Data")
plt.plot(Loss_f3, 'y--', label = "30% Training Data")
plt.plot(Loss_f4, 'g--', label = "40% Training Data")
plt.plot(Loss_f5, 'k--', label = "50% Training Data")
plt.title("Loss vs Epoch for Fashion MNIST Dataset (using MLP)")
plt.xlim([0, num_epochs])
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()<Figure size 432x288 with 1 Axes>
输出图整理: 五条曲线分别记录10%到50%训练占比的loss;由于模型被沿用,曲线不构成独立对照实验。各段原训练日志保留,不生成虚构的替代曲线。