mnist 數據集是一個非常出名的數據集,基本上很多網絡都將其作爲一個測試的標準,其來自美國國家標準與技術研究所, National Institute of Standards and Technology (NIST)。 訓練集 (training set) 由來自 250 個不同人手寫的數字構成, 其中 50% 是高中學生, 50% 來自人口普查局 (the Census Bureau) 的工作人員,一共有 60000 張圖片。 測試集(test set) 也是同樣比例的手寫數字數據,一共有 10000 張圖片。
每張圖片大小是 28 x 28 的灰度圖:
完整代碼在:GitHub 一共4個文件
MNIST.py 是主函數
net.py 裏面定義了3種網絡,訓練的時候選擇其中一種
readpic.py 用於讀取圖片,看看能否識別出來
3.jpg 就是自己用畫圖手寫的一個數字和28*28差不多大
net.py 代碼:
import torch
import torch.nn as nn
class simpleNet(nn.Module):
"""
簡單的三層全連接神經網絡
"""
def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):
super(simpleNet, self).__init__()
self.layer1 = nn.Linear(in_dim, n_hidden_1)
self.layer2 = nn.Linear(n_hidden_1, n_hidden_2)
self.layer3 = nn.Linear(n_hidden_2, out_dim)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
class Activation_Net(nn.Module):
"""
添加激活函數增加網絡的非線性
"""
def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):
super(Activation_Net, self).__init__()
"""
nn.Sequential() 將nn.Linear()和nn.ReLU()組合到一起
"""
self.layer1 = nn.Sequential(nn.Linear(in_dim, n_hidden_1), nn.ReLU(True))
self.layer2 = nn.Sequential(nn.Linear(n_hidden_1, n_hidden_2), nn.ReLU(True))
self.layer3 = nn.Sequential(nn.Linear(n_hidden_2, out_dim))
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
class Batch_Net(nn.Module):
"""
添加批標準化,批標準化一般放在全連接層後面,激活層前面
"""
def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):
super(Batch_Net, self).__init__()
self.layer1 = nn.Sequential(nn.Linear(in_dim, n_hidden_1), nn.BatchNorm1d(n_hidden_1), nn.ReLU(True))
self.layer2 = nn.Sequential(nn.Linear(n_hidden_1, n_hidden_2), nn.BatchNorm1d(n_hidden_2), nn.ReLU(True))
self.layer3 = nn.Sequential(nn.Linear(n_hidden_2, out_dim))
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
MNIST.py 代碼:
- 定義一些超參數和對數據的處理:
# hyperparameters
batch_size = 64*2
learning_rate = 1e-2
num_epoches = 20
data_tf = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])]
)
transforms.Compose()是將各種預處理操作組合在一起
transforms.ToTensor():將圖片轉成Tensor,同時標準化,所以範圍爲0-1
transforms.Normalize():需要傳入兩個參數:第一個是均值,第二個是方差,將數據減均值,再除以方差
相當於:
def data_tf(x):
x = np.array(x, dtype='float32') / 255 # 放到0-1之間
x = (x - 0.5) / 0.5
x = torch.from_numpy(x)
return x
- 然後讀取數據集:
train_dataset = datasets.MNIST(root='./data', train=True, transform=data_tf, download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=data_tf)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
關於dataset和DataLoader使用教程參考:https://www.jianshu.com/p/8ea7fba72673
- 接着導入網絡,定義loss函數和優化方法:
model = net.Batch_Net(28*28, 300, 100, 10)
if torch.cuda.is_available():
model = model.cuda()
# 定義loss函數和優化方法
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
因爲是多分類所以使用 nn.CrossEntropyLoss()
nn.BCELoss是二分類的損失函數
- 開始訓練並在測試集上檢驗結果:
for epoch in range(num_epoches):
model.train()
for data in train_loader: # 每次取一個batch_size張圖片
img, label = data # img.size:128*1*28*28
img = img.view(img.size(0), -1) # 展開成128 *784(28*28)
if torch.cuda.is_available():
img = img.cuda()
label = label.cuda()
output = model(img)
loss = loss_fn(output, label)
# 反向傳播
optimizer.zero_grad()
loss.backward()
optimizer.step()
# print('epoch:', epoch, '|loss:', loss.item())
# 在測試集上檢驗效果
model.eval() # 將模型改爲測試模式
eval_loss = 0
eval_acc = 0
for data in test_loader:
img, label = data
img = img.view(img.size(0), -1)
if torch.cuda.is_available():
img = img.cuda()
label = label.cuda()
out = model(img)
loss = loss_fn(out, label)
eval_loss += loss.item() * label.size(0) # lable.size(0)=128
_, pred = torch.max(out, 1)
num_correct = (pred == label).sum()
eval_acc += num_correct.item()
print('Epoch:{}, Test loss:{:.6f}, Acc:{:.6f}'.format(epoch, eval_loss/(len(test_dataset)), eval_acc/(len(test_dataset))))
readpic.py 代碼:
from PIL import Image
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
def readImage(path='./3.jpg', size=28):
mode = Image.open(path).convert('L') # 轉換成灰度圖
transform1 = transforms.Compose([
transforms.Resize(size),
transforms.CenterCrop((size, size)), # 切割
transforms.ToTensor()
])
mode = transform1(mode)
mode = mode.view(mode.size(0), -1)
return mode
def showTorchImage(image):
mode = transforms.ToPILImage()(image)
plt.imshow(mode)
plt.show()
在MNIST.py裏測試:
figure = readpic.readImage(size=28)
figure = figure.cuda()
y_pred = model(figure)
_, pred = torch.max(y_pred, 1)
print('prediction = ', pred.item())
用測試集識別的效果很好,但是自己手寫數字識別時發現精度並不是很高。
用的圖片也是和28*28的差不多大,不知道哪邊出了問題。