溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

pytorch中with?torch.no_grad()怎么使用

發(fā)布時(shí)間:2022-03-11 11:40:51 來源:億速云 閱讀:1224 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“pytorch中with torch.no_grad()怎么使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“pytorch中with torch.no_grad()怎么使用”吧!

1.關(guān)于with

with是python中上下文管理器,簡單理解,當(dāng)要進(jìn)行固定的進(jìn)入,返回操作時(shí),可以將對(duì)應(yīng)需要的操作,放在with所需要的語句中。比如文件的寫入(需要打開關(guān)閉文件)等。

以下為一個(gè)文件寫入使用with的例子。

        with open (filename,'w') as sh:    
            sh.write("#!/bin/bash\n")
            sh.write("#$ -N "+'IC'+altas+str(patientNumber)+altas+'\n')
            sh.write("#$ -o "+pathSh+altas+'log.log\n') 
            sh.write("#$ -e "+pathSh+altas+'err.log\n') 
            sh.write('source ~/.bashrc\n')          
            sh.write('. "/home/kjsun/anaconda3/etc/profile.d/conda.sh"\n')
            sh.write('conda activate python27\n')
            sh.write('echo "to python"\n')
            sh.write('echo "finish"\n')
            sh.close()

with后部分,可以將with后的語句運(yùn)行,將其返回結(jié)果給到as后的變量(sh),之后的代碼塊對(duì)close進(jìn)行操作。

2.關(guān)于with torch.no_grad():

在使用pytorch時(shí),并不是所有的操作都需要進(jìn)行計(jì)算圖的生成(計(jì)算過程的構(gòu)建,以便梯度反向傳播等操作)。而對(duì)于tensor的計(jì)算操作,默認(rèn)是要進(jìn)行計(jì)算圖的構(gòu)建的,在這種情況下,可以使用 with torch.no_grad():,強(qiáng)制之后的內(nèi)容不進(jìn)行計(jì)算圖構(gòu)建。

以下分別為使用和不使用的情況:

(1)使用with torch.no_grad():

with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))        
print(outputs)

運(yùn)行結(jié)果:

Accuracy of the network on the 10000 test images: 55 %
tensor([[-2.9141, -3.8210,  2.1426,  3.0883,  2.6363,  2.6878,  2.8766,  0.3396,
         -4.7505, -3.8502],
        [-1.4012, -4.5747,  1.8557,  3.8178,  1.1430,  3.9522, -0.4563,  1.2740,
         -3.7763, -3.3633],
        [ 1.3090,  0.1812,  0.4852,  0.1315,  0.5297, -0.3215, -2.0045,  1.0426,
         -3.2699, -0.5084],
        [-0.5357, -1.9851, -0.2835, -0.3110,  2.6453,  0.7452, -1.4148,  5.6919,
         -6.3235, -1.6220]])

此時(shí)的outputs沒有 屬性。

(2)不使用with torch.no_grad():

而對(duì)應(yīng)的不使用的情況

for data in testloader:
    images, labels = data
    outputs = net(images)
    _, predicted = torch.max(outputs.data, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))
print(outputs)

結(jié)果如下:

Accuracy of the network on the 10000 test images: 55 %
tensor([[-2.9141, -3.8210,  2.1426,  3.0883,  2.6363,  2.6878,  2.8766,  0.3396,
         -4.7505, -3.8502],
        [-1.4012, -4.5747,  1.8557,  3.8178,  1.1430,  3.9522, -0.4563,  1.2740,
         -3.7763, -3.3633],
        [ 1.3090,  0.1812,  0.4852,  0.1315,  0.5297, -0.3215, -2.0045,  1.0426,
         -3.2699, -0.5084],
        [-0.5357, -1.9851, -0.2835, -0.3110,  2.6453,  0.7452, -1.4148,  5.6919,
         -6.3235, -1.6220]], grad_fn=<AddmmBackward>)

可以看到,此時(shí)有g(shù)rad_fn=<AddmmBackward>屬性,表示,計(jì)算的結(jié)果在一計(jì)算圖當(dāng)中,可以進(jìn)行梯度反傳等操作。但是,兩者計(jì)算的結(jié)果實(shí)際上是沒有區(qū)別的。

附:pytorch使用模型測(cè)試使用with torch.no_grad():

使用pytorch時(shí),并不是所有的操作都需要進(jìn)行計(jì)算圖的生成(計(jì)算過程的構(gòu)建,以便梯度反向傳播等操作)。而對(duì)于tensor的計(jì)算操作,默認(rèn)是要進(jìn)行計(jì)算圖的構(gòu)建的,在這種情況下,可以使用 with torch.no_grad():,強(qiáng)制之后的內(nèi)容不進(jìn)行計(jì)算圖構(gòu)建。

with torch.no_grad():
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
    100 * correct / total))        
print(outputs)

運(yùn)行結(jié)果:

Accuracy of the network on the 10000 test images: 55 %
tensor([[-2.9141, -3.8210,  2.1426,  3.0883,  2.6363,  2.6878,  2.8766,  0.3396,
         -4.7505, -3.8502],
        [-1.4012, -4.5747,  1.8557,  3.8178,  1.1430,  3.9522, -0.4563,  1.2740,
         -3.7763, -3.3633],
        [ 1.3090,  0.1812,  0.4852,  0.1315,  0.5297, -0.3215, -2.0045,  1.0426,
         -3.2699, -0.5084],
        [-0.5357, -1.9851, -0.2835, -0.3110,  2.6453,  0.7452, -1.4148,  5.6919,
         -6.3235, -1.6220]])

到此,相信大家對(duì)“pytorch中with torch.no_grad()怎么使用”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI