深度学习——Softmax回归(二)

Softmax回归

利用一些有顺序的类别,可以有分类问题转化为回归问题,分类数据的简单⽅法:独热编码(one-hot encoding)。独热编码是⼀个向量,它的分量和类别⼀样多。类别对应的分量设置为1,其他所有分量设置为0。

为了估计所有可能类别的条件概率,我们需要⼀个有多个输出的模型,每个类别对应⼀个输出。

  • 1. softmax运算:

模型的输出yi可以视为属于类i的概率,然后选择具有最⼤输出值的类别argmax(yi)作为我们的预测。

个人理解其实就是输出每个类别可能的概率,然后选取其中概率最大的类别作为最终的预测结果。

  • 2. 小批量矢量化:

假设⼀个批量的样本X,其中特征维度(输⼊数量)为d,批量⼤⼩为n。此外,假设我们在输出中有q个类别。则X为(n,d)矢量, W为(d, q)矢量, 输出为(n,q)矢量。偏置b则会因为传播机制扩展成适合样本的矢量。

  • 3. 损失函数: 损失函数来度量预测的效果。

sofmax函数给出了⼀个向量y,我们可以将其视为“对给定任意输⼊x的每个类的条件概率”。

交叉熵损失:之前的损失只考虑单个情况,如果考虑到整体结果的分布情况,那么表示形式就和以前不同了,如我们现在⽤⼀个概率向量表⽰,如(0:1; 0:2; 0:7),⽽不是仅包含⼆元项的向量(0; 0; 1)。它是所有标签分布的预期损失值。此损失称为交叉熵损失

  • 4. softmax及其导数

导数是我们sofmax模型分配的概率与实际发⽣的情况(由独热标签向量表⽰)之间的差异。从这个意义上讲,这与我们在回归中看到的⾮常相似,其中梯度是观测值y和估计值y^之间的差异。

  • 5. 模型性能评估

在训练sofmax回归模型后,给出任何样本特征,我们可以预测每个输出类别的概率。通常我们使⽤预测概率最⾼的类别作为输出类别。如果预测与实际类别(标签)⼀致,则预测是正确的。在接下来的实验中,我们将使⽤精度(accuracy)来评估模型的性能。精度等于正确预测数与预测总数之间的⽐率。

softmax回归实现

、读取部分图片数据并可视化

import torch
import torchvision
from torch.utils import data
from torchvision import transforms
import matplotlib.pyplot as plt
import time
trans = transforms.ToTensor()       #实例化
FashionMNIST_Trainset_file = "../data"
FashionMNIST_Testset_file = "../data"
mnist_train = torchvision.datasets.FashionMNIST(root=FashionMNIST_Trainset_file, train=True, transform=trans, download=True)
mnist_test = torchvision.datasets.FashionMNIST(root=FashionMNIST_Trainset_file, train=False, transform=trans, download=True)

print(len(mnist_train), len(mnist_test))


# 获取文本标签
def get_fashion_mnist_labels(labels):
    # 获取文本标签
    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
    # 绘制图像列表
    figsize = (num_cols * scale, num_rows * scale)
    fig, 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.axis('off')
        if titles:
            ax.set_title(titles[i], fontsize=10, loc='center')
    plt.show()

train_x, train_y = next(iter(data.DataLoader(mnist_train, batch_size= 18)))
show_images(train_x.reshape(18, 28, 28), 2, 9, titles = get_fashion_mnist_labels(train_y))


、读取小批量数据并计算运行时间

batch_size = 256

""" 使⽤多进程来读取数据 """
def get_dataloader_workers(worker_num = 8):
    return worker_num

train_iter = data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers= get_dataloader_workers(8))
time_start = time.time()
for x, y in train_iter:
    continue
