暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PyTorch张量的创建与基本类型

AI有温度 2021-11-04
549

AI因你而升温,记得加个星标哦!

0 导读

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

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

import torch
torch.__version__
# '1.7.0'

复制

1 张量的创建

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

1.1 通过列表创建

t = torch.tensor([1, 2])
print(t)
# tensor([1, 2])

复制

1.2 通过元组创建

t = torch.tensor((1, 2))
print(t)
# tensor([1, 2])

复制

1.3 通过Numpy
创建

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

复制

2 张量的数据类型

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

2.1 type()

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

复制

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

2.2 dtype

t = torch.tensor([1, 2])
print(t.dtype)
# torch.int64

复制

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

2.3 type()
dtype
的不同

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 PyTorch
Tensor
的数据类型

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
参数直接定义它的类型。

t = torch.tensor([1, 2], dtype = torch.float64)
print(t.dtype)
# torch.float64

复制

3 张量类型的转化

3.1 张量类型的隐式转化

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

t = torch.tensor([1.1, 2])
print(t)
# tensor([1.1000, 2.0000])

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

复制

3.2 张量类型的转化方法

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

t = torch.tensor([1, 2])
f = t.float()
print(f)
print(t)
# tensor([1., 2.])
# tensor([1, 2])

复制

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


推荐阅读
TensorFlow与PyTorch到底该如何选择?
AI科普(四):通俗易懂的机器学习模型
鹅厂面试:赛马问题
文章转载自AI有温度,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论