Pytorch使用教学1-Tensor的创建

0 导读

在我们不知道什么是深度学习计算框架时,我们可以把PyTorch看做是Python的第三方库,在PyTorch中定义了适用于深度学习的张量Tensor,以及张量的各类计算。就相当于NumPy中定义的Array和对应的科学计算方法,正是这些基本数据类型和对应的方法函数,为我们进一步在PyTorch上进行深度学习建模提供了基本对象和基本工具。

因此,我们需要熟练掌握PyTorch中张量的基本操作方法。torch.Tensor是一种包含单一数据类型元素的多维矩阵。

Python 复制代码
import torch
torch.__version__
# '1.7.0'

1 张量的创建

张量的最基本创建方法和Numpy中创建Array的格式一致,都是创建函数的格式。

1.1 通过列表创建

Python 复制代码
t = torch.tensor([1, 2])
print(t)
# tensor([1, 2])

1.2 通过元组创建

Python 复制代码
t = torch.tensor((1, 2))
print(t)
# tensor([1, 2])

1.3 通过Numpy创建

Python 复制代码
import numpy as np
n = np.array([1, 2])
t = torch.tensor(n)
print(t)
# tensor([1, 2])

2 张量的数据类型

Python中,我们可以使用type()方法查看一个变量的数据类型。

2.1 type()

Python 复制代码
t = torch.tensor([1, 2])
print(type(t))
# <class 'torch.Tensor'>

Python环境中直接使用type()方法打印变量t的类型torch.Tensor。那么Tensor下有什么类型呢?我们需要使用dtype方法进行查看。

2.2 dtype

Python 复制代码
t = torch.tensor([1, 2])
print(t.dtype)
# torch.int64

我们可以看到t的大类是Tensor,更具体的说,它是torch.int64类型的变量。

2.3 type()dtype的不同

Python 复制代码
i = torch.tensor([1, 2])
f = torch.tensor([1.0, 2.0])
print(type(i), i.dtype, sep = ' , ')
print(type(f), f.dtype, sep = ' , ')
# <class 'torch.Tensor'> , torch.int64
# <class 'torch.Tensor'> , torch.float32

我们可以看到,type()不能识别出Tensor内部的数据类型,只能识别出变量的基本类型是Tensor,而dtype方法可以识别出变量具体为哪种类型的Tensor

2.4 PyTorchTensor的数据类型

PyTorch中我们常用Tensor的数据类型有整数型、浮点型和布尔型。具体如下:

数据类型 dtype
32bit浮点数 torch.float32或torch.float
64bit浮点数 torch.float64或torch.double
16bit浮点数 torch.half
8bit无符号整数 torch.unit8
8bit有符号整数 torch.int8
16bit有符号整数 torch.int16或torch.short
32bit有符号整数 torch.int32或torch.int
64bit有符号整数 torch.int64
布尔型 torch.bool
复数型 torch.complex64

此外,我们可以在创建张量时通过dtype参数直接定义它的类型。

Python 复制代码
t = torch.tensor([1, 2], dtype = torch.float64)
print(t.dtype)
# torch.float64

3 张量类型的转化

3.1 张量类型的隐式转化

NumpyArray相同,当张量各元素属于不同类型时,系统会自动进行隐式转化。

Python 复制代码
t = torch.tensor([1.1, 2])
print(t)
# tensor([1.1000, 2.0000])
Python 复制代码
t = torch.tensor([True, 2])
print(t)
# tensor([1, 2])

3.2 张量类型的转化方法

可以使用.float().int()等方法对张量类型进行转化。

Python 复制代码
t = torch.tensor([1, 2])
f = t.float()
print(f)
print(t)
# tensor([1., 2.])
# tensor([1, 2])

需要注意的是,这里并不会改变原来t的数据类型。

Pytorch张量操作大全:

Pytorch使用教学1-Tensor的创建
Pytorch使用教学2-Tensor的维度
Pytorch使用教学3-特殊张量的创建与类型转化
Pytorch使用教学4-张量的索引
Pytorch使用教学5-视图view与reshape的区别
Pytorch使用教学6-张量的分割与合并
Pytorch使用教学7-张量的广播
Pytorch使用教学8-张量的科学运算
Pytorch使用教学9-张量的线性代数运算
Pytorch使用教学10-张量操作方法大总结

相关推荐
机器之心4 分钟前
谁说Scaling Law到头了?新研究:每一步的微小提升会带来指数级增长
人工智能·openai
该用户已不存在9 分钟前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
算家计算17 分钟前
AI配音革命!B站最新开源IndexTTS2本地部署教程:精准对口型,情感随心换
人工智能·开源·aigc
量子位20 分钟前
马斯克周末血裁xAI 500人
人工智能·ai编程
算家计算29 分钟前
OpenAI最强编程模型GPT-5-Codex发布!可独立编程7小时,编程效率提升10倍
人工智能·ai编程·资讯
站大爷IP2 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
聚客AI2 小时前
🌟大模型为什么产生幻觉?预训练到推理的漏洞全揭秘
人工智能·llm·掘金·日新计划
Juchecar2 小时前
一文讲清 nn.Sequential 等容器类
人工智能
阿里云云原生3 小时前
如何快速看懂「祖传项目」?Qoder 强势推出新利器
人工智能
美团技术团队3 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法