1.網(wǎng)絡(luò)模型轉(zhuǎn)移到CUDA上
1
2
|
net = AlexNet() net.cuda() #轉(zhuǎn)移到CUDA上 |
2.將loss轉(zhuǎn)移到CUDA上
1
2
|
criterion = nn.CrossEntropyLoss() criterion = criterion.cuda() |
這一步不做也可以,因?yàn)閘oss是根據(jù)out、label算出來的
1
|
loss = criterion(out, label) |
只要out、label在CUDA上,loss自然也在CUDA上了,但是發(fā)現(xiàn)不轉(zhuǎn)移到CUDA上準(zhǔn)確率竟然降低了1%
3.將數(shù)據(jù)集轉(zhuǎn)移到CUDA上
這里要解釋一下數(shù)據(jù)集使用方法
1
2
3
|
#download the dataset train_set = CIFAR10( "./data_cifar10" , train = True , transform = data_tf, download = True ) train_data = torch.utils.data.DataLoader(train_set, batch_size = 64 , shuffle = True ) |
dataset是把所有的input,label都制作成了一個(gè)大的多維數(shù)組
dataloader是在這個(gè)大的多維數(shù)組里采樣制作成batch,用這些batch來訓(xùn)練
1
2
3
4
5
6
7
|
for im, label in train_data: i = i + 1 im = im.cuda() #把數(shù)據(jù)遷移到CUDA上 im = Variable(im) #把數(shù)據(jù)放到Variable里 label = label.cuda() label = Variable(label) out = net(im) #the output should have the size of (N,10) |
遍歷batch的時(shí)候,首先要把拿出來的Image、label都轉(zhuǎn)移到CUDA上,這樣接下來的計(jì)算都是在CUDA上了
開始的時(shí)候只在轉(zhuǎn)成Variable以后才遷移到CUDA上,這樣在網(wǎng)絡(luò)傳播過程中就數(shù)據(jù)不是在CUDA上了,所以一直報(bào)錯(cuò)
訓(xùn)練網(wǎng)絡(luò)時(shí)指定gpu顯卡
查看有哪些可用的gpu
1
|
nvidia - smi |
實(shí)時(shí)查看gpu信息1代表每1秒刷新一次
1
|
watch - n - 1 nvidia - smi |
指定使用的gpu
1
2
3
|
import os # 使用第一張與第三張GPU卡 os.environ[ "CUDA_VISIBLE_DEVICES" ] = "0,3" |
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_41680653/article/details/93750326