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
相关推荐
令狐少侠20111 分钟前
ai之RAG本地知识库--基于OCR和文本解析器的新一代RAG引擎:RAGFlow 认识和源码剖析
人工智能·ai
weixin_307779134 分钟前
批量OCR的GitHub项目
python·github·ocr
小叮当爱咖啡6 分钟前
Seq2seq+Attention 机器翻译
人工智能·自然语言处理·机器翻译
shadowcz0076 分钟前
奥特曼论人工智能、OpenAI与创业
人工智能·百度
AI人工智能+18 分钟前
应用俄文OCR技术,为跨语言交流与数字化管理提供更强大的支持
人工智能·ocr·文字识别
UQI-LIUWJ30 分钟前
李宏毅LLM笔记: AI Agent
人工智能·笔记
百度Geek说42 分钟前
百度阮瑜:百度大模型应用赋能产业智变|2025全球数字经济大会
人工智能
大明哥_1 小时前
最新 Coze 教程:40+ 条视频涨粉 10W+,利用 Coze 工作流 + 视频组件,一键制作爆款小人国微景动画视频
人工智能·agent
SugarPPig1 小时前
ReAct (Reason and Act) OR 强化学习(Reinforcement Learning, RL)
人工智能
孤狼warrior1 小时前
灰色预测模型
人工智能·python·算法·数学建模