● 语言环境:Python3.8
● 编译器:pycharm
● 深度学习环境:Pytorch
import matplotlib.pyplot as plt
import torch
import numpy as np
from model import *
from torchinfo import summary
# 一、 数据准备
# --- 1、设置GPU ---
import torchvision.datasets
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# --- 2、导入数据 ---
train_ds = torchvision.datasets.CIFAR10('data',
train=True,
transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
download=True)
test_ds = torchvision.datasets.CIFAR10('data',
train=False,
transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
download=False)
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_ds,
batch_size=batch_size,
shuffle=False)
test_dl = torch.utils.data.DataLoader(test_ds, batch_size=batch_size)
# --- 3、数据可视化 ---
imgs, labels = next(iter(train_dl))
plt.figure(figsize=(32, 5))
for i, imgs in enumerate(imgs):
npimg = imgs.numpy().transpose((1, 2, 0))
plt.subplot(2, 16, i + 1)
plt.imshow(npimg, cmap=plt.cm.binary)
plt.axis('off')
plt.show()
# 二、构建网络
# model.py __init__() forward()
# 加载并打印模型
model = Model().to(device)
summary(model)
# 三、模型训练
# --- 1、 设置超参数 ---
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
opt = torch.optim.SGD(model.parameters(), lr=learn_rate) # 定义优化器,随机梯度下降算法
# --- 2、编写训练函数 ---
# model.py train(dataloader, model, loss_fn, optimizer, device)
# --- 3、编写测试函数 ---
# model.py test(dataloader, model, loss_fn, optimizer, device)
# --- 4、正式训练 ---
epochs = 10
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(epochs):
model.train()
epoch_train_acc, epoch_train_loss = model.train1(train_dl, model, loss_fn, opt, device)
model.eval()
epoch_test_acc, epoch_test_loss = model.test1(test_dl, model, loss_fn, opt, device)
train_loss.append(epoch_train_loss)
train_acc.append(epoch_train_acc)
test_loss.append(epoch_test_loss)
test_acc.append(epoch_test_acc)
template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc * 100, epoch_test_loss))
print('Done')
# 四、结果可视化
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100 # 分辨率
epoch_range = range(epochs)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
plt.plot(epoch_range, train_acc, label='Training Accuracy')
plt.plot(epoch_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epoch_range, train_loss, label='Training loss')
plt.plot(epoch_range, test_loss, label='Test loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
# _*_coding:utf-8_*_
import torch
import torch.nn as nn
import torch.nn.functional as F
num_class = 10 # 图片的分类数
class Model(nn.Module):
def __init__(self):
super().__init__()
# 特征提取网络
self.conv1 = nn.Conv2d(3, 64, kernel_size=3)
self.pool1 = nn.MaxPool2d(kernel_size=2)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3)
self.pool2 = nn.MaxPool2d(kernel_size=2)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3)
self.pool3 = nn.MaxPool2d(kernel_size=2)
# 分类网络
self.fc1 = nn.Linear(512, 256)
self.fc2 = nn.Linear(256, num_class)
# 前向传播
def forward(self, x):
x = self.pool1(F.relu(self.conv1(x)))
x = self.pool2(F.relu(self.conv2(x)))
x = self.pool3(F.relu(self.conv3(x)))
x = torch.flatten(x, start_dim=1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
def train1(self, dataloader, model, loss_fn, optimizer, device):
size = len(dataloader.dataset) # 6000张图片
num_batch = len(dataloader) # 批次的数目
train_loss, train_acc = 0, 0 # 初始化训练损失 和 正确率
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X) # 计算网络输出
loss = loss_fn(pred, y) # 计算网络输出和预测的loss
# 反向传播
optimizer.zero_grad() # 梯度归零
loss.backward() # 反向传播
optimizer.step() # 自动更新参数
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
train_acc /= size
train_loss /= num_batch
return train_acc, train_loss
def test1(self, dataloader, model, loss_fn, optimizer, device):
size = len(dataloader.dataset)
number_batch = len(dataloader)
test_loss, test_acc = 0, 0 # 验证数据的损失和准确率
# 停止更新梯度
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
target_pred = model(imgs) # 网络预测结果
loss = loss_fn(target_pred, target) # 计算loss
test_loss += loss.item()
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
test_loss /= number_batch
test_acc /= size
return test_acc, test_loss
为什么model(x)可以直接调用forward(x)?
forward是自动调用的
model = Net()
y = model(x)
如上则调用网络模型定义的forward方法。
即,当把定义的网络模型model当作函数调用的时候就自动调用定义的网络模型的forward方法。
是通过nn.Module 的__call__方法调用的
就相当于调用了模型就是直接调用它的forward函数,y=model(x),这个x就是直接传入到forward函数的x参数
————————————————
版权声明:本文为CSDN博主「hxxjxw」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hxxjxw/article/details/107707471