1-Pytorch初始化张量和张量的类型

1-Pytorch初始化张量和张量的类型

1 导入必备库

python 复制代码
import torch
import numpy as np

2 初始化张量

python 复制代码
# 初始化张量
t = torch.tensor([1,2])#.type(torch.FloatTensor)
print(t)
print(t.dtype)

输出:

复制代码
tensor([1, 2])
torch.int64

3 创建float型张量

python 复制代码
# 创建float型张量
t = torch.FloatTensor([1,2])
print(t)
print(t.dtype)

t = torch.LongTensor([1,2])#int型
print(t)
print(t.dtype)

输出:

复制代码
tensor([1., 2.])
torch.float32
tensor([1, 2])
torch.int64

4 从Numpy数组ndarray创建张量

python 复制代码
# 从Numpy数组ndarray创建张量
np_array = np.array([[1,2],[3,4]])
t_np = torch.from_numpy(np_array)#.type(torch.int32)
print(t_np)

'''张量的ndarray类型主要包含:
    32位浮点型:torch.float32/torh.float(常用),相当于torch.FloatTensor
    64位浮点型:torch.float64
    16位浮点型:torch.float16
    64位整型:torch.in64/torch.long(常用),相当于torch.LongTensor
    32位整型:torch.int32
    16位整型:torch.int16
    8位整型:torch.int8
'''
print(torch.float == torch.float32)
print(torch.long == torch.int64)

输出:

复制代码
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
True
True

5 构建张量时用dtype明确其类型,或者用type

python 复制代码
# 构建张量时用dtype明确其类型,或者用type
t = torch.tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
print(t)
print(t.dtype)

t = torch.tensor([[1, 2],
        [3, 4]]).type(torch.int32)
print(t)
print(t.dtype)

输出:

复制代码
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
torch.int32
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
torch.int32

6 等价转换int64和float32

python 复制代码
t = torch.tensor([[1, 2],
        [3, 4]]).type(torch.int32)
print(t)
print(t.dtype)

t = t.long()    #等同int64
print(t)
print(t.dtype)

t = t.float()   #等同float32
print(t)
print(t.dtype)

输出:

复制代码
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
torch.int32
tensor([[1, 2],
        [3, 4]])
torch.int64
tensor([[1., 2.],
        [3., 4.]])
torch.float32
相关推荐
知识浅谈17 小时前
Transformer 中的 Q、K、V 到底是什么?怎么理解 Query、Key、Value?
人工智能·深度学习·transformer
名不经传的养虾人17 小时前
从0到1:企业级AI项目迭代日记 Vol.36|临时方案下线,网关区分负载,用量穿透链路——这一周全是“归位”
人工智能·ai编程·ai工作流·企业ai·多agent协作
小程故事多_8017 小时前
拆解Hermes Agent技术架构,会自我迭代的开源智能体如何突破AI传统局限
人工智能·架构·开源
黎阳之光17 小时前
数智透明·安全兜底|黎阳之光透明矿山,AI+数字孪生守护矿山生命线
人工智能·物联网·算法·安全·数字孪生
Bigger17 小时前
mini-cc 的 MCP 协议:给 AI 装个 USB-C 接口
人工智能·ai编程·claude
AI_yangxi17 小时前
短视频矩阵系统哪个稳定
大数据·人工智能·矩阵
方向研究17 小时前
态势感知AI基金
人工智能
2601_9577867717 小时前
企业矩阵系统的实践与内容协同价值分析
大数据·人工智能·内容协同·数字化获客
lihui_cbdd17 小时前
HPC 集群上 OpenMM GPU 多版本安装实战指南
运维·服务器·人工智能·计算化学
人工智能培训17 小时前
设备故障?数字孪生提前预警
人工智能·深度学习·神经网络·机器学习·生成对抗网络