感知机和二分类的区别:
线性回归输出的是实数,而感知机输出是离散的类
与softmax的区别是感知机只能输出一类,而softmax是进行多个种类分类,有多少个类别就输出多少;类
训练感知机
initialize w=0 and b=0
repeat
if yi[<w,xi>+b]<=0 then
w<—w+yixi and b<–b+yi
end if
until all classified correctly
等价于使用批量大小为1的梯度下降,并使用如下的损失函数:
l(y,x,w)=max(0, -y<w,x>)
收敛定理
数据在半径r内
余量p分类两类:y(x^T* w+b)>=p
对于||w||2+b2<=1
感知机保证在(r2+1)/p2步后收敛
XOR问题
感知机不能拟合XOR函数,它只能产生线性分割面
总结
感知机是一个二分类模型
求解算法等价于使用批量大小为1的梯度下降
它不能拟合XOR函数
多层感知机
学习XOR问题
激活函数:Sigmoid函数,Tanh函数,ReLu函数
详细看:
https://zh-v2.d2l.ai/chapter_multilayer-perceptrons/mlp.html
多类分类
y1,y2,…yk=softmax(o1,o2,…,ok)
每个隐藏层都有激活函数,避免层数塌陷,并且最后一层没有激活函数
超参数:隐藏层数、每层隐藏层的大小
总结:
多层感知机在输出层和输入层之间增加一个或多个全连接隐藏层,并通过激活函数转换隐藏层的输出。
常用的激活函数包括ReLU函数、sigmoid函数和tanh函数。
softmax处理多分类
超参数为隐藏层数和各个隐藏层的大小
多层感知机从零实现
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)
实现一个具有单隐藏层的多层感知机,包含256个隐藏单元
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]
实现ReLu激活函数
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) # X: 批量大小*输入大小,w:784*256
loss=nn.CrossEntropyLoss(reduction='none') #没有loss的线:写入reduction='none'
多层感知机的训练过程和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)
#出现AssertionError是因为视频中初始化W偏大,应改为[0,0.01]
多层感知机的简洁实现
通过高级API更简洁实现多层感知机
import torch
from torch import nn
from d2l import torch as d2l
隐藏层包含了256个隐藏单元,并使用了ReLu激活函数
net=nn.Sequential(nn.Flatten(), # 将3d展平成2维
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)