softmax回归实现
导包
import torch
from IPython import display
from d2l import torch as d2l
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
初始化模型参数
num_inputs = 784 #28x28的图片拉成一个向量784
num_outputs = 10
#X输入将会是1x784
W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True) #784行,10列
b = torch.zeros(num_outputs, requires_grad=True) #1行10列
实现softmax
需要用到一个功能:
X = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdim=True), X.sum(1, keepdim=True)
0是将列压扁,把行的各项相加,变为1行,1是将行压扁,把列的各项相加,变为1列
(tensor([[5., 7., 9.]]),
tensor([[ 6.],
[15.]]))
实现softmax:
def softmax(X):
X_exp = torch.exp(X)
partition = X_exp.sum(1, keepdim=True) #sum的参数为1,按行求和,比如,a*b变为a*1,因为b列的数字求和变为一个数字
return X_exp / partition #因为分子分母行列数不匹配,用到了广播机制
实现softmax回归模型:
def net(X):
return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b) #X将被重构为256x784的矩阵,X每次取batch_size数量的图片,batch_size是256
需要学习一种索引方法:
创建一个数据样本y_hat
,其中包含2个样本在3个类别的预测概率,以及它们对应的标签y
。使用y
作为y_hat
中概率的索引
y = torch.tensor([0, 2])
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[[0,1], y]
tensor([0.1000, 0.5000])
理解:对于y_hat第0行和第1行,识别到y标签的概率,即第0行识别为0的概率和第一行识别为2的概率,分别为0.1,0.5,即y_hat第一个索引为行索引,指明在y_hat的范围内,而y作为真实标签,结果就是y_hat识别真实标签的概率
实现交叉熵损失函数:
def cross_entropy(y_hat, y):
return - torch.log(y_hat[range(len(y_hat)), y])
# y存储的是每一行(即每一个样本)对应的真实标签,y_hat从0取到y_hat的行数,列取y中的值,比如,h_hat行索引取0时,列索引取y[0],,h_hat行索引取1时,列索引取y[1]
准确性计算:
def accuracy(y_hat, y):
"""计算预测正确的数量"""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = y_hat.argmax(axis=1) #axis=1将返回每一行最大数值的索引,argmax是返回最大数索引的,而axis是表明按行找最大值还是按列找最大值,感觉和sum类似
cmp = y_hat.type(y.dtype) == y
return float(cmp.type(y.dtype).sum())
accuracy(y_hat, y) / len(y)
精度计算:(这里用到了Accumulator)
def evaluate_accuracy(net, data_iter):
"""计算在指定数据集上模型的精度"""
if isinstance(net, torch.nn.Module): #如果net是torchnn模型的话
net.eval() ##把模型转为评估模式,就是不用算梯度了
metric = Accumulator(2)
with torch.no_grad():
for X, y in data_iter:
metric.add(accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
Accumulator
实例中创建了2个变量,
分别用于存储正确预测的数量和预测的总数量
class Accumulator:
"""在n个变量上累加"""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
evaluate_accuracy(net, test_iter)
updater是一个梯度下降函数:
lr = 0.1
def updater(batch_size):
return d2l.sgd([W, b], lr, batch_size)
Softmax回归的训练:
def train_epoch_ch3(net, train_iter, loss, updater):
"""训练模型一个迭代周期(定义见第3章)"""
if isinstance(net, torch.nn.Module):
net.train()
metric = Accumulator(3)
for X, y in train_iter:
y_hat = net(X)
l = loss(y_hat, y)
if isinstance(updater, torch.optim.Optimizer):
updater.zero_grad()
l.mean().backward()
updater.step()
else:
l.sum().backward()
updater(X.shape[0])
metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
return metric[0] / metric[2], metric[1] / metric[2]
训练模型10个迭代周期
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
可视化部分:
class Animator:
"""在动画中绘制数据"""
def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
figsize=(3.5, 2.5)):
if legend is None:
legend = []
d2l.use_svg_display()
self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
if nrows * ncols == 1:
self.axes = [self.axes, ]
self.config_axes = lambda: d2l.set_axes(
self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
self.X, self.Y, self.fmts = None, None, fmts
def add(self, x, y):
if not hasattr(y, "__len__"):
y = [y]
n = len(y)
if not hasattr(x, "__len__"):
x = [x] * n
if not self.X:
self.X = [[] for _ in range(n)]
if not self.Y:
self.Y = [[] for _ in range(n)]
for i, (a, b) in enumerate(zip(x, y)):
if a is not None and b is not None:
self.X[i].append(a)
self.Y[i].append(b)
self.axes[0].cla()
for x, y, fmt in zip(self.X, self.Y, self.fmts):
self.axes[0].plot(x, y, fmt)
self.config_axes()
display.display(self.fig)
display.clear_output(wait=True)