Pytorch学习笔记

Softmax Classifier

Output a Distribution of prediction with Softmax
在这里插入图片描述

Softmax Layer

在这里插入图片描述

Softmax Layer-Example

在这里插入图片描述

Loss function - Cross Entropy

在这里插入图片描述

Cross Entropy in Pytorch

在这里插入图片描述

Implementation of classifier to MNIST dataset

Course of Training

1. Prepare dataset
2. Design model using Class inherited from nn.Module
3. Construct loss and optimizer using Pytorch API
4. Traing cycle and Test ( forward,backward,update )

1.Prepare Dataset

在这里插入图片描述
在这里插入图片描述

2.Design model using Class inherited from nn.Module

在这里插入图片描述(1)64维到10维最后一层不使用激活函数,在损失函数中Softmax层进行最后一层变化
(2)将像素转化为一个矩阵 x=x.view(-1,784)

#Design model
class Net(torch.nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.l1=torch.nn.Linear(784,512)
        self.l2=torch.nn.Linear(512,256)
        self.l3=torch.nn.Linear(256,128)
        self.l4=torch.nn.Linear(128,64)
        self.l5=torch.nn.Linear(64,10)

    def forward(self,x):
        x=x.view(-1,784)
        x=F.relu(self.l1(x))
        x=F.relu(self.l2(x))
        x=F.relu(self.l3(x))
        x=F.relu(self.l4(x))
        return self.l5(x)                   #不使用激活函数

model=Net()   

Construct loss and optimizer using Pytorch API

#Construct loss and optimizer
criterion=torch.nn.CrossEntropyLoss()
#增加冲量,跳出局部最优解和鞍点
optimizer=optim.SGD(model.parameters(),lr=0.01,momentum=0.5) 

Traing cycle and Test

#Training Cycle
def train(epoch):
    runing_loss=0.0
    for batch_idex,data in enumerate(train_loader,0):
        inputs,target=data

        optimizer.zero_grad()

        #forward+backward+update
        outputs=model(inputs)
        loss=criterion(outputs,target)
        loss.backward()

        optimizer.step()

        runing_loss +=loss.item()

        if batch_idex %300==299:
            print('[%d %5d] loss: %.3f'%(epoch+1,batch_idex+1,runing_loss/300) )
            runing_loss=0.0

def test():
    correct=0
    total=0
    with torch.no_grad():
        for data in test_loader:
            images,labels=data
            outputs=model(images)
            _,predicted=torch.max(outputs.data,dim=1)
            total +=labels.size(0)
            correct +=(predicted==labels).sum().item()
    print("Accuray on test set: %d %%"%(100*correct/total))

test

if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

在这里插入图片描述

Reference

B站刘老师Pytorch深度学习实践

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值