当前位置:   article > 正文

使用GPU训练模型

使用gpu训练模型

公众号后台回复关键字:Pytorch,获取项目github地址。

Pytorch没有官方的高阶API。一般通过nn.Module来构建模型并编写自定义训练循环。

为了更加方便地训练模型,作者编写了仿keras的Pytorch模型接口:torchkeras, 作为Pytorch的高阶API。

本章我们主要详细介绍Pytorch的高阶API如下相关的内容。

  • 构建模型的3种方法(继承nn.Module基类,使用nn.Sequential,辅助应用模型容器)

  • 训练模型的3种方法(脚本风格,函数风格,torchkeras.Model类风格)

  • 使用GPU训练模型(单GPU训练,多GPU训练)

本篇我们介绍使用GPU训练模型。

深度学习的训练过程常常非常耗时,一个模型训练几个小时是家常便饭,训练几天也是常有的事情,有时候甚至要训练几十天。

训练过程的耗时主要来自于两个部分,一部分来自数据准备,另一部分来自参数迭代。

当数据准备过程还是模型训练时间的主要瓶颈时,我们可以使用更多进程来准备数据。

当参数迭代过程成为训练时间的主要瓶颈时,我们通常的方法是应用GPU来进行加速。

Pytorch中使用GPU加速模型非常简单,只要将模型和数据移动到GPU上。核心代码只有以下几行。

  1. # 定义模型
  2. ... 
  3. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  4. model.to(device) # 移动模型到cuda
  5. # 训练模型
  6. ...
  7. features = features.to(device) # 移动数据到cuda
  8. labels = labels.to(device) # 或者  labels = labels.cuda() if torch.cuda.is_available() else labels
  9. ...

如果要使用多个GPU训练模型,也非常简单。只需要在将模型设置为数据并行风格模型。则模型移动到GPU上之后,会在每一个GPU上拷贝一个副本,并把数据平分到各个GPU上进行训练。核心代码如下。

  1. # 定义模型
  2. ... 
  3. if torch.cuda.device_count() > 1:
  4.     model = nn.DataParallel(model) # 包装为并行风格模型
  5. # 训练模型
  6. ...
  7. features = features.to(device) # 移动数据到cuda
  8. labels = labels.to(device) # 或者 labels = labels.cuda() if torch.cuda.is_available() else labels
  9. ...

以下是一些和GPU有关的基本操作汇总

在Colab笔记本中:修改->笔记本设置->硬件加速器 中选择 GPU

注:以下代码只能在Colab 上才能正确执行。

可点击如下链接,直接在colab中运行范例代码。

《torch使用gpu训练模型》

