千家信息网

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

发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,本篇内容主要讲解"pytorch中with torch.no_grad()怎么使用",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"pytorch中with
千家信息网最后更新 2026年11月01日pytorch中with torch.no_grad()怎么使用

本篇内容主要讲解"pytorch中with torch.no_grad()怎么使用",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"pytorch中with torch.no_grad()怎么使用"吧!

1.关于with

with是python中上下文管理器,简单理解,当要进行固定的进入,返回操作时,可以将对应需要的操作,放在with所需要的语句中。比如文件的写入(需要打开关闭文件)等。

以下为一个文件写入使用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后的语句运行,将其返回结果给到as后的变量(sh),之后的代码块对close进行操作。

2.关于with torch.no_grad():

在使用pytorch时,并不是所有的操作都需要进行计算图的生成(计算过程的构建,以便梯度反向传播等操作)。而对于tensor的计算操作,默认是要进行计算图的构建的,在这种情况下,可以使用 with torch.no_grad():,强制之后的内容不进行计算图构建。

以下分别为使用和不使用的情况:

(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)

运行结果:

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]])

此时的outputs没有 属性。

(2)不使用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)

结果如下:

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=)

可以看到,此时有grad_fn=属性,表示,计算的结果在一计算图当中,可以进行梯度反传等操作。但是,两者计算的结果实际上是没有区别的。

附:pytorch使用模型测试使用with torch.no_grad():

使用pytorch时,并不是所有的操作都需要进行计算图的生成(计算过程的构建,以便梯度反向传播等操作)。而对于tensor的计算操作,默认是要进行计算图的构建的,在这种情况下,可以使用 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)

运行结果:

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]])

到此,相信大家对"pytorch中with torch.no_grad()怎么使用"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

结果 内容 情况 文件 梯度 运行 实际 属性 语句 过程 传播 学习 强制 生成 实用 更深 下文 代码 例子 兴趣 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 互联网科技行业发展 科技互联网政务服务 广州互联网科技公司 互联网科技的发展 杭州互联网科技公司 奇酷互联网络科技公司 碳银互联网科技有限公司 互联网科技的未来发展 互联网高科技股票 广州恒生互联网科技有限 苏州五指互联网络科技有限 哈尔滨屹滨互联网科技有限公司 青海科技产业互联网发展 西安小鹰速贷互联网科技有限公司 华夏恒生科技与互联网科技 深圳艾果互联网通讯科技 上海同邻互联网科技有限公司规模 抖集互联网科技技术咨询 互联网大会出现的黑科技 银川新华互联网科技学校招聘 网络科技有限互联网 迪茉互联网科技 玉溪互联网科技怎么选 电子科技大学互联网创业大赛 本届互联网博览会上的黑科技 南博望互联网科技有限公司 广州百诚互联网科技有限公司官网 互联网金融运营模式中的金融科技 同城互联网络科技 互联网高科技绘画
0