2.1感知机
感知机由两层的神经元组成,即输入层和输出层。对于感知机模型来说,在实际运用中具有较大的局限性,如不能进行异或运算。为了解决非线性的可分问题,考虑在网络中加入一个或多个隐藏层得到一个多层感知机。
多层感知机在输出层和输入层之间增加一个或多个全连接隐藏层,并通过激活函数转换隐藏层的输出一个单隐藏层的多层感知机如下图所示。
激活函数(activation function)通过计算加权和并加上偏置来确定神经元是否应该被激活, 它们将输入信号转换为输出的可微运算。大多数激活函数都是非线性的。
ReLu函数:
sigmoid函数:
tanh函数:
2.2 代码实现1
!pip install git+https://github.com/d2l-ai/d2l-zh@release # installing d2l
!pip install matplotlib==3.0.0
import torch
from torch import nn
from d2l import torch as d2l
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
#初始化
num_inputs, num_outputs, num_hiddens = 784, 10, 256
W1 = nn.Parameter(torch.randn(num_inputs, num_hiddens, requires_grad=True)*0.01)
b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
W2 = nn.Parameter(torch.randn(num_hiddens, num_outputs, requires_grad=True)*0.01)
b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))
params = [W1,b1,W2,b2]
def relu(X):
a = torch.zeros_like(X)
return torch.max(X,a)
def net(X):
X = X.reshape((-1,num_inputs))
H = relu(X@W1 + b1)# @为矩阵乘法
return H@W2 + b2
loss = nn.CrossEntropyLoss(reduction='none')
#由于多层感知机与softmax训练过程完全相同 这里直接使用softmax的训练函数
num_epochs, lr = 10, 0.1
updater = torch.optim.SGD(params, lr=lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
运行结果:
2.3 代码实现2
!pip install git+https://github.com/d2l-ai/d2l-zh@release # installing d2l
!pip install matplotlib==3.0.0
import torch
from torch import nn
from d2l import torch as d2l
net = nn.Sequential(nn.Flatten(),nn.Linear(784, 256),nn.ReLU(),nn.Linear(256, 10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net.apply(init_weights);
batch_size, lr, num_epochs = 256, 0.1, 10
loss = nn.CrossEntropyLoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(), lr=lr)
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
运行结果: