CIFAR10

import torch.optim
from torch.utils.tensorboard import SummaryWriter

# from model import *   # 注意model文件和train文件是在同一个目录底下
import torchvision.datasets
from torch import nn
import torchvision.transforms as transforms
from torch.nn import *
from torch.utils.data import DataLoader
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

#对训练集及测试集数据的不同处理组合
transform_train = transforms.Compose([
    transforms.RandomHorizontalFlip(), #依据概率p对PIL图片进行水平翻转
    transforms.RandomGrayscale(), #依概率p将图片转换为灰度图,若通道数为3,则3 channel with r == g == b
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
transform_test = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

# 准备数据
train_data = torchvision.datasets.CIFAR10("dataset", train=True, transform=transform_train, download=True)

test_data = torchvision.datasets.CIFAR10("dataset", train=False, transform=transform_test, download=True)

# length 长度
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练数据集的长度:{}".format(train_data_size))
print("测试数据集的长度:{}".format(test_data_size))

# 利用dataloader加载数据集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)


class Xiong10(nn.Module):
    def __init__(self):
        super(Xiong10, self).__init__()
        self.model1 = Sequential(
            Conv2d(3, 16, 3, padding=1),
            nn.ReLU(),
            Conv2d(16, 32, 3, padding=1),
            nn.ReLU(),
            MaxPool2d(2),
            Conv2d(32, 64, 3, padding=1),
            nn.ReLU(),
            Conv2d(64, 128, 3, padding=1),
            nn.ReLU(),
            MaxPool2d(2),
            Conv2d(128, 256, 3, padding=1),
            nn.ReLU(),
            MaxPool2d(2),
            Flatten(),
            Linear(256*4*4, 64),
            Linear(64, 10)
        )

    def forward(self, x):
        x = self.model1(x)
        return x


# 创建网络模型
xiong = Xiong10()

# 损失函数
loss_fn = nn.CrossEntropyLoss()

# 优化器
learnning_rate = 1e-3
optim = torch.optim.Adam(xiong.parameters(), lr=learnning_rate)

# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epochs = 10

# 添加tensorboard可视化显示
writer = SummaryWriter("logs_train")

for epoch in range(epochs):
    print("------第 {} 轮训练开始------".format(epoch+1))

    train_acc = 0
    total_train_acc = 0
    total_train_loss = 0
    # 训练步骤开始
    for data in train_dataloader:
        imgs, targets = data
        outputs = xiong(imgs)
        loss = loss_fn(outputs, targets)

        # 优化器优化模型
        optim.zero_grad()
        loss.backward()
        optim.step()

        total_train_step = total_train_step + 1
        train_acc = (outputs.argmax(1) == targets).sum()
        total_train_acc += train_acc
        total_train_loss += loss
        # if total_train_step % 1000 == 0:
        #     print("训练次数:{},loss:{}".format(total_train_step, loss.item()))
    print("整体训练集上的loss:{},正确率:{:.2f}%".format(total_train_loss/train_data_size,100*total_train_acc/train_data_size))

    # writer.add_scalar("train_loss", loss.item(), total_train_step)

    # 利用现有的模型进行调优和测试
    # 测试步骤开始
    total_test_loss = 0
    # 添加正确率
    total_accuracy = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            outputs = xiong(imgs)
            loss = loss_fn(outputs, targets)
            total_test_loss = total_test_loss + loss.item()
            accuracy = (outputs.argmax(1) == targets).sum()
            total_accuracy = total_accuracy + accuracy

    print("整体测试集上的Loss:{}".format(total_test_loss/test_data_size))
    print("整体测试集上的正确率:{:.2f}%".format(100*total_accuracy/test_data_size))
    writer.add_scalar("test_loss", total_test_loss/test_data_size, total_test_step)
    writer.add_scalar("total_accuracy", total_accuracy/test_data_size, total_test_step)
    total_test_step += 1


writer.close()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值