pytorch7 卷积神经网络

卷积层能保留图像的空间信息,所以相对于线性变换把所有像素值展成一维来说,更能保留图像的特性。这段代码把计算放在gpu上,相对较快

 

import numpy as np
import torch
import matplotlib.pyplot as plt
from torchvision import transforms
import torch.nn.functional as F
from torchvision import datasets #与Datasets类相比,不用实现里面的函数,直接就可以取出里面的(x,y)
from torch.utils.data import DataLoader


batch_size = 64
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
#transforms.ToTensor()将数据从[0,255]范围转换到[0,1],图像转张量,transforms.Normalize是归一化,后面参数是均值和标准差

train_dataset = datasets.MNIST(root='../dataset/mnist/', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
test_dataset = datasets.MNIST(root='../dataset/mnist/', train=False, download=True, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)

class Net(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = torch.nn.Conv2d(1,10,kernel_size=5)
        self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
        self.pooling = torch.nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(320,10)

    def forward(self,x):
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        x = F.relu(self.pooling(self.conv2(x)))
        x = x.view(batch_size,-1) #-1自动算出320
        x = self.fc(x)
        return x

model = Net()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

criterion = torch.nn.CrossEntropyLoss(reduction='mean') #交叉熵
optimizer = torch.optim.SGD(model.parameters(), lr=0.01,momentum=0.5)

def train(epoch):
    sum_loss = 0
    for i,data in enumerate(train_loader, 0):
        inputs,labels = data #inputs是一个batch的输入
        #print(i,inputs.size())
        inputs, labels = inputs.to(device), labels.to(device)
        y_pred = model(inputs)
        loss = criterion(y_pred,labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        sum_loss+=loss.item()
        if(i%300==299):
            print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, sum_loss / 300))
            sum_loss = 0.0

def t():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)  # dim = 1 列是第0个维度,行是第1个维度
            #_是无用变量,占位的,因为第一个返回值是最大值,predicted是最大值的下标,只需要第二个变量
            total += labels.size(0)
            correct += (predicted == labels).sum().item()  # 张量之间的比较运算
    print('accuracy on test set: %d %% ' % (100 * correct / total))
    return correct/total


epoch_list = []
acc_list = []

if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        acc = t()
        epoch_list.append(epoch)
        acc_list.append(acc)

    plt.plot(epoch_list, acc_list)
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.show()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值