PyTorch_标量张量和数字的转换

对于只有一个元素的张量,使用 item() 函数将该值从张量中提取出来。


代码

python 复制代码
import torch 
import numpy as np 

def test01():
    tensor1 = torch.tensor(30)
    tensor2 = torch.tensor([30])
    tensor3 = torch.tensor([[30]])

    print(tensor1.item())
    print(tensor2.item())
    print(tensor3.item())

    # 注意:张量中只有一个元素,如果有多个元素的话,使用 item 函数可能会报错
    # tensor4 = torch.tensor([30, 40])
    # print(tensor4.item())


if __name__ == "__main__":
    test01() 
相关推荐
BK贝壳1 天前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
汤姆宝库1 天前
蒸馏的三层实现:logits级、序列级与数据级
人工智能·深度学习·机器学习
BD_Marathon1 天前
安装Jupyter notebook
ide·python·jupyter
云半S一1 天前
Agent学习总结补充:2
人工智能·经验分享·笔记·agent·学习分享
Zlzxzw1 天前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn1 天前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
wflynn1 天前
Inkling 2 Mini:26B 参数循环 Transformer 的本地多模态模型
人工智能·ai
hryou09221 天前
模型已经会欺骗评估员?24人爆料,OpenAI为何考虑停训
人工智能·ai编程
Csvn1 天前
Agent 能调工具那天,权限就该已经修好了——最小权限 + 人工确认(S03)
人工智能·aigc·agent
Eyfcom1 天前
〖物流低代码实战 06〗AI 生成 Schema 的工程边界:大模型能否直接接管快递软件的页面搭建?
人工智能·低代码·快递软件·物流低代码实战