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)
)
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))
# w1 b1是第一层,w2 b2是第二层
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)
loss = nn.CrossEntropyLoss()
# 训练
num_epochs,lr=10,0.1
updater = torch.optim.SGD(params,lr=lr)
print(updater)
# d2l.train_ch3(net,train_iter,test_iter,loss,num_epochs,updater)
标签:w1,nn,torch,多层,感知机,pytorch,num,b1,b2 From: https://www.cnblogs.com/jinbb/p/17589303.html