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() 
相关推荐
江畔柳前堤3 小时前
roLabelImg 详细安装教程
开发语言·人工智能·后端·云原生
阿里云大数据AI技术3 小时前
分链路差异化设计的DSP准实时数仓|钛动科技基于阿里云实时计算 Flink 版 + DLF Paimon + EMR Serverless StarRocks 的实践
人工智能·flink
陕西企来客3 小时前
2026年7月AI智能搜索曝光趋势研判
大数据·人工智能·机器学习·ai智能搜索曝光
0566463 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
阿里云大数据AI技术3 小时前
从算力到智能体,面向 Agentic AI 的基础设施演进
人工智能·agent
程序员爱德华4 小时前
Python与C++:异同点对比
c++·python
hangyuekejiGEO4 小时前
GEO技术服务选型指南
大数据·人工智能·python
阿里云大数据AI技术4 小时前
EMR Serverless Spark AI Function 的双维降本实践
人工智能·sql·spark
软萌萌的14 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
维基框架5 小时前
GitHub源码处理提速 一趟扫描反而更慢
人工智能·github