机器学习模型训练之GPU使用
- 1.电脑自带GPU
- 2.kaggle之免费GPU
- 3.amazon SageMaker Studio Lab
免费GPU使用推荐
深度学习框架由大量神经元组成,它们的计算大多是矩阵运算,这类运算在计算时涉及的数据量较大,但运算形式往往只有加法和乘法,比较简单。我们计算机中的CPU可以支持复杂的逻辑运算,但是CPU的核心数往往较少,运行矩阵运算需要较长的时间,不适合进行深度学习模型的构建。与CPU相反,GPU主要负责图形计算。图形计算同样主要基于矩阵运算,这与我们的深度学习场景不谋而合。根据NVIDIA的统计数据,对于同样的深度学习模型,GPU和CPU的运算速度可以相差数百倍。因此,一个好的GPU平台对深度学习十分重要。
1.电脑自带GPU
示例:Pytorch使用GPU训练,只需修改代码中的几个地方即可。
(1)方法1:通过对网络模型、数据、损失函数这三类变量调用.cuda()来在GPU上进行训练
import time
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
# from model import *
# 运用gpu加快运算速度 .cuda()
# 改动以下几个地方:网络模型、数据(输入、标注)、损失函数
# 准备数据集
train_data = torchvision.datasets.CIFAR10(root="dataset1",train=True,transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10(root="dataset1",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
# 获取数据集的长度
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 Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3,32,5,1,2),
nn.MaxPool2d(2),
nn.Conv2d(32,32,5,1,2),
nn.MaxPool2d(2),
nn.Conv2d(32,64,5,1,2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64*4*4,64),
nn.Linear(64,10)
)
def forward(self,x):
x = self.model(x)
return x
model = Model()
if torch.cuda.is_available():
model = model.cuda()
# 损失函数
# 交叉熵
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
loss_fn = loss_fn.cuda()
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(model.parameters(),lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter("logs_train")
start_time = time.time()
for i in range(epoch):
print("------第{}轮训练开始------".format(i+1))
# 训练步骤开始
model.train()
for data in train_dataloader:
imgs,targets = data
if torch.cuda.is_available():
imgs = imgs.cuda()
targets =targets.cuda()
outputs = model(imgs)
loss = loss_fn(outputs,targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_train_step = total_train_step+1
if total_train_step % 100 ==0:
end_time = time.time()
print("训练时长为:{}".format(end_time-start_time))
print("训练次数:{},Loss:{}".format(total_train_step,loss.item()))
writer.add_scalar("train_loss",loss.item(),total_train_step)
# 测试步骤开始
model.eval()
total_test_loss = 0
total_accuracy = 0
# 无梯度
with torch.no_grad():
for data in test_dataloader:
if torch.cuda.is_available():
imgs,targets = data
imgs = imgs.cuda()
targets = targets.cuda()
outputs = model(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))
print("整体测试集上的正确率:{}".format(total_accuracy/test_data_size))
writer.add_scalar("test_loss",total_test_loss,total_test_step)
writer.add_scalar("test_accuracy",total_accuracy/test_data_size,total_test_step)
total_test_step = total_test_step+1
# 保存模型
torch.save(model,"model{}.pth".format(i))
print("模型已保存")
writer.close()
(2)方法2:指定训练设备.to(device)
import time
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
# 定义训练的设备
device = torch.device("cpu")
# device = torch.device("cuda")
# device = torch.device("cuda:0") 单显卡
# 如果有gpu就运行
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 准备数据集
train_data = torchvision.datasets.CIFAR10(root="dataset1",train=True,transform=torchvision.transforms.ToTensor(),
download=True)
test_data = torchvision.datasets.CIFAR10(root="dataset1",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
# 获取数据集的长度
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 Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3,32,5,1,2),
nn.MaxPool2d(2),
nn.Conv2d(32,32,5,1,2),
nn.MaxPool2d(2),
nn.Conv2d(32,64,5,1,2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64*4*4,64),
nn.Linear(64,10)
)
def forward(self,x):
x = self.model(x)
return x
model = Model()
model = model.to(device)
# 损失函数
# 交叉熵
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(model.parameters(),lr=learning_rate)
# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10
# 添加tensorboard
writer = SummaryWriter("logs_train")
start_time = time.time()
for i in range(epoch):
print("------第{}轮训练开始------".format(i+1))
# 训练步骤开始
model.train()
for data in train_dataloader:
imgs,targets = data
imgs = imgs.to(device)
targets =targets.to(device)
outputs = model(imgs)
loss = loss_fn(outputs,targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_train_step = total_train_step+1
if total_train_step % 100 ==0:
end_time = time.time()
print("训练时长为:{}".format(end_time-start_time))
print("训练次数:{},Loss:{}".format(total_train_step,loss.item()))
writer.add_scalar("train_loss",loss.item(),total_train_step)
# 测试步骤开始
model.eval()
total_test_loss = 0
total_accuracy = 0
# 无梯度
with torch.no_grad():
for data in test_dataloader:
imgs = imgs.to(device)
targets = targets.to(device)
targets = targets.cuda()
outputs = model(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))
print("整体测试集上的正确率:{}".format(total_accuracy/test_data_size))
writer.add_scalar("test_loss",total_test_loss,total_test_step)
writer.add_scalar("test_accuracy",total_accuracy/test_data_size,total_test_step)
total_test_step = total_test_step+1
# 保存模型
torch.save(model,"model{}.path".format(i))
print("模型已保存")
writer.close()
2.kaggle之免费GPU
链接:https://www.kaggle.com/# (1)注册账号
此处验证时,可能会出现地区不支持。可使用VPN代理,可在Microsoft Edge浏览器中安装Hoxx VPN Proxy插件,打开代理即可使用
(2)登录,create new Notebook
- 每周约30h免费使用时间
此处通过手机号验证后,可选择使用GPU、TPU
3.amazon SageMaker Studio Lab
链接:https://studiolab.sagemaker.aws/ 不需要aws账号,即可使用免费的GPU资源。Studio Lab 为用户提供了所有入门 AI 所需的基础能力,包括 JupyterLab IDE、CPU 和 GPU 模型训练算力以及 15 GB 的永久存储。
(1)进入主页,Request account
(2)完善信息,提交请求,后续收到邮件后验证通过则提交成功【此处验证时,可能会出现地区不支持。可使用VPN代理,可在Microsoft Edge浏览器中安装Hoxx VPN Proxy插件,打开代理即可使用】;
注:该请求是批量处理,可能需要等待1~5天不等,收到注册链接后,注册账号即可。
(3)注册成功后,登录后即可来到使用界面。
- 有GPU和CPU两种资源
- GPU每次使用限制为4h,4h使用完后,runtime使用环境会停止,点击stop runtime 会重新开启4h;(CPU为12h)
- 点击open project即可进行jupyter notebook环境中学习
- 可拓展学习沐神的《动手学习深度学习》