pytorch实现softmax多分类(MNIST)

#导入各种库
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Training settings
batch_size = 64

#数据集的处理

#图片变换:转换成Tensor,标准化
transform = transforms.Compose([ transforms.ToTensor(),
                                transforms.Normalize((0.1307, ),(0.3081, ))])
#创建训练数据集
train_dataset = datasets.MNIST(root='./mnist_data/',
                               train=True, download=True,
                               transform=transform)
#导入训练数据集
train_loader = DataLoader(train_dataset,
                          shuffle=True,
                          batch_size=batch_size)
#创建测试数据集
test_dataset = datasets.MNIST(root='./mnist_data/',
                              train=False,
                              download=True,
                              transform=transform)
#导入测试数据集
test_loader = DataLoader(test_dataset,
                          shuffle=False,
                          batch_size=batch_size)

class Net(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):
        # Flatten the data (n, 1, 28, 28) --> (n, 784)
        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 F.log_softmax(self.l5(x), dim=1)

model = Net()

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

def train(epoch):
    # 每次输入barch_idx个数据
    for batch_idx, data in enumerate(train_loader):
        inputs, target = data
        optimizer.zero_grad()
        output = model(inputs)
        # loss
        loss = criterion(output, target)
        loss.backward()
        # update
        optimizer.step()
        if batch_idx % 200 == 0:   #len(data)=64,理解为batch-size,len(train_loader.dataset)=60000总样本数,len(train_loader)是有多少个loader,理解为共有多少个iterations
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(inputs), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))

def test():
    test_loss = 0
    correct = 0
    # 测试集
    # 不计算梯度,节省内存
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            output = model(images)
            # sum up batch loss
            test_loss += criterion(output, labels).item()
            # get the index of the max
            pred = output.data.max(1, keepdim=True)[1]
            correct += pred.eq(labels.data.view_as(pred)).cpu().sum()

    test_loss /= len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

for epoch in range(1,10):
    train(epoch)
    test()

log如下:
/usr/local/bin/python3.6 /Users/function/Documents/code/test2.py
Train Epoch: 1 [0/60000 (0%)] Loss: 2.309441
Train Epoch: 1 [12800/60000 (21%)] Loss: 2.183163
Train Epoch: 1 [25600/60000 (43%)] Loss: 0.835843
Train Epoch: 1 [38400/60000 (64%)] Loss: 0.439794
Train Epoch: 1 [51200/60000 (85%)] Loss: 0.261408

Test set: Average loss: 0.0057, Accuracy: 8866/10000 (89%)

Train Epoch: 2 [0/60000 (0%)] Loss: 0.508892
Train Epoch: 2 [12800/60000 (21%)] Loss: 0.333321
Train Epoch: 2 [25600/60000 (43%)] Loss: 0.200243
Train Epoch: 2 [38400/60000 (64%)] Loss: 0.277475
Train Epoch: 2 [51200/60000 (85%)] Loss: 0.187367

Test set: Average loss: 0.0030, Accuracy: 9425/10000 (94%)

Train Epoch: 3 [0/60000 (0%)] Loss: 0.145257
Train Epoch: 3 [12800/60000 (21%)] Loss: 0.043807
Train Epoch: 3 [25600/60000 (43%)] Loss: 0.183113
Train Epoch: 3 [38400/60000 (64%)] Loss: 0.186657
Train Epoch: 3 [51200/60000 (85%)] Loss: 0.101876

Test set: Average loss: 0.0022, Accuracy: 9578/10000 (96%)

Train Epoch: 4 [0/60000 (0%)] Loss: 0.184665
Train Epoch: 4 [12800/60000 (21%)] Loss: 0.340358
Train Epoch: 4 [25600/60000 (43%)] Loss: 0.151537
Train Epoch: 4 [38400/60000 (64%)] Loss: 0.025888
Train Epoch: 4 [51200/60000 (85%)] Loss: 0.175476

Test set: Average loss: 0.0020, Accuracy: 9610/10000 (96%)

Train Epoch: 5 [0/60000 (0%)] Loss: 0.112639
Train Epoch: 5 [12800/60000 (21%)] Loss: 0.130508
Train Epoch: 5 [25600/60000 (43%)] Loss: 0.107424
Train Epoch: 5 [38400/60000 (64%)] Loss: 0.023164
Train Epoch: 5 [51200/60000 (85%)] Loss: 0.075948

Test set: Average loss: 0.0017, Accuracy: 9673/10000 (97%)

Train Epoch: 6 [0/60000 (0%)] Loss: 0.037222
Train Epoch: 6 [12800/60000 (21%)] Loss: 0.033421
Train Epoch: 6 [25600/60000 (43%)] Loss: 0.019519
Train Epoch: 6 [38400/60000 (64%)] Loss: 0.229080
Train Epoch: 6 [51200/60000 (85%)] Loss: 0.012769

Test set: Average loss: 0.0015, Accuracy: 9698/10000 (97%)

Train Epoch: 7 [0/60000 (0%)] Loss: 0.024760
Train Epoch: 7 [12800/60000 (21%)] Loss: 0.043735
Train Epoch: 7 [25600/60000 (43%)] Loss: 0.025668
Train Epoch: 7 [38400/60000 (64%)] Loss: 0.030804
Train Epoch: 7 [51200/60000 (85%)] Loss: 0.048212

Test set: Average loss: 0.0014, Accuracy: 9743/10000 (97%)

Train Epoch: 8 [0/60000 (0%)] Loss: 0.061919
Train Epoch: 8 [12800/60000 (21%)] Loss: 0.047970
Train Epoch: 8 [25600/60000 (43%)] Loss: 0.088634
Train Epoch: 8 [38400/60000 (64%)] Loss: 0.069933
Train Epoch: 8 [51200/60000 (85%)] Loss: 0.010266

Test set: Average loss: 0.0013, Accuracy: 9739/10000 (97%)

Train Epoch: 9 [0/60000 (0%)] Loss: 0.024968
Train Epoch: 9 [12800/60000 (21%)] Loss: 0.024904
Train Epoch: 9 [25600/60000 (43%)] Loss: 0.071306
Train Epoch: 9 [38400/60000 (64%)] Loss: 0.003656
Train Epoch: 9 [51200/60000 (85%)] Loss: 0.023971

Test set: Average loss: 0.0012, Accuracy: 9768/10000 (98%)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,482评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,377评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,762评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,273评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,289评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,046评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,351评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,988评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,476评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,948评论 2 324
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,064评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,712评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,261评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,264评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,486评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,511评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,802评论 2 345