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, 默认
相关推荐
XM_jhxx16 分钟前
±0.03mm的精度怎么保证?翌东塑胶用AI赋能质量管控升级
人工智能
阿正的梦工坊1 小时前
深入理解 PyTorch 中的 unsqueeze 操作
人工智能·pytorch·python
澈2072 小时前
C++并查集:高效解决连通性问题
java·c++·算法
秦歌6662 小时前
DeepAgents框架详解和文件后端
人工智能·langchain
测试员周周3 小时前
【Appium 系列】第06节-页面对象实现 — LoginPage 实战
开发语言·前端·人工智能·python·功能测试·appium·测试用例
霸道流氓气质3 小时前
基于 Milvus Lite 的 Spring AI RAG 向量库实践方案与示例
人工智能·spring·milvus
旖-旎3 小时前
深搜练习(单词搜索)(12)
c++·算法·深度优先·力扣
ar01233 小时前
AR巡检平台:构筑智能巡检新模式的数字化引擎
人工智能·ar
语音之家3 小时前
【预讲会征集】ACL 2026 论文预讲会
人工智能·论文·acl
碳基硅坊3 小时前
电商场景下的商品自动识别与辅助上架
人工智能