time_stop = time.time()

    
def load_data_fashion_mnist(batch_size, resize=None): #@save
    trans = [transforms.ToTensor()]
    if resize:
        trans.insert(0, transforms.Resize(resize))
    trans = transforms.Compose(trans)
    mnist_train = torchvision.datasets.FashionMNIST(root=FashionMNIST_Trainset_file, train=True, transform=trans, download=True)
    mnist_test = torchvision.datasets.FashionMNIST(root=FashionMNIST_Testset_file, train=False, transform=trans, download=True)
    return (data.DataLoader(mnist_train, batch_size, shuffle=True,num_workers=get_dataloader_workers()),
            data.DataLoader(mnist_test, batch_size, shuffle=False,num_workers=get_dataloader_workers()))

从零开始实现softmax

回想⼀下,实现sofmax由三个步骤组成:

  1. 对每个项求幂(使⽤exp);
  2. 对每⼀⾏求和(⼩批量中每个样本是⼀⾏),得到每个样本的规范化常数;
  3. 将每⼀⾏除以其规范化常数,确保结果的和为1。
# 1. 导入所需库
import torch
from IPython import display

# 2. 构建数据生成器
batch_size = 256
train_iter, test_iter = load_data_fashion_mnist(batch_size)

# 3. 初始化模型参数
num_inputs = 28 * 28    # 输入层大小
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操作定义
def softmax(x):
    x_exp = torch.exp(x)
    parition = x_exp.sum(1, keepdim=True)
    return x_exp / parition

x = torch.normal(0, 1, (2, 5))
X_prob = softmax(x)
X_prob, X_prob.sum(1)

# 5. 定义模型
def net(x):
    return softmax(torch.matmul(x.reshape((-1, w.shape[0])), w) + b)

# 6. 定义损失函数:交叉熵损失函数

y = torch.tensor([0, 2])
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[range(len(y_hat)), y]

def cross_entropy(y_hat, y):
    return - torch.log(y_hat[range(len(y_hat)), y])

cross_entropy(y_hat, y)

# 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())

accuracy(y_hat, y) / len(y)

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 evaluate_accuracy(net, data_iter): #@save
    """计算在指定数据集上模型的精度"""
    if isinstance(net, torch.nn.Module):
        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]

# evaluate_accuracy(net, train_iter)
y.numel()

模型训练

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):
            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]


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 train_acc <= 1 and train_acc > 0.7, train_acc
    assert test_acc <= 1 and test_acc > 0.7, test_acc

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 = []
        
        self.fig, self.axes = plt.subplots(nrows, ncols, figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes, ]
        # 使用lambda函数捕获参数
        self.config_axes = lambda: plt.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)

lr = 0.1

def updater(batch_size):
    return torch.optim.SGD([w, b], lr, batch_size)

num_epochs = 3
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)

softmax简易实现

import torch
from torch import nn

# 1. 初始化参数
batch_size = 1000
train_iter, test_iter = load_data_fashion_mnist(batch_size)
input_num = 28 * 28
output_num = 10
num_epochs = 14

net = nn.Sequential(nn.Flatten(), nn.Linear(input_num, output_num))

def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)

net.apply(init_weights)
# 2. 损失函数
loss = nn.CrossEntropyLoss(reduction='none')
# 3. 优化方法
trainer = torch.optim.SGD(net.parameters(), lr=0.1)

train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)



def predict_ch3(net, test_iter, n=10): #@save
    """预测标签(定义⻅第3章) """
    for X, y in test_iter:
        break
    trues = get_fashion_mnist_labels(y)
    preds = get_fashion_mnist_labels(net(X).argmax(axis=1))
    titles = [true +'\n' + pred for true, pred in zip(trues, preds)]
    show_images(X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n])
predict_ch3(net, test_iter)



import torch
import torch.nn as nn
import torch.nn.functional as F
from d2l import torch as d2l
net = nn.Sequential(nn.Flatten(),
                    nn.Linear(784, 256),
                    nn.ReLU(),
                    nn.Linear(256, 10),  
                    )
def init_weight(m):
    if type(m) == nn.Linear:
        nn.init.kaiming_normal_(m.weight.data, std=0.01)

# net.apply(init_weight); 
batch_size, lr, num_epochs = 256, 0.1, 10

loss = nn.CrossEntropyLoss(reduction='none')
optimer = torch.optim.SGD(net.parameters(), lr=lr)
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, optimer)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

君逸~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值