https://colab.research.google.com/drive/1FDmi44-U3TFRCt9MwGn4HIj2SaaWIjHu?usp=sharing

  1. import torch 
  2. from torch import nn 
  1. 1,查看gpu信息
  2. if_cuda = torch.cuda.is_available()
  3. print("if_cuda=",if_cuda)
  4. gpu_count = torch.cuda.device_count()
  5. print("gpu_count=",gpu_count)
  1. if_cuda= True
  2. gpu_count= 1
  1. 2,将张量在gpu和cpu间移动
  2. tensor = torch.rand((100,100))
  3. tensor_gpu = tensor.to("cuda:0") # 或者 tensor_gpu = tensor.cuda()
  4. print(tensor_gpu.device)
  5. print(tensor_gpu.is_cuda)
  6. tensor_cpu = tensor_gpu.to("cpu") # 或者 tensor_cpu = tensor_gpu.cpu() 
  7. print(tensor_cpu.device)
  1. cuda:0
  2. True
  3. cpu
  1. 3,将模型中的全部张量移动到gpu上
  2. net = nn.Linear(2,1)
  3. print(next(net.parameters()).is_cuda)
  4. net.to("cuda:0") # 将模型中的全部参数张量依次到GPU上,注意,无需重新赋值为 net = net.to("cuda:0")
  5. print(next(net.parameters()).is_cuda)
  6. print(next(net.parameters()).device)
  1. False
  2. True
  3. cuda:0
  1. 4,创建支持多个gpu数据并行的模型
  2. linear = nn.Linear(2,1)
  3. print(next(linear.parameters()).device)
  4. model = nn.DataParallel(linear)
  5. print(model.device_ids)
  6. print(next(model.module.parameters()).device) 
  7. #注意保存参数时要指定保存model.module的参数
  8. torch.save(model.module.state_dict(), "./data/model_parameter.pkl"
  9. linear = nn.Linear(2,1)
  10. linear.load_state_dict(torch.load("./data/model_parameter.pkl")) 
  1. cpu
  2. [0]
  3. cuda:0
  1. 5,清空cuda缓存
  2. # 该方法在cuda超内存时十分有用
  3. torch.cuda.empty_cache()

一,矩阵乘法范例

下面分别使用CPU和GPU作一个矩阵乘法,并比较其计算效率。

  1. import time
  2. import torch 
  3. from torch import nn
  1. # 使用cpu
  2. a = torch.rand((10000,200))
  3. b = torch.rand((200,10000))
  4. tic = time.time()
  5. c = torch.matmul(a,b)
  6. toc = time.time()
  7. print(toc-tic)
  8. print(a.device)
  9. print(b.device)
  1. 0.6454010009765625
  2. cpu
  3. cpu
  1. # 使用gpu
  2. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  3. a = torch.rand((10000,200),device = device) #可以指定在GPU上创建张量
  4. b = torch.rand((200,10000)) #也可以在CPU上创建张量后移动到GPU上
  5. b = b.to(device) #或者 b = b.cuda() if torch.cuda.is_available() else b 
  6. tic = time.time()
  7. c = torch.matmul(a,b)
  8. toc = time.time()
  9. print(toc-tic)
  10. print(a.device)
  11. print(b.device)
  1. 0.014541149139404297
  2. cuda:0
  3. cuda:0

二,线性回归范例

下面对比使用CPU和GPU训练一个线性回归模型的效率

1,使用CPU

  1. # 准备数据
  2. n = 1000000 #样本数量
  3. X = 10*torch.rand([n,2])-5.0  #torch.rand是均匀分布 
  4. w0 = torch.tensor([[2.0,-3.0]])
  5. b0 = torch.tensor([[10.0]])
  6. Y = X@w0.t() + b0 + torch.normal( 0.0,2.0,size = [n,1])  # @表示矩阵乘法,增加正态扰动
  1. # 定义模型
  2. class LinearRegression(nn.Module): 
  3.     def __init__(self):
  4.         super().__init__()
  5.         self.w = nn.Parameter(torch.randn_like(w0))
  6.         self.b = nn.Parameter(torch.zeros_like(b0))
  7.     #正向传播
  8.     def forward(self,x): 
  9.         return x@self.w.t() + self.b
  10.         
  11. linear = LinearRegression() 
  1. # 训练模型
  2. optimizer = torch.optim.Adam(linear.parameters(),lr = 0.1)
  3. loss_func = nn.MSELoss()
  4. def train(epoches):
  5.     tic = time.time()
  6.     for epoch in range(epoches):
  7.         optimizer.zero_grad()
  8.         Y_pred = linear(X) 
  9.         loss = loss_func(Y_pred,Y)
  10.         loss.backward() 
  11.         optimizer.step()
  12.         if epoch%50==0:
  13.             print({"epoch":epoch,"loss":loss.item()})
  14.     toc = time.time()
  15.     print("time used:",toc-tic)
  16. train(500)
  1. {'epoch'0'loss'3.996487855911255}
  2. {'epoch'50'loss'3.9969770908355713}
  3. {'epoch'100'loss'3.9964890480041504}
  4. {'epoch'150'loss'3.996488332748413}
  5. {'epoch'200'loss'3.996488094329834}
  6. {'epoch'250'loss'3.996488332748413}
  7. {'epoch'300'loss'3.996488332748413}
  8. {'epoch'350'loss'3.996488094329834}
  9. {'epoch'400'loss'3.996488332748413}
  10. {'epoch'450'loss'3.996488094329834}
  11. time used: 5.4090576171875

2,使用GPU

  1. # 准备数据
  2. n = 1000000 #样本数量
  3. X = 10*torch.rand([n,2])-5.0  #torch.rand是均匀分布 
  4. w0 = torch.tensor([[2.0,-3.0]])
  5. b0 = torch.tensor([[10.0]])
  6. Y = X@w0.t() + b0 + torch.normal( 0.0,2.0,size = [n,1])  # @表示矩阵乘法,增加正态扰动
  7. # 移动到GPU上
  8. print("torch.cuda.is_available() = ",torch.cuda.is_available())
  9. X = X.cuda()
  10. Y = Y.cuda()
  11. print("X.device:",X.device)
  12. print("Y.device:",Y.device)
  1. torch.cuda.is_available() =  True
  2. X.device: cuda:0
  3. Y.device: cuda:0
  1. # 定义模型
  2. class LinearRegression(nn.Module): 
  3.     def __init__(self):
  4.         super().__init__()
  5.         self.w = nn.Parameter(torch.randn_like(w0))
  6.         self.b = nn.Parameter(torch.zeros_like(b0))
  7.     #正向传播
  8.     def forward(self,x): 
  9.         return x@self.w.t() + self.b
  10.         
  11. linear = LinearRegression() 
  12. # 移动模型到GPU上
  13. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  14. linear.to(device)
  15. #查看模型是否已经移动到GPU上
  16. print("if on cuda:",next(linear.parameters()).is_cuda)
if on cuda: True
  1. # 训练模型
  2. optimizer = torch.optim.Adam(linear.parameters(),lr = 0.1)
  3. loss_func = nn.MSELoss()
  4. def train(epoches):
  5.     tic = time.time()
  6.     for epoch in range(epoches):
  7.         optimizer.zero_grad()
  8.         Y_pred = linear(X) 
  9.         loss = loss_func(Y_pred,Y)
  10.         loss.backward() 
  11.         optimizer.step()
  12.         if epoch%50==0:
  13.             print({"epoch":epoch,"loss":loss.item()})
  14.     toc = time.time()
  15.     print("time used:",toc-tic)
  16.     
  17. train(500)
  1. {'epoch'0'loss'3.9982845783233643}
  2. {'epoch'50'loss'3.998818874359131}
  3. {'epoch'100'loss'3.9982895851135254}
  4. {'epoch'150'loss'3.9982845783233643}
  5. {'epoch'200'loss'3.998284339904785}
  6. {'epoch'250'loss'3.9982845783233643}
  7. {'epoch'300'loss'3.9982845783233643}
  8. {'epoch'350'loss'3.9982845783233643}
  9. {'epoch'400'loss'3.9982845783233643}
  10. {'epoch'450'loss'3.9982845783233643}
  11. time used: 0.4889392852783203

三,torchkeras使用单GPU范例

下面演示使用torchkeras来应用GPU训练模型的方法。

其对应的CPU训练模型代码参见《6-2,训练模型的3种方法》

本例仅需要在它的基础上增加一行代码,在model.compile时指定 device即可。

1,准备数据

!pip install -U torchkeras 
  1. import torch 
  2. from torch import nn 
  3. import torchvision 
  4. from torchvision import transforms
  5. import torchkeras 
  1. transform = transforms.Compose([transforms.ToTensor()])
  2. ds_train = torchvision.datasets.MNIST(root="./data/minist/",train=True,download=True,transform=transform)
  3. ds_valid = torchvision.datasets.MNIST(root="./data/minist/",train=False,download=True,transform=transform)
  4. dl_train =  torch.utils.data.DataLoader(ds_train, batch_size=128, shuffle=True, num_workers=4)
  5. dl_valid =  torch.utils.data.DataLoader(ds_valid, batch_size=128, shuffle=False, num_workers=4)
  6. print(len(ds_train))
  7. print(len(ds_valid))
  1. %matplotlib inline
  2. %config InlineBackend.figure_format = 'svg'
  3. #查看部分样本
  4. from matplotlib import pyplot as plt 
  5. plt.figure(figsize=(8,8)) 
  6. for i in range(9):
  7.     img,label = ds_train[i]
  8.     img = torch.squeeze(img)
  9.     ax=plt.subplot(3,3,i+1)
  10.     ax.imshow(img.numpy())
  11.     ax.set_title("label = %d"%label)
  12.     ax.set_xticks([])
  13.     ax.set_yticks([]) 
  14. plt.show()

2,定义模型

  1. class CnnModel(nn.Module):
  2.     def __init__(self):
  3.         super().__init__()
  4.         self.layers = nn.ModuleList([
  5.             nn.Conv2d(in_channels=1,out_channels=32,kernel_size = 3),
  6.             nn.MaxPool2d(kernel_size = 2,stride = 2),
  7.             nn.Conv2d(in_channels=32,out_channels=64,kernel_size = 5),
  8.             nn.MaxPool2d(kernel_size = 2,stride = 2),
  9.             nn.Dropout2d(p = 0.1),
  10.             nn.AdaptiveMaxPool2d((1,1)),
  11.             nn.Flatten(),
  12.             nn.Linear(64,32),
  13.             nn.ReLU(),
  14.             nn.Linear(32,10)]
  15.         )
  16.     def forward(self,x):
  17.         for layer in self.layers:
  18.             x = layer(x)
  19.         return x
  20. net = CnnModel()
  21. model = torchkeras.Model(net)
  22. model.summary(input_shape=(1,32,32))
  1. ----------------------------------------------------------------
  2.         Layer (type)               Output Shape         Param #
  3. ================================================================
  4.             Conv2d-1           [-1323030]             320
  5.          MaxPool2d-2           [-1321515]               0
  6.             Conv2d-3           [-1641111]          51,264
  7.          MaxPool2d-4             [-16455]               0
  8.          Dropout2d-5             [-16455]               0
  9.  AdaptiveMaxPool2d-6             [-16411]               0
  10.            Flatten-7                   [-164]               0
  11.             Linear-8                   [-132]           2,080
  12.               ReLU-9                   [-132]               0
  13.            Linear-10                   [-110]             330
  14. ================================================================
  15. Total params: 53,994
  16. Trainable params: 53,994
  17. Non-trainable params: 0
  18. ----------------------------------------------------------------
  19. Input size (MB): 0.003906
  20. Forward/backward pass size (MB): 0.359695
  21. Params size (MB): 0.205971
  22. Estimated Total Size (MB): 0.569572
  23. ----------------------------------------------------------------

3,训练模型

  1. from sklearn.metrics import accuracy_score
  2. def accuracy(y_pred,y_true):
  3.     y_pred_cls = torch.argmax(nn.Softmax(dim=1)(y_pred),dim=1).data
  4.     return accuracy_score(y_true.cpu().numpy(),y_pred_cls.cpu().numpy()) 
  5.     # 注意此处要将数据先移动到cpu上,然后才能转换成numpy数组
  6. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  7. model.compile(loss_func = nn.CrossEntropyLoss(),
  8.              optimizer= torch.optim.Adam(model.parameters(),lr = 0.02),
  9.              metrics_dict={"accuracy":accuracy},device = device) # 注意此处compile时指定了device
  10. dfhistory = model.fit(3,dl_train = dl_train, dl_val=dl_valid, log_step_freq=100
  1. Start Training ...
  2. ================================================================================2020-06-27 00:24:29
  3. {'step'100'loss'1.063'accuracy'0.619}
  4. {'step'200'loss'0.681'accuracy'0.764}
  5. {'step'300'loss'0.534'accuracy'0.818}
  6. {'step'400'loss'0.458'accuracy'0.847}
  7.  +-------+-------+----------+----------+--------------+
  8. | epoch |  loss | accuracy | val_loss | val_accuracy |
  9. +-------+-------+----------+----------+--------------+
  10. |   1   | 0.412 |  0.863   |  0.128   |    0.961     |
  11. +-------+-------+----------+----------+--------------+
  12. ================================================================================2020-06-27 00:24:35
  13. {'step'100'loss'0.147'accuracy'0.956}
  14. {'step'200'loss'0.156'accuracy'0.954}
  15. {'step'300'loss'0.156'accuracy'0.954}
  16. {'step'400'loss'0.157'accuracy'0.955}
  17.  +-------+-------+----------+----------+--------------+
  18. | epoch |  loss | accuracy | val_loss | val_accuracy |
  19. +-------+-------+----------+----------+--------------+
  20. |   2   | 0.153 |  0.956   |  0.085   |    0.976     |
  21. +-------+-------+----------+----------+--------------+
  22. ================================================================================2020-06-27 00:24:42
  23. {'step'100'loss'0.126'accuracy'0.965}
  24. {'step'200'loss'0.147'accuracy'0.96}
  25. {'step'300'loss'0.153'accuracy'0.959}
  26. {'step'400'loss'0.147'accuracy'0.96}
  27.  +-------+-------+----------+----------+--------------+
  28. | epoch |  loss | accuracy | val_loss | val_accuracy |
  29. +-------+-------+----------+----------+--------------+
  30. |   3   | 0.146 |   0.96   |  0.119   |    0.968     |
  31. +-------+-------+----------+----------+--------------+
  32. ================================================================================2020-06-27 00:24:48
  33. Finished Training...

4,评估模型

  1. %matplotlib inline
  2. %config InlineBackend.figure_format = 'svg'
  3. import matplotlib.pyplot as plt
  4. def plot_metric(dfhistory, metric):
  5.     train_metrics = dfhistory[metric]
  6.     val_metrics = dfhistory['val_'+metric]
  7.     epochs = range(1len(train_metrics) + 1)
  8.     plt.plot(epochs, train_metrics, 'bo--')
  9.     plt.plot(epochs, val_metrics, 'ro-')
  10.     plt.title('Training and validation '+ metric)
  11.     plt.xlabel("Epochs")
  12.     plt.ylabel(metric)
  13.     plt.legend(["train_"+metric, 'val_'+metric])
  14.     plt.show()
plot_metric(dfhistory,"loss")
plot_metric(dfhistory,"accuracy")
model.evaluate(dl_valid)
{'val_accuracy'0.967068829113924'val_loss'0.11601964030650598}

5,使用模型

model.predict(dl_valid)[0:10]
  1. tensor([[ -9.2092,   3.1997,   1.4028,  -2.7135,  -0.7320,  -2.0518-20.4938,
  2.           14.6774,   1.7616,   5.8549],
  3.         [  2.8509,   4.9781,  18.0946,   0.0928,  -1.6061,  -4.1437,   4.8697,
  4.            3.8811,   4.3869,  -3.5929],
  5.         [-22.5231,  13.6643,   5.0244-11.0188-16.8147,  -9.5894,  -6.2556,
  6.          -10.5648-12.1022-19.4685],
  7.         [ 23.2670-12.0711,  -7.3968,  -8.2715,  -1.0915-12.6050,   8.0444,
  8.          -16.9339,   1.8827,  -0.2497],
  9.         [ -4.1159,   3.2102,   0.4971-11.8064,  12.1460,  -5.1650,  -6.5918,
  10.            1.0088,   0.8362,   2.5132],
  11.         [-26.1764,  15.6251,   6.1191-12.2424-13.9725-10.0540,  -7.8669,
  12.           -5.9602-11.1944-18.7890],
  13.         [ -5.0602,   3.3779,  -0.6647,  -8.5185,  10.0320,  -5.5107,  -6.9579,
  14.            2.3811,   0.2542,   3.2860],
  15.         [  4.1017,  -0.4282,   7.2220,   3.3700,  -3.6813,   1.1576,  -1.8479,
  16.            0.7450,   3.9768,   6.2640],
  17.         [  1.9689,  -0.3960,   7.4414-10.4789,   2.7066,   1.7482,   5.7971,
  18.           -4.5808,   3.0911,  -5.1971],
  19.         [ -2.9680,  -1.2369,  -0.0829,  -1.8577,   1.9380,  -0.8374,  -8.2207,
  20.            3.5060,   3.8735,  13.6762]], device='cuda:0')

6,保存模型

  1. # save the model parameters
  2. torch.save(model.state_dict(), "model_parameter.pkl")
  3. model_clone = torchkeras.Model(CnnModel())
  4. model_clone.load_state_dict(torch.load("model_parameter.pkl"))
  5. model_clone.compile(loss_func = nn.CrossEntropyLoss(),
  6.              optimizer= torch.optim.Adam(model.parameters(),lr = 0.02),
  7.              metrics_dict={"accuracy":accuracy},device = device) # 注意此处compile时指定了device
  8. model_clone.evaluate(dl_valid)
{'val_accuracy'0.967068829113924'val_loss'0.11601964030650598}

四,torchkeras使用多GPU范例

注:以下范例需要在有多个GPU的机器上跑。如果在单GPU的机器上跑,也能跑通,但是实际上使用的是单个GPU。

1,准备数据

  1. import torch 
  2. from torch import nn 
  3. import torchvision 
  4. from torchvision import transforms
  5. import torchkeras 
  1. transform = transforms.Compose([transforms.ToTensor()])
  2. ds_train = torchvision.datasets.MNIST(root="./data/minist/",train=True,download=True,transform=transform)
  3. ds_valid = torchvision.datasets.MNIST(root="./data/minist/",train=False,download=True,transform=transform)
  4. dl_train =  torch.utils.data.DataLoader(ds_train, batch_size=128, shuffle=True, num_workers=4)
  5. dl_valid =  torch.utils.data.DataLoader(ds_valid, batch_size=128, shuffle=False, num_workers=4)
  6. print(len(ds_train))
  7. print(len(ds_valid))

2,定义模型

  1. class CnnModule(nn.Module):
  2.     def __init__(self):
  3.         super().__init__()
  4.         self.layers = nn.ModuleList([
  5.             nn.Conv2d(in_channels=1,out_channels=32,kernel_size = 3),
  6.             nn.MaxPool2d(kernel_size = 2,stride = 2),
  7.             nn.Conv2d(in_channels=32,out_channels=64,kernel_size = 5),
  8.             nn.MaxPool2d(kernel_size = 2,stride = 2),
  9.             nn.Dropout2d(p = 0.1),
  10.             nn.AdaptiveMaxPool2d((1,1)),
  11.             nn.Flatten(),
  12.             nn.Linear(64,32),
  13.             nn.ReLU(),
  14.             nn.Linear(32,10)]
  15.         )
  16.     def forward(self,x):
  17.         for layer in self.layers:
  18.             x = layer(x)  
  19.         return x
  20. net = nn.DataParallel(CnnModule())  #Attention this line!!!
  21. model = torchkeras.Model(net)
  22. model.summary(input_shape=(1,32,32))

3,训练模型

  1. from sklearn.metrics import accuracy_score
  2. def accuracy(y_pred,y_true):
  3.     y_pred_cls = torch.argmax(nn.Softmax(dim=1)(y_pred),dim=1).data
  4.     return accuracy_score(y_true.cpu().numpy(),y_pred_cls.cpu().numpy()) 
  5.     # 注意此处要将数据先移动到cpu上,然后才能转换成numpy数组
  6. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  7. model.compile(loss_func = nn.CrossEntropyLoss(),
  8.              optimizer= torch.optim.Adam(model.parameters(),lr = 0.02),
  9.              metrics_dict={"accuracy":accuracy},device = device) # 注意此处compile时指定了device
  10. dfhistory = model.fit(3,dl_train = dl_train, dl_val=dl_valid, log_step_freq=100
  1. Start Training ...
  2. ================================================================================2020-06-27 00:24:29
  3. {'step'100'loss'1.063'accuracy'0.619}
  4. {'step'200'loss'0.681'accuracy'0.764}
  5. {'step'300'loss'0.534'accuracy'0.818}
  6. {'step'400'loss'0.458'accuracy'0.847}
  7.  +-------+-------+----------+----------+--------------+
  8. | epoch |  loss | accuracy | val_loss | val_accuracy |
  9. +-------+-------+----------+----------+--------------+
  10. |   1   | 0.412 |  0.863   |  0.128   |    0.961     |
  11. +-------+-------+----------+----------+--------------+
  12. ================================================================================2020-06-27 00:24:35
  13. {'step'100'loss'0.147'accuracy'0.956}
  14. {'step'200'loss'0.156'accuracy'0.954}
  15. {'step'300'loss'0.156'accuracy'0.954}
  16. {'step'400'loss'0.157'accuracy'0.955}
  17.  +-------+-------+----------+----------+--------------+
  18. | epoch |  loss | accuracy | val_loss | val_accuracy |
  19. +-------+-------+----------+----------+--------------+
  20. |   2   | 0.153 |  0.956   |  0.085   |    0.976     |
  21. +-------+-------+----------+----------+--------------+
  22. ================================================================================2020-06-27 00:24:42
  23. {'step'100'loss'0.126'accuracy'0.965}
  24. {'step'200'loss'0.147'accuracy'0.96}
  25. {'step'300'loss'0.153'accuracy'0.959}
  26. {'step'400'loss'0.147'accuracy'0.96}
  27.  +-------+-------+----------+----------+--------------+
  28. | epoch |  loss | accuracy | val_loss | val_accuracy |
  29. +-------+-------+----------+----------+--------------+
  30. |   3   | 0.146 |   0.96   |  0.119   |    0.968     |
  31. +-------+-------+----------+----------+--------------+
  32. ================================================================================2020-06-27 00:24:48
  33. Finished Training...

4,评估模型

  1. %matplotlib inline
  2. %config InlineBackend.figure_format = 'svg'
  3. import matplotlib.pyplot as plt
  4. def plot_metric(dfhistory, metric):
  5.     train_metrics = dfhistory[metric]
  6.     val_metrics = dfhistory['val_'+metric]
  7.     epochs = range(1len(train_metrics) + 1)
  8.     plt.plot(epochs, train_metrics, 'bo--')
  9.     plt.plot(epochs, val_metrics, 'ro-')
  10.     plt.title('Training and validation '+ metric)
  11.     plt.xlabel("Epochs")
  12.     plt.ylabel(metric)
  13.     plt.legend(["train_"+metric, 'val_'+metric])
  14.     plt.show()
plot_metric(dfhistory, "loss")
plot_metric(dfhistory,"accuracy")
model.evaluate(dl_valid)
{'val_accuracy'0.9603441455696202'val_loss'0.14203246376371081}

5,使用模型

model.predict(dl_valid)[0:10]
  1. tensor([[ -9.2092,   3.1997,   1.4028,  -2.7135,  -0.7320,  -2.0518-20.4938,
  2.           14.6774,   1.7616,   5.8549],
  3.         [  2.8509,   4.9781,  18.0946,   0.0928,  -1.6061,  -4.1437,   4.8697,
  4.            3.8811,   4.3869,  -3.5929],
  5.         [-22.5231,  13.6643,   5.0244-11.0188-16.8147,  -9.5894,  -6.2556,
  6.          -10.5648-12.1022-19.4685],
  7.         [ 23.2670-12.0711,  -7.3968,  -8.2715,  -1.0915-12.6050,   8.0444,
  8.          -16.9339,   1.8827,  -0.2497],
  9.         [ -4.1159,   3.2102,   0.4971-11.8064,  12.1460,  -5.1650,  -6.5918,
  10.            1.0088,   0.8362,   2.5132],
  11.         [-26.1764,  15.6251,   6.1191-12.2424-13.9725-10.0540,  -7.8669,
  12.           -5.9602-11.1944-18.7890],
  13.         [ -5.0602,   3.3779,  -0.6647,  -8.5185,  10.0320,  -5.5107,  -6.9579,
  14.            2.3811,   0.2542,   3.2860],
  15.         [  4.1017,  -0.4282,   7.2220,   3.3700,  -3.6813,   1.1576,  -1.8479,
  16.            0.7450,   3.9768,   6.2640],
  17.         [  1.9689,  -0.3960,   7.4414-10.4789,   2.7066,   1.7482,   5.7971,
  18.           -4.5808,   3.0911,  -5.1971],
  19.         [ -2.9680,  -1.2369,  -0.0829,  -1.8577,   1.9380,  -0.8374,  -8.2207,
  20.            3.5060,   3.8735,  13.6762]], device='cuda:0')

6,保存模型

  1. # save the model parameters
  2. torch.save(model.net.module.state_dict(), "model_parameter.pkl")
  3. net_clone = CnnModel()
  4. net_clone.load_state_dict(torch.load("model_parameter.pkl"))
  5. model_clone = torchkeras.Model(net_clone)
  6. model_clone.compile(loss_func = nn.CrossEntropyLoss(),
  7.              optimizer= torch.optim.Adam(model.parameters(),lr = 0.02),
  8.              metrics_dict={"accuracy":accuracy},device = device)
  9. model_clone.evaluate(dl_valid)
{'val_accuracy'0.9603441455696202'val_loss'0.14203246376371081}

如果本书对你有所帮助,想鼓励一下作者,记得给本项目加一颗星星star⭐️,并分享给你的朋友们喔????!

如果对本书内容理解上有需要进一步和作者交流的地方,可以在公众号后台回复关键字:加群,加入读者交流群和大家讨论。

公众号后台回复关键字:pytorch,获取项目github地址。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53736?site
推荐阅读
相关标签
  

闽ICP备14008679号