【Pytorch神经网络实战案例】01 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-方法①
生活随笔
收集整理的這篇文章主要介紹了
【Pytorch神经网络实战案例】01 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-方法①
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import torch
import torchvision
from torch import nn
from torch.utils.tensorboard import SummaryWriterfrom torch.utils.data import DataLoader# 取消全局證書驗證(當項目對安全性問題不太重視時,推薦使用,可以全局取消證書的驗證,簡易方便)
import ssl
ssl._create_default_https_context = ssl._create_unverified_context# 準備數據集
train_data=torchvision.datasets.CIFAR10("datas-train",train=True,transform=torchvision.transforms.ToTensor(),download=True)
test_data=torchvision.datasets.CIFAR10("datas-test",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加載數據集
# Batch Size定義:一次訓練所選取的樣本數。
# Batch Size的大小影響模型的優化程度和速度。同時其直接影響到GPU內存的使用情況,假如你GPU內存不大,該數值最好設置小一點。
train_dataloader=DataLoader(train_data,batch_size=64)
test_dataloader=DataLoader(test_data,batch_size=64)# 創建網絡模型
# 搭建神經網絡
class Tudui(nn.Module):def __init__(self):super(Tudui, self).__init__()self.model = nn.Sequential(# Conv2d中##in_channels:輸入的通道數目 【必選】##out_channels: 輸出的通道數目 【必選】##kernel_size:卷積核的大小,類型為int 或者元組,當卷積是方形的時候,只需要一個整數邊長即可,卷積不是方形,要輸入一個元組表示 高和寬。【必選】##stride: 卷積每次滑動的步長為多少,默認是 1 【可選】##padding(手動計算):設置在所有邊界增加值為0的邊距的大小(也就是在feature map 外圍增加幾圈 0 ),## 例如當 padding =1 的時候,如果原來大小為 3 × 3 ,那么之后的大小為 5 × 5 。即在外圍加了一圈 0 。【可選】##dilation:控制卷積核之間的間距【可選】nn.Conv2d(3, 32, 5, 1, 2),# MaxPool2d中:# #kernel_size(int or tuple) - max pooling的窗口大小,# # stride(int or tuple, optional) - max pooling的窗口移動的步長。默認值是kernel_size# # padding(int or tuple, optional) - 輸入的每一條邊補充0的層數# # dilation(int or tuple, optional) – 一個控制窗口中元素步幅的參數# # return_indices - 如果等于True,會返回輸出最大值的序號,對于上采樣操作會有幫助# # ceil_mode - 如果等于True,計算輸出信號大小的時候,會使用向上取整,代替默認的向下取整的操作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()是用于設置網絡中的全連接層的,在二維圖像處理的任務中,全連接層的輸入與輸出一般都設置為二維張量,形狀通常為[batch_size, size]# 相當于一個輸入為[batch_size, in_features]的張量變換成了[batch_size, out_features]的輸出張量。nn.Linear(64*4*4, 64),nn.Linear(64, 10))def forward(self, x):x = self.model(x)return xtudui=Tudui()#使用GPU訓練方法①---》模型修改
tudui=tudui.cuda()# 損失函數
# 使用交叉熵==>分類
loss_fn=nn.CrossEntropyLoss()if torch.cuda.is_available():#使用GPU訓練方法①---》損失函數修改loss_fn=loss_fn.cuda()# 優化器
learning_rate=0.01 #學習速率
optimizer=torch.optim.SGD(tudui.parameters(),lr=learning_rate)#設置訓練網絡的參數
#記錄訓練的次數
total_train_step=0
# 記錄測試的次數
test_train_step=0
# 訓練的輪次
epoch=10
# 添加tensorboard
writer=SummaryWriter("firstjuan")for i in range(epoch): #0-9print("-----------第{}輪訓練開始-----------".format(i+1))tudui.train()# 訓練步驟開始for data in train_dataloader:imgs,targets=dataif torch.cuda.is_available():# 使用GPU訓練方法①--》測試數據修改imgs = imgs.cuda()targets = targets.cuda()outputs=tudui(imgs)#將計算所得的output的數值與真實數值進行對比,即求差loss=loss_fn(outputs,torch.squeeze(targets).long())#優化器優化模型optimizer.zero_grad()loss.backward()optimizer.step()# 記錄訓練train的次數+1total_train_step=total_train_step+1if total_train_step %100==0 : #減少輸出 方便查看測試結果print("訓練次數:{},損失值loss:{}".format(total_train_step,loss))writer.add_scalar("train_loss",loss.item(),total_train_step)# 測試步驟開始tudui.eval()total_test_loss=0# 正確率total_accuracy=0with torch.no_grad(): #保證網絡模型的梯度保持沒有,僅需要測試,不需要對梯度進行優化與調整for data in test_dataloader:imgs,targets=dataif torch.cuda.is_available():# 使用GPU訓練方法①--》測試數據修改imgs=imgs.cuda()targets=targets.cuda()outputs=tudui(imgs)loss=loss_fn(outputs,targets)total_test_loss=total_test_loss+loss.item()# 1為橫向 0為豎 計算正確率accuracy=(outputs.argmax(1)==targets).sum()total_accuracy=total_accuracy+accuracyprint("整體測試集上的Loss:{}".format(total_test_loss))print("整體測試集上的正確率accuracy:{}".format(total_accuracy/test_data_size))writer.add_scalar("test_accuracy", total_test_loss, test_train_step)writer.add_scalar("test_loss",total_accuracy/test_data_size,test_train_step)# 記錄測試test的次數+1test_train_step=test_train_step+1# 保存模型# torch.save(tudui.state_dict(),"tudui_{}".format(i))torch.save(tudui,"tudui_{}".format(i))print("模型已經保存")
writer.close()
import torch
from torch import nn# 搭建神經網絡
class Tudui(nn.Module):def __init__(self):super(Tudui, self).__init__()self.model = nn.Sequential(# Conv2d中##in_channels:輸入的通道數目 【必選】##out_channels: 輸出的通道數目 【必選】##kernel_size:卷積核的大小,類型為int 或者元組,當卷積是方形的時候,只需要一個整數邊長即可,卷積不是方形,要輸入一個元組表示 高和寬。【必選】##stride: 卷積每次滑動的步長為多少,默認是 1 【可選】##padding(手動計算):設置在所有邊界增加值為0的邊距的大小(也就是在feature map 外圍增加幾圈 0 ),## 例如當 padding =1 的時候,如果原來大小為 3 × 3 ,那么之后的大小為 5 × 5 。即在外圍加了一圈 0 。【可選】##dilation:控制卷積核之間的間距【可選】nn.Conv2d(3, 32, 5, 1, 2),# MaxPool2d中:# #kernel_size(int or tuple) - max pooling的窗口大小,# # stride(int or tuple, optional) - max pooling的窗口移動的步長。默認值是kernel_size# # padding(int or tuple, optional) - 輸入的每一條邊補充0的層數# # dilation(int or tuple, optional) – 一個控制窗口中元素步幅的參數# # return_indices - 如果等于True,會返回輸出最大值的序號,對于上采樣操作會有幫助# # ceil_mode - 如果等于True,計算輸出信號大小的時候,會使用向上取整,代替默認的向下取整的操作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()是用于設置網絡中的全連接層的,在二維圖像處理的任務中,全連接層的輸入與輸出一般都設置為二維張量,形狀通常為[batch_size, size]# 相當于一個輸入為[batch_size, in_features]的張量變換成了[batch_size, out_features]的輸出張量。nn.Linear(64*4*4, 64),nn.Linear(64, 10))def forward(self, x):x = self.model(x)return xif __name__ == '__main__':tudui = Tudui()input = torch.ones((64, 3, 32, 32))output = tudui(input)print(output.shape)
總結
以上是生活随笔為你收集整理的【Pytorch神经网络实战案例】01 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-方法①的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 绿盟防火墙配置手册_双链路环境下不同品牌
- 下一篇: OpenCV_11 轮廓检测:图像的轮廓