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
相关推荐
陈大鱼头31 分钟前
[译]费尽心思来保障 OpenClaw ?那跟直接用 GPT 有什么区别?
人工智能
Fleshy数模36 分钟前
玩转OpenCV:视频椒盐噪声处理与图像形态学操作实战
人工智能·opencv·音视频
程序媛一枚~40 分钟前
✨✨✨使用Python,OpenCV及图片拼接生成❤️LOVE❤️字样图,每张小图加随机颜色边框,大图加随机大小随机颜色边框
图像处理·python·opencv·numpy·图像拼接
幂律智能43 分钟前
Agent × 流程引擎融合架构:从静态流程到智能流程编排
人工智能·架构·agent
无垠的广袤1 小时前
ChatECNU 大语言模型与 PicoClaw 部署
人工智能·语言模型·自然语言处理·嵌入式·树莓派
MediaTea1 小时前
Python:collections.Counter 常用函数及应用
开发语言·python
爱淋雨的男人1 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
互联网科技看点1 小时前
AI算力爆发叠加数据资产风口,铂拉锐科技布局去中心化数字生态
人工智能·科技·去中心化
如若1231 小时前
flash-attn 安装失败?从报错到成功的完整排雷指南(CUDA 12.8 + PyTorch 2.7)
人工智能·pytorch·python
007张三丰1 小时前
知乎高赞回答爬虫:从零开始,建立你的专属知识库
爬虫·python·知识库·python爬虫·知乎·高赞回答