softmax代码实现,代码原理供参考

import torch
from IPython import display
from d2l import torch as d2l
import torch.utils.data.dataloader
from matplotlib import pyplot as plt
# import pylab
batch_size=64
train_iter,test_iter=d2l.load_data_fashion_mnist(batch_size)  #训练集和测试集的迭代器

num_inputs=784
num_outputs=10

w=torch.normal(0,0.1,size=(num_inputs,num_outputs),requires_grad=True)#定义权重,高斯初始化参数
b=torch.zeros(num_outputs,requires_grad=True)#偏移量,需计算梯度

# x=torch.tensor([[1.0,2.0,3.0],[4.0,5.0,6.0]])
# x.sum(0,keepdim=True)
# x.sum(1,keepdim=True)
# 给定一个对所有元素求和的矩阵X
def softmax(x):
    x_exp=torch.exp(x)#对每个元素做指数计算
    partition=x_exp.sum(1,keepdim=True)#按照维度为一把每一行求和
    return  x_exp/partition#应用广播机制,消除量纲

# softmax实现
def net(x):
    return softmax(torch.matmul(x.reshape((-1,w.shape[0])),w)+b)#-1是自动计算的意思,w。shape0是批量大小
#把wx+b放入spftmax里面
y=torch.tensor([0,2])
y_hat=torch.tensor([[0.1,0.3,0.6],[0.3,0.2,0.5]])
y_hat[[0,1],y]

def cross_entropy(y_hat,y):#交叉熵损失函数
    return -torch.log(y_hat[range(len(y_hat)),y])

cross_entropy(y_hat,y)

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)
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:
    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 train_epoch_ch3(net,train_iter,loss,updater):
    if isinstance(net,torch.nn.Module):
        net.train()
    metric=Accumulator(3)#长度为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.size().numel())
    return metric[0]/metric[2],metric[1]/metric[2]

# 可视化
class Animator:
    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,]
        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)


# 训练函数
def train_ch3(net,train_iter,test_iter,loss,num_epochs,updater):
    animator=Animator(xlabel='epoch',xlim=[1,num_epochs],ylim=[0.3],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

lr=0.1
def updater(batch_size):
    return d2l.sgd([w,b],lr,batch_size)

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


d2l.plt.show()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

在读研究僧-深度学习

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

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

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

打赏作者

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

抵扣说明:

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

余额充值