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
相关推荐
张较瘦_16 分钟前
[论文阅读] 人工智能+软件工程 | 结对编程中的知识转移新图景
人工智能·软件工程·结对编程
小Q小Q1 小时前
cmake编译LASzip和LAStools
人工智能·计算机视觉
yzx9910131 小时前
基于 Q-Learning 算法和 CNN 的强化学习实现方案
人工智能·算法·cnn
token-go1 小时前
[特殊字符] 革命性AI提示词优化平台正式开源!
人工智能·开源
cooldream20092 小时前
华为云Flexus+DeepSeek征文|基于华为云Flexus X和DeepSeek-R1打造个人知识库问答系统
人工智能·华为云·dify
老胖闲聊5 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1185 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之6 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
scdifsn6 小时前
动手学深度学习12.7. 参数服务器-笔记&练习(PyTorch)
pytorch·笔记·深度学习·分布式计算·数据并行·参数服务器
DFminer7 小时前
【LLM】fast-api 流式生成测试
人工智能·机器人