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
相关推荐
小星AI10 分钟前
Claude Code 从入门到精通,一步到位
人工智能
后端小肥肠16 分钟前
Codex + Obsidian 做人生副本视频:输入主题文案,直通剪映草稿
人工智能·aigc·agent
百度Geek说1 小时前
全链路研发智能体 ——从"体感能用"到"实际可用"的工程实践
人工智能
甲维斯2 小时前
500块的豆包,能帮我搞定这个么?!
人工智能
火山引擎开发者社区2 小时前
当 Agent 自己做 SRE:详解 ArkClaw 自动化可观测体系的工程实践
人工智能
Coffeeee4 小时前
两个例子,帮你快速理解什么是Token
人工智能·程序员·ai编程
饼干哥哥4 小时前
用AI全自动剪辑,日更 100条爆款视频——HyperFrames、Remotion、Git使用入门
人工智能·机器学习·ai编程
用户83244598541325 小时前
深入拆解 AlexNet:跟着一张猫咪照片,看数据如何流动
人工智能
饼干哥哥5 小时前
开源Skills|搭建亚马逊动态关键词库系统,每天抓SSS级机会词
人工智能·深度学习·数据分析
Weigang5 小时前
别等 Agent 上线后补评估:先用 DeepEval 写失败样本
人工智能