softmax分类

参数初始化也很重要
学习了zip,enumerate用法
pytorch的广播机制

import torch
import torchvision
from torch.utils import data
from torchvision import transforms

from utils import *
W = torch.normal(0, 1, (784, 10), requires_grad=True)
b = torch.zeros(10, requires_grad=True)
batch_size=256


def load_data(batch_size, resize=None):
    trans = [transforms.ToTensor()]
    if resize:
        trans.insert(0, transforms.Resize(resize))
    trans = transforms.Compose(trans)
    mnist_train = torchvision.datasets.FashionMNIST(
        root="../data", train=True, transform=trans, download=False)
    mnist_test = torchvision.datasets.FashionMNIST(
        root="../data", train=False, transform=trans, download=False)
    return data.DataLoader(mnist_train, batch_size,shuffle=True), data.DataLoader(mnist_test, batch_size,shuffle=False)

train_iter,test_iter = load_data(batch_size)





def net(x=torch.tensor(0)):
    '''

    :param x:
    :return y_hat:
    '''
    y_hat = torch.exp(torch.matmul(x.reshape((-1,W.shape[0])), W) + b)  # flatten X
    y_hat = y_hat / y_hat.sum(1, keepdim=True)  # use broadcast
    return y_hat


def loss(y_hat=torch.tensor(0), y=torch.tensor(0)):
    '''
    :param y_hat:prediction
    :param y: reality
    :return: the difference between prediction and reality
    why is it a vector?
    '''
    return -torch.log(y_hat[range(len(y_hat)), y])


def accuracy(y_hat=torch.tensor(0), y=torch.tensor(0)):
    '''

    :param y_hat:
    :param y:
    :return: accurate number
    '''

    y_hat = torch.argmax(y_hat, 1)  # 得出y_hat所对应的类
    t = y_hat.type(y.dtype) == y
    return float(t.type(y.dtype).sum())


def evaluate_accuracy(net,data_iter):
    '''
    :param data_iter:
    :return:precision
    '''
    metric = Accumulator(2)
    for X,y in data_iter:
        metric.add(accuracy(net(X),y),y.numel())
    return (metric[0])/(metric[1])


def train_epoch(net,train_iter,loss,updater):
    metric = Accumulator(3)
    for X,y in train_iter:
        y_hat=net(X)
        l = loss(y_hat,y)
        l.sum().backward()
        updater(X.shape[0],[W,b])
        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
    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(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





num_epochs = 10
train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)

import torch
from IPython import display
from d2l import torch as d2l

class Accumulator:
    '''
    '''
    def __init__(self,n):
        self.data = [0]*n
    def add(self,*args):
        self.data=[a+float(b) for a,b in zip(self.data,args)]
    def __getitem__(self, item):
        return self.data[item]


def sgd(params,lr,batch_size):
    with torch.no_grad():
        for param in params:
            param-=lr*param.grad/batch_size
            param.grad.zero_()


def updater(batch_size,params):
    return sgd(params,0.1,batch_size)


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)
        display.clear_output(wait=True)```

### softmax分类器的作用 softmax分类器主要用于多类别分类任务,其主要作用体现在以下几个方面: 1. **概率分布转换**:给定一组输入特征,通过神经网络或其他模型计算出每个类别的预测分数(logits),然后利用`softmax`函数将这些分数转化为概率分布,使得每个类别的概率之和为1。 - 公式表示为:对于输入`x_i`(第i个类别的预测分数), \[ P(y=j|x)=\frac{e^{x_j}}{\sum_{k=1}^{n} e^{x_k}} \] 其中`n`是类别的总数,`y`是实际类别标签。 2. **概率决策**:输出的概率分布可以用于概率性地决定哪个类别最有可能是正确的。例如,在图像识别任务中,如果得到的结果是`P(猫) > P(狗) > P(汽车)`,那么模型就倾向于预测这张图片是一只猫。 3. **损失函数评估**:softmax分类器与交叉熵损失函数结合使用来评估模型的预测准确性。交叉熵损失衡量的是模型预测的概率分布与真实分布之间的差异。 - 使用交叉熵损失函数计算预测概率与实际类别标签之间的误差: \[ L=-\sum_{j} y_j \log(P(y=j|x)) \] ### 示例说明 假设我们有一个包含三个类别的分类任务(如动物分类任务,可能包括猫、狗和鸟)。我们的模型给出了如下预测分数: - `猫`: 0.4 - `狗`: 0.5 - `鸟`: 0.1 使用`softmax`函数将这些分数转化为概率: - `猫`: \(e^{0.4}/(e^{0.4} + e^{0.5} + e^{0.1}) ≈ 0.44\) - `狗`: \(e^{0.5}/(e^{0.4} + e^{0.5} + e^{0.1}) ≈ 0.47\) - `鸟`: \(e^{0.1}/(e^{0.4} + e^{0.5} + e^{0.1}) ≈ 0.09\) 最终,模型会输出概率最高的类别作为预测结果,即在这里是`狗`。 ### 相关问题: 1. **softmax与sigmoid的区别是什么?** 2. **如何调整softmax分类器以适应不平衡的数据集?** 3. **softmax分类器在实际部署中需要注意哪些事项?** --- 在这个回答中,我并没有直接引用具体的外部资源链接,而是通过文本描述和数学公式详细介绍了softmax分类器的作用及其背后的原理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值