知识点
torch.zeros_like(X)#是一个PyTorch张量函数,用于创建一个与张量X具有相同形状(shape)和数据类型(dtype)的零张量(全为0的张量)。
ctrl 进去找不认识的参数
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
# train_iter, test_iter = data.DataLoader(mnist_train, batch_size, shuffle=True,
# num_workers=get_dataloader_workers()),
# data.DataLoader(mnist_test, batch_size, shuffle=False,
# num_workers=get_dataloader_workers())
# mnist_train = torchvision.datasets.FashionMNIST(
root="../data", train=True, transform=trans, download=True)
# mnist_test = torchvision.datasets.FashionMNIST(
root="../data", train=False, transform=trans, download=True)
trans = transforms.Compose(trans)
ReLU函数的定义为relu(x) = max(0, x),即对于输入x,如果x小于等于0,则输出为0,否则输出为x本身。
多层感知机
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 # 输入、输出是数据决定的,256是调参自己决定的
W1 = nn.Parameter(torch.randn(num_inputs, num_hiddens, requires_grad=True))
b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
W2 = nn.Parameter(torch.randn(num_hiddens, num_outputs, requires_grad=True))
b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))
params = [W1,b1,W2,b2]
# 实现 ReLu 激活函数
def relu(X):
a = torch.zeros_like(X) # 数据类型、形状都一样,但是值全为 0
return torch.max(X,a)
# 实现模型
def net(X):
#print("X.shape:",X.shape)
X = X.reshape((-1, num_inputs)) # -1为自适应的批量大小
#print("X.shape:",X.shape)
H = relu(X @ W1 + b1)
#print("H.shape:",H.shape)
#print("W2.shape:",W2.shape)
return (H @ W2 + b2)
# 损失
loss = nn.CrossEntropyLoss() # 交叉熵损失
# 多层感知机的训练过程与softmax回归的训练过程完全一样
num_epochs ,lr = 10, 0.01
updater = torch.optim.SGD(params, lr=lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
多层感知机-框架
import torch
from torch import nn
from d2l import torch as d2l
# 隐藏层包含256个隐藏单元,并使用了ReLU激活函数
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, )
net.apply(init_weights)
# 训练过程
batch_size, lr, num_epochs = 256, 0.1, 10
loss = nn.CrossEntropyLoss()
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)
文章来源地址https://www.toymoban.com/news/detail-668119.html
文章来源:https://www.toymoban.com/news/detail-668119.html
到了这里,关于多层感知机的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!