CNN基本步骤
1.读取数据
2.创建数据加载器
3.定义模型
4.训练模型
5.测试模型
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision # 数据库模块
#1读取数据
# Mnist 手写数字
train_data = torchvision.datasets.MNIST(
root='./mnist/', # 保存或者提取位置
train=True, # this is training data
transform=torchvision.transforms.ToTensor(), # 转换 PIL.Image or numpy.ndarray 成
# torch.FloatTensor (C x H x W), 训练的时候 normalize 成 [0.0, 1.0] 区间
download=True, # 没下载就下载, 下载了就不用再下了
)
test_data = torchvision.datasets.MNIST(
root='./mnist/', # 保存或者提取位置
train=False, # this is test data
transform=torchvision.transforms.ToTensor(),
download=True, # 没下载就下载, 下载了就不用再下了
)
#2创建数据加载器
train_loader = Data.DataLoader(dataset=train_data, batch_size=64, shuffle=True)
test_loader = Data.DataLoader(dataset=test_data, batch_size=64, shuffle=True)
for x,y in test_loader:
print(x.shape)
print(y.shape,y.dtype)
break
#3定义模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential( # input shape (1, 28, 28)
nn.Conv2d(
in_channels=1, # input height
out_channels=16, # n_filters
kernel_size=5, # filter size
stride=1, # filter movement/step
padding=2, # 如果想要 con2d 出来的图片长宽没有变化, padding=(kernel_size-1)/2 当 stride=1
), # output shape (16, 28, 28)
nn.ReLU(), # activation
nn.MaxPool2d(kernel_size=2), # 在 2x2 空间里向下采样, output shape (16, 14, 14)
)
self.conv2 = nn.Sequential( # input shape (16, 14, 14)
nn.Conv2d(16, 32, 5, 1, 2), # output shape (32, 14, 14)
nn.ReLU(), # activation
nn.MaxPool2d(2), # output shape (32, 7, 7)
)
self.out = nn.Linear(32 * 7 * 7, 10) # fully connected layer, output 10 classes
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0), -1) # 展平多维的卷积图成 (batch_size, 32 * 7 * 7)
output = self.out(x)
return output
cnn=CNN()
device="cuda" if torch.cuda.is_available() else "cpu"
print("using {}".format(device))
cnn.to(device)
#优化器和损失函数
optimizer = torch.optim.Adam(cnn.parameters(), lr=0.001) # optimize all cnn parameters
loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted
#4训练模型
def train(dataloader,model,loss_fu,optimizer):
for epoch in range(5):
for batch,(x,y) in enumerate(dataloader):
x,y=x.to(device),y.to(device)
pred=model(x)
loss=loss_fu(pred,y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print("train_loss:%f"%loss.item())
train(train_loader,cnn,loss_func,optimizer)
#5测试模型
def test(dataloader,model):
size=len(dataloader.dataset)
model.eval()
test_loss,correct=0,0
with torch.no_grad():
for x,y in dataloader:
x,y=x.to(device),y.to(device)
pred=model(x)
test_loss+=loss_func(pred,y).item()
correct+=(pred.argmax(1)==y).type(torch.float).sum().item()
test_loss/=size
correct/=size
print("test_loss:%f,准确率:%f "%(test_loss,correct*100))
test(test_loader,cnn)