import matplotlib.pyplot as plt
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) # 返回训练集和测试集的迭代器
# 将展平每个图像,将它们视为长度为784的向量。 图像是28*28的,拉长就是784
# 因为数据集有10个类别,所以网格输出维度为10
num_inputs = 784
num_output = 10
w = torch.normal(0, 0.01, size=(num_inputs, num_output), requires_grad=True) # 权重 size:形状--num_inputs:行、num_output:列
b = torch.zeros(num_output, requires_grad=True) # 偏差
'''
# 回顾:给定一个矩阵,我们可以对所有元素求和
x = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(x)
print(x.sum(0, keepdim=True), '\n', x.sum(1, keepdim=True))
# tensor([[1., 2., 3.],
# [4., 5., 6.]])
# tensor([[5., 7., 9.]])
# tensor([[ 6.],
# [15.]])
'''
# 实现softmax 对矩阵用softmax就是在矩阵的每一行上进行
"""
对每个项求幂(使用exp);
对每一行求和(小批量中每个样本是一行),得到每个样本的规范化常数;
将每一行除以其规范化常数,确保结果的和为1。
"""
def softmax(x):
x_exp = torch.exp(x)
partition = x_exp.sum(1, keepdim=True)
return x_exp / partition # 应用了广播机制
# 测试
x = torch.normal(0, 1, (2, 5))
x_prob = softmax(x)
# print(x_prob, '\n', x_prob.sum(1))
# 测试结果:将每个元素变成一个非负数。此外,依据概率原理,每行总和为1
# tensor([[0.1488, 0.0353, 0.1059, 0.5232, 0.1868],
# [0.1903, 0.0968, 0.3103, 0.1855, 0.2172]])
# tensor([1.0000, 1.0000])
# 实现softmax回归模型
def net(x):
return softmax(torch.matmul(x.reshape((-1, w.shape[0])), w) + b) # x.reshape((-1, w.shape[0]):
# -1表示自动计算维度大小,将x调整成w一样形状
# 就是wx+b
# 演示如何怎么样在我的预测值里面根据我的标号把我的对应的预测值拿出来
# 创建一个数据y_hat,其中包含2个样本在3个类别的预测概率,使用y作为y_hat中概率的索引
y = torch.tensor([0, 2]) # 表示两个真实的标号
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]]) # 预测值
# print(y_hat[[0, 1], y]) # 这里的[0, 1]表示y_hat的第0行和第1行,y是[0, 2],表示第0列和第2列,组合起来就是(0,0)和(1,2)
# 实现交叉熵损失函数 -ln(y_hat[range(len(y_hat)), y])
def cross_entropy(y_hat, y):
return -torch.log(y_hat[range(len(y_hat)), y])
# print(cross_entropy(y_hat, y)) # tensor([2.3026, 0.6931])
# 将预测类别与真实y元素进行比较
def accuracy(y_hat, y):
"""计算预测正确的数量"""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1: # y_hat的行数和列数都大于一
y_hat = y_hat.argmax(axis=1) # 每一行元素值最大的那个下标存到y_hat中
cmp = y_hat.type(y.dtype) == y # 把y_hat转成y的数据类型然后作比较变成一个bool的tensor
return float(cmp.type(y.dtype).sum()) # 再将cmp转成跟y一样的形状,求和
# print(accuracy(y_hat, y) / y) # tensor([ inf, 0.5000])
# 我们可以评估在任意模型net的准确率
def evaluate_accuracy(net, data_iter):
"""计算在指定数据集上模型的精度"""
if isinstance(net, torch.nn.Module):
net.eval() # 将模型设置为评估模式
metric = Accumulator(2) # 正确预测数、预测总数 累加器(Accumulator)对象,该对象用于累积两个值:正确预测的数量和总的预测数量。
for x, y in data_iter:
metric.add(accuracy(net(x), y), y.numel())
return metric[0] / metric[1]
class Accumulator: # @save
"""在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]
def train_epoch_ch3(net, train_iter, loss, updater): # @save
"""训练模型一个迭代周期(定义见第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):
# 使用PyTorch内置的优化器和损失函数
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]
class Animator: # @save
"""在动画中绘制数据"""
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, ]
# 使用lambda函数捕获参数
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)
plt.draw()
plt.pause(0.001)
display.clear_output(wait=True)
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): # @save
"""训练模型(定义见第3章)"""
animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],
legend=['train loss', 'train acc', 'test acc'])
for epoch in range(num_epochs):
train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
test_acc = evaluate_accuracy(net, test_iter)
animator.add(epoch + 1, train_metrics + (test_acc,))
train_loss, train_acc = train_metrics
assert train_loss < 0.5, train_loss
assert 1 >= train_acc > 0.7, train_acc
assert 1 >= test_acc > 0.7, test_acc
lr = 0.1
def updater(batch_size):
return d2l.sgd([w, b], lr, batch_size)
if __name__ == '__main__':
# print(evaluate_accuracy(net, test_iter))
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
softmax回归的从零实现
最新推荐文章于 2024-08-29 23:08:54 发布