PyTorch提供了方便漂亮的类和模块,来帮助我们创建和训练神经网络,例如 torch.nn, torch.optim 等。
为了更好地理解这些模块的功能和原理,我们在手动搭建的神经网络上,逐步添加这些模块,以显示每部分模块的功能,以及每部分是如何让代码更加灵活简洁的。
1、手动搭建神经网络
使用MNIST数据集,该数据集共有50000个图片,每一图片大小为2828,储存在长度为2828=784的扁平行。
#定义权重和偏执值,需要requires_grad=True,以便自动计算梯度,完成反馈
weights = torch.randn(784, 10,requires_grad=True)
bias = torch.zeros(10, requires_grad=True)
#定义激活函数
def log_softmax(x):
return x - x.exp().sum(-1).log().unsqueeze(-1)
#定义神经网络运算过程,其中@表示点乘
def model(xb):
return log_softmax(xb @ weights + bias)
#定义代价函数
def nll(input, target):
return -input[range(target.shape[0]), target].mean()
loss_func = nll
#验证结果的准确性
def accuracy(out, yb):
preds = torch.argmax(out, dim=1)
return (preds == yb).float().mean()
#获取一批数据,验证预测的结果:
bs = 64 # batch size
xb = x_train[0:bs] # a mini-batch from x
yb = y_train[0:bs]
preds = model(xb) # predictions
print(preds[0], preds.shape)
print(loss_func(preds, yb))
print(accuracy(preds, yb))
输出:
tensor([-1.7022, -3.0342, -2.4138, -2.6452, -2.7764, -2.0892, -