"""
演示
张量元素类型的转换
设计到的API:
data.to(torch.float32)
data.type(torch.DoubleTensor)
data.half/double/float/short/int/long()
需要掌握:
data.to(dtype,device)
"""
# 导包
import torch
# 设置设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"device:{device}")
# 1.定义函数,演示 张量的元素类型转换
def demo01():
# 1.创建张量时,指定元素类型
t1 = torch.tensor([[1,2,3],[4,5,6]], dtype=torch.float32)
print(f"t1:{t1}, shape: {t1.shape}, dtype: {t1.dtype}, device: {t1.device}")
# 2.使用data.to实现张量元素类型转换
t2 = t1.to(dtype=torch.float64)
print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}, device: {t2.device}")
t2 = t2.to(device)
print(f"t2:{t2}, shape: {t2.shape}, dtype: {t2.dtype}, device: {t2.device}")
# 3.使用data.type实现张量元素类型转换
t3 = t1.type(dtype=torch.float64)
print(f"t3:{t3}, shape: {t3.shape}, dtype: {t3.dtype}, device: {t3.device}")
# 4.使用data.double实现张量元素类型转换
t4 = t1.double()
print(f"t4:{t4}, shape: {t4.shape}, dtype: {t4.dtype}, device: {t4.device}")
# 测试
if __name__ == '__main__':
demo01()