一、Softmax回归
Softmax回归虽然称为回归,但是其实它是一个分类问题。
回归VS分类: 回归估计一个连续值; 分类预测一个连续类别。 回归的输出为真实值与预测值之间的损失; 分类的输出为各个类别的概率,概率最大类别即为预测类别。 对于Softmax输出概率,一般使用交叉熵来计算损失
总结 Softmax回归是一个多类分类模型; 使用Softmax操作子得到每个类的预测置信度; 使用交叉熵来衡量预测和标号的区别。
二、损失函数
L2Loss: l(y,y’)=1/2 (y-y’)^2 L1Loss: l(y,y’)=|y-y’| 因为绝对值损失在一些点不可导,所以当预测值与实际值较近时(预测接近末端时),损失的变化可能会不那么稳定。
在pytorch中还有其他的一些损失函数可供直接调用
三、图片分类数据集
1.下载Fashion-MNIST数据集
Fashion-MNIST数据集
import torch
import torchvision
from torch.utils import data
from torchvision import transforms
import matplotlib.pyplot as plt
trans=transforms.ToTensor()
mnist_train=torchvision.datasets.FashionMNIST(root="./data",
train=True,
transform=trans,
download=True)
mnist_test=torchvision.datasets.FashionMNIST(root="./data",
train=False,
transform=trans,
download=True)
print(len(mnist_train),len(mnist_test))
print(mnist_train[0][0].shape
60000 10000 torch.Size([1, 28, 28])
mnist_train有60000张图片,mnist_test有10000张图片 mnist_train中的图片为一通道灰度图,大小为28*28
得到Fashion-MNIST数据集图片的标签
def get_fashion_mnist_labels(labels):
"""返回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):
"""Plot a list of images."""
figsize = (num_cols * scale, num_rows * scale)
_, axes = plt.subplots(num_rows, num_cols, figsize=figsize)
axes = axes.flatten()
for i, (ax, img) in enumerate(zip(axes, imgs)):
if torch.is_tensor(img):
ax.imshow(img.numpy())
else:
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
按批量读取图片并显示: batch_size=18即为拿到一个批量为18的数据 next()即为拿的是第一个批量的数据
X, y = next(iter(data.DataLoader(mnist_train, batch_size=18)))
show_images(X.reshape(18, 28, 28), 2, 9, titles=get_fashion_mnist_labels(y));
以下是训练数据集中的前几个样本的图像及其相应的标签(文本形式):
2.读入数据
batch_size=256
def get_dataloader_workers():
"""使用0个进程来读取数据"""
return 0
"""根据CPU的配置可修改为使用n个进程进行数据的处理,返回0时表示不使用多进程"""
train_iter=data.DataLoader(mnist_train,batch_size,shuffle=True,
num_workers=get_dataloader_workers())
test_iter=data.DataLoader(mnist_test,batch_size,shuffle=False,
num_workers=get_dataloader_workers())
for X,y in train_iter:
continue
读取数据的时间一般要比我们训练的时间快很多
3、初始化权重和偏移
将28*28的图像展平为784的向量,因此输入的数据维度为784;因为数据集有10个类别,所以网络输出维度为10。
num_inputs=784
num_outputs=10
w=torch.normal(0,0.01,size=(num_inputs,num_outputs),requires_grad=True)
b=torch.zeros(num_outputs,requires_grad=True)
4、定义Softmax操作
根据softmax定义公式设计softmax计算函数:
def softmax(X):
X_exp=torch.exp(X)
partition=X_exp.sum(1,keepdim=True)
return X_exp/partition
5、定义模型
def net(X):
return softmax(torch.matmul(X.reshape((-1,w.shape[0])),w)+b)
6、定义损失函数
对于分类问题而言,损失函数需要选用交叉熵损失函数
def cross_entropy(y_hat,y):
return -torch.log(y_hat[range(len(y_hat)),y])
return中y_hat为对任意一个标号的十个分类的预测概率。
7、评价
def accuracy(y_hat,y):
"""计算预测正确的数量"""
if len(y_hat.shape)>1 and y_hat.shape[1]>1:
y_hat=y_hat.argmax(axis=1)
cmp=y_hat.type(y.dtype)==y
return float(cmp.type(y.dtype).sum())
def evaluate_accuracy(net, data_iter):
"""计算在指定数据集上模型的精度。"""
if isinstance(net, torch.nn.Module):
net.eval()
metric = Accumulator(2)
for X, y in data_iter:
metric.add(accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
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]
8、训练
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.backward()
updater.step()
metric.add(float(l) * len(y), accuracy(y_hat, y),
y.size().numel())
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]
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):
"""训练模型(定义见第3章)。"""
for epoch in range(num_epochs):
train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
test_acc = evaluate_accuracy(net, test_iter)
train_loss, train_acc = train_metrics
assert train_loss < 0.5, train_loss
assert train_acc <= 1 and train_acc > 0.7, train_acc
assert test_acc <= 1 and test_acc > 0.7, test_acc
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
四、softmax回归的简洁实现
import torch
import torchvision
from torch import nn
from torch.utils import data
from torchvision import transforms
batch_size=256
trans=transforms.ToTensor()
mnist_train=torchvision.datasets.FashionMNIST(root="./data",
train=True,
transform=trans,
download=True)
mnist_test=torchvision.datasets.FashionMNIST(root="./data",
train=False,
transform=trans,
download=True)
train_iter=data.DataLoader(mnist_train,batch_size,shuffle=True,
num_workers=0)
test_iter=data.DataLoader(mnist_test,batch_size,shuffle=False,
num_workers=0)
net=nn.Sequential(nn.Flatten(),nn.Linear(784, 10))
def init_weights(m):
if type(m)==nn.Linear:
nn.init.normal_(m.weight,std=0.01)
net.apply(init_weights)
criterion=nn.CrossEntropyLoss()
optimizer=torch.optim.SGD(net.parameters(), lr=0.1)
if __name__=='__main__':
for epoch in range(10):
running_loss=0.0
for batch_idx,data in enumerate(train_iter,0):
inputs,target=data
optimizer.zero_grad()
outputs=net(inputs)
loss=criterion(outputs,target)
loss.backward()
optimizer.step()
running_loss+=loss.item()
if batch_idx % 10==9:
print('[%d,%5d] loss: %.3f' % (epoch+1,batch_idx+1,running_loss/10))
running_loss=0.0
基于pytorch深度学习框架的基本架构: 1、准备数据
trans=transforms.ToTensor()
mnist_train=torchvision.datasets.FashionMNIST(root="./data",
train=True,
transform=trans,
download=True)
mnist_test=torchvision.datasets.FashionMNIST(root="./data",
train=False,
transform=trans,
download=True)
train_iter=data.DataLoader(mnist_train,batch_size,shuffle=True,
num_workers=0)
test_iter=data.DataLoader(mnist_test,batch_size,shuffle=False,
num_workers=0)
2、通过类(class)设计模型
net=nn.Sequential(nn.Flatten(),nn.Linear(784, 10))
3、构造损失函数和优化器
criterion=nn.CrossEntropyLoss()
optimizer=torch.optim.SGD(net.parameters(), lr=0.1)
4、设计训练循环
for epoch in range(10):
running_loss=0.0
for batch_idx,data in enumerate(train_iter,0):
inputs,target=data
optimizer.zero_grad()
outputs=net(inputs)
loss=criterion(outputs,target)
loss.backward()
optimizer.step()
running_loss+=loss.item()
if batch_idx % 10==9:
print('[%d,%5d] loss: %.3f' % (epoch+1,batch_idx+1,running_loss/10))
running_loss=0.0
一般的训练循环流程: 1、前向传播:预测(Forward:Predict) 2、前向传播:计算损失(Forward:Loss) 3、梯度清零:optimizer.zero_grad() 4、反向传播:loss.backward()(Backward:Autograd) 5、更新权重:optimizer.step()(Update)
|