多层感知机的简单实现

Posted tacit-lxs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多层感知机的简单实现相关的知识,希望对你有一定的参考价值。

多层感知机的简单实现

import torch
import numpy as np
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import sys

def load_data_fashion_mnist(batch_size, resize=None, root='~/Datasets/FashionMNIST'):
    """Download the fashion mnist dataset and then load into memory."""
    trans = []
    if resize:
        trans.append(torchvision.transforms.Resize(size=resize))
    trans.append(torchvision.transforms.ToTensor())
    
    transform = torchvision.transforms.Compose(trans)
    mnist_train = torchvision.datasets.FashionMNIST(root=root, train=True, download=True, transform=transform)
    mnist_test = torchvision.datasets.FashionMNIST(root=root, train=False, download=True, transform=transform)
    if sys.platform.startswith('win'):
        num_workers = 0  # 0表示不用额外的进程来加速读取数据
    else:
        num_workers = 4
    train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=num_workers)
    test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=num_workers)

    return train_iter, test_iter

batch_size = 256
train_iter, test_iter = load_data_fashion_mnist(batch_size) # 每个batch_size含有256张图片及对应的标签。
# 一、参数模型初始化
num_inputs, num_outputs, num_hiddens = 784, 10, 256 #输入个数、输出个数、隐藏层个数
W1 = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_hiddens)), dtype=torch.float) # 784x256
b1 = torch.zeros(num_hiddens, dtype=torch.float)
W2 = torch.tensor(np.random.normal(0, 0.01, (num_hiddens, num_outputs)), dtype=torch.float) # 256x10 
b2 = torch.zeros(num_outputs, dtype=torch.float)
#设置梯度追踪
params = [W1, b1, W2, b2]
for param in params:
    param.requires_grad_(requires_grad=True)

def relu(X): # 用max函数实现relu函数
    return torch.max(input=X, other=torch.tensor(0.0))

# 二、定义模型
def net(X): #将原始图像转化为长度为784的向量
    X = X.view((-1, num_inputs)) 
    H = relu(torch.matmul(X, W1) + b1)
    return torch.matmul(H, W2) + b2

# 四、训练模型
num_epochs, lr = 5, 100.0 #学习率设置为100,因为sgd里面除以了一个batch_size.
#精度
def accuracy(y_hat, y):
    return (y_hat.argmax(dim=1) == y).float().mean().item()
def evaluate_accuracy(data_iter, net):
    acc_sum, n = 0.0, 0
    for X, y in data_iter:
        acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
        n += y.shape[0]
    return acc_sum / n

def sgd(params, lr, batch_size):  # 本函数已保存在d2lzh_pytorch包中⽅便以后使⽤
    for param in params:
        param.data -= lr * param.grad / batch_size  # 注意这⾥更改param时⽤的param.data
def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
              params=None, lr=None, optimizer=None):
    for epoch in range(num_epochs):
        train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
        for X, y in train_iter:
            y_hat = net(X)
            l = loss(y_hat, y).sum()
            
            # 梯度清零
            if optimizer is not None:
                optimizer.zero_grad()
            elif params is not None and params[0].grad is not None:
                for param in params:
                    param.grad.data.zero_()
            
            l.backward()
            if optimizer is None:
                sgd(params, lr, batch_size)
            else:
                optimizer.step()  # “softmax回归的简洁实现”一节将用到
            
            
            train_l_sum += l.item()
            train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
            n += y.shape[0]
        test_acc = evaluate_accuracy(test_iter, net)
        print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
              % (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))
train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)

简洁实现

import torch
from torch import nn
from torch.nn import init
import numpy as np
import sys
# 一、初始化
num_inputs, num_outputs, num_hiddens = 784, 10, 256
# 二、模型定义
class FlattenLayer(torch.nn.Module):
    def __init__(self):
        super(FlattenLayer, self).__init__()
    def forward(self, x): # x shape: (batch, *, *, ...)
        return x.view(x.shape[0], -1)
net = nn.Sequential(
        FlattenLayer(), #扁平化,将原始输入转化为784维的向量
        nn.Linear(num_inputs, num_hiddens), #线性模块
        nn.ReLU(),#激活函数
        nn.Linear(num_hiddens, num_outputs), 
        )
# 参数初始化
for params in net.parameters():
    init.normal_(params, mean=0, std=0.01)
#加载数据
batch_size = 256
train_iter, test_iter = load_data_fashion_mnist(batch_size)
loss = torch.nn.CrossEntropyLoss()
#模型训练
optimizer = torch.optim.SGD(net.parameters(), lr=0.5)

num_epochs = 5
train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)

以上是关于多层感知机的简单实现的主要内容,如果未能解决你的问题,请参考以下文章

感知机+激活函数+多层感知机的实现

神经网络多层感知机的从零开始实现(mlp-scratch)

多层感知机

多层感知机的从零开始实现( 从D2L 包中抽取函数)

多层感知机的从零开始实现( 从D2L 包中抽取函数)

基于多层感知机的手写数字识别(Tensorflow实现)