独热编码(one-hot encoding):是一个向量,向量的分量与类别一样多,对应分量设置为1,其他为0。如y={(1,0,0),(0,1,0),(0,0,1)}可用来表示三分类问题
softmax将未规范化的数字变为非负数且总和为1,满足概率论要求。softmax是非线性函数,softmax回归是线性回归模型。
分类问题的损失函数从均值平方L2的MSELoss变为交叉熵损失(cross-entropy loss)
3.1 读取数据集
这里可以学习enumerate
for i ,(ax,img) in enumerate(zip(axes,imgs)):其中enumerate为每一个循环提供一个标号i,从0开始
import torch
import torchvision
from torch.utils import data
from torchvision import transforms
from d2l import torch as d2l
from matplotlib_inline import backend_inline
def use_svg_dispaly(): #@save
'''使用svg格式显示绘图'''
backend_inline.set_matplotlib_formats('svg')
d2l.use_svg_display()
#####读取数据集
#Fashion-MNIST由10个类别图像,每个类别有60000张训练集和10000张测试集
trans=transforms.ToTensor()#通过ToTensor实例将图像数据从PIT类型变换为32位浮点数,除以255到0-1
mnist_train=torchvision.datasets.FashionMNIST(
root="../mnistdata",train=True,transform=trans,download=True
)
mnist_test=torchvision.datasets.FashionMNIST(
root="../mnistdata",train=False,transform=trans,download=True
)
#数字标签索引与其文本名称进行转换
def get_fashion_mnist_labels(labels):#@save
'''返回Fashion-MNIST数据集的文本标签'''
text_labels=['t-shirt','trouser','pullover','dress','coat'
'sandal','shirt','sneaker','bag','ankle boot']
return [text_labels[int(i)]for i in labels]
#创建函数可视化样本
def show_images(imgs,num_rows,num_cols,titles=None,scale=1.5):#@save
'''绘制图像列表'''
#此处num_rows,num_cols是指显示图片的排布
figsize=(num_cols*scale,num_rows*scale)
_, axes=d2l.plot.subplots(num_rows,num_cols,figsize=figsize)
axes=axes.flatten()
for i,(ax,img)in enumerate(zip(axes,imgs)):#enumerate的作用是为每一个循环提供索引i(从0开始)
if torch.is_tensor(img):
#图像张量
ax.imshow(img.numpy())
else:
#PIL图像
ax.imshow(img)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if titles:
ax.set_title(titles[i])
return axes
#显示前几个样本
X,y=next(iter(data.DataLoader(mnist_train,batch_size=18)))#iter构造Python迭代器,next取第一项
show_images(X.reshape(18,28,28),2,9,titles=get_fashion_mnist_labels(y))