#coding=utf-8
import torch
import torchvision
import numpy as np
import sys
sys.path.append("..") # 为了导入上层目录的d2lzh_pytorch
from d2l import torch as d2l
import matplotlib.pyplot as plt
#from IPython import display
batch_size=256
train_iter,test_iter=d2l.load_data_fashion_mnist(batch_size)
#每个输入是一张图片,输入为一维向量,将大小28*28的图片拉伸成一维向量,大小784,输出为10种分类情况
num_inputs=784
num_outputs=10
#定义权重
#w=torch.normal(0,0.01,size=(num_inputs,num_outputs),requires_grad=torch.float)
#b=torch.zeros(num_outputs,requires_grad=True)
w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, num_outputs)), dtype=torch.float)
b = torch.zeros(num_outputs, dtype=torch.float)
#通过设置requires_grad_属性为True,可以告诉PyTorch在反向传播过程中需要计算该参数的梯度
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
#实现softmax的运算,经过softmax后,所有输出为非负,且和为1
def softmax(x):
x_exp=x.exp()
partition=x_exp.sum(dim=1,keepdim=True)
return x_exp/partition
#return 中运用了广播机制
#广播机制的原理很简单:对于两个形状不同的张量A和B,
# 如果它们的形状在某个维度上相同,那么在该维度上的每个元素都可以被独立地视为一个标量来进行操作;
# 如果它们的形状在某个维度上不同,那么在该维度上为1的尺寸会自动扩展以匹配另一个张量的该维度,
# 而其他维度则用0来填充。这样,两个张量就可以进行逐元素操作了
#定义模型
def net(x):
return softmax(torch.matmul(x.reshape((-1,w.shape[0])),w)+b)
#x通过reshape操作转换为一个列向量,然后与权重矩阵w进行矩阵乘法运算,得到一个新的张量。[1,784]*[784,10]=[1,10]
# 接着,将上一步的结果与偏置向量b相加,得到一个新的张量。
# 最后,对这个新的张量应用softmax函数,得到每个类别的概率分布。
#定义损失函数,使用交叉熵损失函数
"""首先通过y_hat张量计算出一个预测值向量,
其中每个元素表示对应样本属于每个类别的概率。
然后,通过torch.log函数对该预测值向量进行对数运算,得到一个新的张量。
最后,通过对该新的张量和真实标签y进行索引操作,
选取出正确类别的预测值,并取其相反数,得到二元交叉熵损失函数的值"""
def crposs_entropy(y_hat,y):
return -torch.log(y_hat[range(len(y_hat)),y])
#检测准确率
def evaluate_accuracy(data_iter, net):
acc_sum, n = 0.0, 0
for X, y in data_iter:
acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
n += y.shape[0]
return acc_sum / n
#训练模型
num_epochs, lr = 5, 0.1
# 本函数已保存在d2lzh包中方便以后使用
def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, optimizer=None):
for epoch in range(num_epochs):
train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
for X, y in train_iter:
y_hat = net(X)
l = loss(y_hat, y).sum()
# 梯度清零
if optimizer is not None:
optimizer.zero_grad()
elif params is not None and params[0].grad is not None:
for param in params:
param.grad.data.zero_()
l.backward()
if optimizer is None:
d2l.sgd(params, lr, batch_size)
else:
optimizer.step() # “softmax回归的简洁实现”一节将用到
train_l_sum += l.item()
train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
n += y.shape[0]
test_acc = evaluate_accuracy(test_iter, net)
print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
% (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))
train_ch3(net, train_iter, test_iter, crposs_entropy, num_epochs, batch_size, [w, b], lr)
#进行预测测试
x,y=next(iter(test_iter))
true_labels=d2l.get_fashion_mnist_labels(y.numpy())
pre_labels=d2l.get_fashion_mnist_labels(net(x).argmax(dim=1).numpy())
titles=[true +"\n"+pred for true,pred in zip(true_labels,pre_labels)]
#运行代码是d2l库显示没有show_fashion_mnist函数时,可以手动添加下段代码进行运行
#也可以ctrl+单击,进入d2l库中,将下段代码添加进d2l中
'''def show_fashion_mnist(images, labels):
d2l.use_svg_display()
# 这里的_表示我们忽略(不使用)的变量
_, figs = plt.subplots(1, len(images), figsize=(12, 12))
for f, img, lbl in zip(figs, images, labels):
f.imshow(img.view((28, 28)).numpy())
f.set_title(lbl)
f.axes.get_xaxis().set_visible(False)
f.axes.get_yaxis().set_visible(False)
plt.show()'''
X, y = next(iter(test_iter))
true_labels = d2l.get_fashion_mnist_labels(y.numpy())
pred_labels = d2l.get_fashion_mnist_labels(net(X).argmax(dim=1).numpy())
titles = [true + '\n' + pred for true, pred in zip(true_labels, pred_labels)]
d2l.show_fashion_mnist(X[0:9], titles[0:9])
写代码的时候,注意show_fashion_mnist()函数的使用,可能会显示d2l库没有此函数的错误提示,上面有解决办法。下图为模型计算参数,和预测结果值