python - 如何将 torch.device('cuda' if torch.cuda.is_available() else 'cpu') 编写为完整的 if else 语句?
问题描述
我是 Pytorch 的初学者,想将这个语句作为一个整体输入 if else 语句:-
torch.device('cuda' if torch.cuda.is_available() else 'cpu')
有人可以帮助我吗?
解决方案
这是整个 if-else 语句的代码:
torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if torch.cuda.is_available():
torch.device('cuda')
else:
torch.device('cpu')
由于您可能想要存储设备以备后用,您可能需要这样的东西:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
这是一篇关于 Python 中三元运算符的帖子和讨论:https ://stackoverflow.com/a/2802748/13985765
从那个帖子:
value_when_true if condition else value_when_false
推荐阅读
- javascript - 从参数json打开一个html文件
- java - 在 Java 中将 Jersey 集成到 Undertow 服务器
- ios - 如何添加叠加层然后导出 UIImage?
- java - 如何使用 Mockito 2 模拟枚举类
- react-native - 我正在尝试使用反应导航,并收到此错误
- javascript - 映射函数返回未定义
- .net - 是否可以将 Powershell 变量设置为固定的 N 个字符?
- mysql - 如何使用 mysql 获得工作人员的主管
- marklogic - Marklogic 在托管文档上使用 xPath 会生成此文档的所有版本
- python - Tensorflow 对象检测在 Python 和 C++(OpenCV)之间有不同的结果