学习全连接神经网络,尝试使用pytorch去做

import torch
import torch.utils.data
from torch import nn
from torch.nn import functional as F
from torch import optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt

from utils import plot_image, plot_curve, one_hot


# 下载数据集
train_dataset = torchvision.datasets.MNIST('./data', train=True, download=True,
                                           transform=transforms.Compose([transforms.ToTensor(),
                                                                         transforms.Normalize((0.1307,),
                                                                                              (0.3081,))
                                                                         ])
                                           )
test_dataset = torchvision.datasets.MNIST('./data', train=False, download=True,
                                          transform=transforms.Compose([transforms.ToTensor(),
                                                                        transforms.Normalize((0.1307,),
                                                                                             (0.3081,))
                                                                        ])
                                          )
batch_size = 512
# 加载数据集
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=False)

x, y = next(iter(train_loader))
print(x.shape, y.shape, x.min(), x.max())
# plot_image(x, y, 'image-sample')

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()

        self.fc1 = nn.Linear(28*28, 256)
        self.fc2 = nn.Linear(256, 64)
        self.fc3 = nn.Linear(64, 10)

    def forward(self, x):

        # 对不同的激活函数进行分析和比较(SELU,ELU,Leaky-ReLU,ReLU等)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        # x = F.softmax(self.fc3(x))

        return x


net = Net()
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)

train_loss = []
for epoch in range(3):

    for batch_idx, (x, y) in enumerate(train_loader):

        # print(x.shape, y.shape)
        # # torch.Size([128, 1, 28, 28]) torch.Size([128])
        # break
        x = x.view(x.size(0), 28*28)
        out = net(x)
        y_onehot = one_hot(y)

        loss = F.mse_loss(out, y_onehot)

        optimizer.zero_grad()
        loss.backward()
        # w' = w - lr*grad
        optimizer.step()

        train_loss.append(loss.item())

        if batch_idx % 10 == 0:
            print(epoch+1, batch_idx, loss.item())


# 得到[w1,b1,w2,b2,w3,b3]
plot_curve(train_loss)

total_correct = 0
for x, y in test_loader:
    x = x.view(x.size(0), 28*28)
    out = net(x)
    pred = out.argmax(dim=1)
    correct = pred.eq(y).sum().float()
    total_correct += correct

total_num = len(test_loader.dataset)
acc = total_correct / total_num
print('test acc:', acc)

x, y = next(iter(test_loader))
out = net(x.view(x.size(0), 28*28))
pred = out.argmax(dim=1)
plot_image(x, pred, 'test')