10.PyTorch_元素类型转换

1、data.type(torch.DoubleTensor)

2、data.half/double/float/short/int/long()

python 复制代码
"""
案例:
    创建指定类型的张量.

涉及到的函数:
    type(torch支持的数据类型)
    half()/double()/float()/short()/int()/long()

你要掌握的函数:
    type()
"""

# 导包
import torch

# 场景1: 直接创建指定类型的张量.
t1 = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float)  # 默认是: float32
print(f't1: {t1}, (元素)类型: {t1.dtype}, (张量)类型: {type(t1)}')  # float32
print('-' * 30)

# 场景2: 创建好张量后 -> 做类型转换.
# 思路1: type()函数, 推荐掌握.
t2 = t1.type(torch.int16)
print(f't2: {t2}, (元素)类型: {t2.dtype}, (张量)类型: {type(t2)}')  # int16
print('-' * 30)


# 思路2: half()/double()/float()/short()/int()/int()
print(t2.half())        # float16
print(t2.float())       # float32, 默认
print(t2.double())      # float64
print(t2.short())       # int16
print(t2.int())         # int32
print(t2.long())        # int64, 默认
相关推荐
武子康几秒前
MultiNet 只听到一次命令,为什么连续触发?
人工智能·后端·agent
每天都要写算法(努力版)几秒前
【行业前沿报告】AutoML / AutoResearch / RSI
人工智能·agent·rsi
全栈探索者几秒前
给视频配一段完整 BGM:一次生成还是分段拼?
人工智能·comfyui·音频生成·stable audio
Teable任意门互动6 分钟前
破解多平台数据不通!江浙沪跨境电商外贸业务私有化部署方案|任意门互动科技
大数据·人工智能·科技·信息可视化·信息与通信
自养Agent6 分钟前
AI 私有化实战:多模态本地化·视觉与音频怎么装下
人工智能·大模型·llm·音视频·语音识别
miofly9 分钟前
美团龙猫发布 LongCat-2.5:1.6T 参数原生多模态模型,主攻长程智能体任务
人工智能
lm down11 分钟前
IndexTTS 2/2.5 轻量版、Qwen3-TTS 轻量版:支持AMD、Intel、NVIDIA显卡和Mac,2GB显存可跑
人工智能·ai·音视频·tts
johnsong21 分钟前
AI前沿日报 · 2026-11-01 | 资本狂潮与安全崩塌 —— 当AI大国博弈遇上供应链暗战
人工智能·安全
u13013029 分钟前
AI 日报(2026年10月31日)
人工智能
Flynn Liang34 分钟前
让 AI 查订单、查库存、发消息:Spring AI 自定义工具(Tool)实战与工具描述工程
java·人工智能·spring·函数调用·springai·tool·自定义工具