#scratch
import torch
from d2l import torch as d2l
from torch import nn
#load data set fashion_mnist
batch_size = 128 #
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
#set parameters
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))
parameters = [W1, b1, W2, b2]
#set net one hidden
def net(X):
X = X.reshape((-1,num_inputs))
return torch.relu(X@W1 + b1)@W2 + b2
#set loss func
loss = nn.CrossEntropyLoss(reduction="none")
#train
num_epochs, lr = 20, 0.1
updater = torch.optim.SGD(parameters, lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
#test
d2l.predict_ch3(net, test_iter)
训练
测试
#concise
import torch
from torch import nn
from d2l import torch as d2l
# use Sequential to define the net: Flatten,Linear,ReLU,Linear
net = nn.Sequential(nn.Flatten(),
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10))
# weight tensor to normal weight tensor
def init_weights(m):
# if m is nn.Linear, the tensor m.weight -> a normal tensor which mean=0,std=0.01
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01) # Fills the input Tensor with values drawn from the normal
net.apply(init_weights)
# define parameters batch_size, lr, num_epochs and loss, updater
batch_size, lr, num_epochs = 128, 0.1, 10
loss = nn.CrossEntropyLoss(reduction='none')
updater = torch.optim.SGD(net.parameters(), lr=lr)
# load dataset and train
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
训练
教程链接d2l.ai