标签:pytorch60 tensor torch 张量 Tensor print Numpy 入门
张量
张量如同数组和矩阵一样, 是一种特殊的数据结构。在PyTorch
中, 神经网络的输入、输出以及网络的参数等数据, 都是使用张量来进行描述。
张量的使用和Numpy
中的ndarrays
很类似, 区别在于张量可以在GPU
或其它专用硬件上运行, 这样可以得到更快的加速效果。如果你对ndarrays
很熟悉的话, 张量的使用对你来说就很容易了。如果不太熟悉的话, 希望这篇有关张量API
的快速入门教程能够帮到你。
import torch
import numpy as np
张量初始化
张量有很多种不同的初始化方法, 先来看看四个简单的例子:
1. 直接生成张量
由原始数据直接生成张量, 张量类型由原始数据类型决定。
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
2. 通过Numpy数组来生成张量
由已有的Numpy
数组来生成张量(反过来也可以由张量来生成Numpy
数组, 参考张量与Numpy之间的转换)。
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
3. 通过已有的张量来生成新的张量
新的张量将继承已有张量的数据属性(结构、类型), 也可以重新指定新的数据类型。
x_ones = torch.ones_like(x_data) # 保留 x_data 的属性
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # 重写 x_data 的数据类型
print(f"Random Tensor: \n {x_rand} \n") int -> float
输出:
Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.0381, 0.5780],
[0.3963, 0.0840]])
4. 通过指定数据维度来生成张量
shape
是元组类型, 用来描述张量的维数, 下面3个函数通过传入shape
来指定生成张量的维数。
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
输出:
Random Tensor:
tensor([[0.0266, 0.0553, 0.9843],
[0.0398, 0.8964, 0.3457]])
Ones Tensor:
tensor([[1., 1., 1.],
[1., 1., 1.]])
Zeros Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])
张量属性
从张量属性我们可以得到张量的维数、数据类型以及它们所存储的设备(CPU或GPU)。
来看一个简单的例子:
tensor = torch.rand(3,4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
输出:
Shape of tensor: torch.Size([3, 4]) # 维数
Datatype of tensor: torch.float32 # 数据类型
Device tensor is stored on: cpu # 存储设备
张量运算
有超过100种张量相关的运算操作, 例如转置、索引、切片、数学运算、线性代数、随机采样等。更多的运算可以在这里查看。
所有这些运算都可以在GPU上运行(相对于CPU来说可以达到更高的运算速度)。如果你使用的是Google的Colab环境, 可以通过 Edit > Notebook Settings
来分配一个GPU使用。
# 判断当前环境GPU是否可用, 然后将tensor导入GPU内运行
if torch.cuda.is_available():
tensor = tensor.to('cuda')
光说不练假把式, 接下来的例子一定要动手跑一跑。如果你对Numpy的运算非常熟悉的话, 那tensor的运算对你来说就是小菜一碟。
1. 张量的索引和切片
tensor = torch.ones(4, 4)
tensor[:,1] = 0 # 将第1列(从0开始)的数据全部赋值为0
print(tensor)
输出:
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
2. 张量的拼接
你可以通过torch.cat
方法将一组张量按照指定的维度进行拼接, 也可以参考torch.stack
方法。这个方法也可以实现拼接操作, 但和torch.cat
稍微有点不同。
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
输出:
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
3. 张量的乘积和矩阵乘法
# 逐个元素相乘结果
print(f"tensor.mul(tensor): \n {tensor.mul(tensor)} \n")
# 等价写法:
print(f"tensor * tensor: \n {tensor * tensor}")
输出:
tensor.mul(tensor):
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
tensor * tensor:
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
下面写法表示张量与张量的矩阵乘法:
print(f"tensor.matmul(tensor.T): \n {tensor.matmul(tensor.T)} \n")
# 等价写法:
print(f"tensor @ tensor.T: \n {tensor @ tensor.T}")
输出:
tensor.matmul(tensor.T):
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
tensor @ tensor.T:
tensor([[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.],
[3., 3., 3., 3.]])
4. 自动赋值运算
自动赋值运算通常在方法后有 _
作为后缀, 例如: x.copy_(y)
, x.t_()
操作会改变 x
的取值。
print(tensor, "\n")
tensor.add_(5)
print(tensor)
输出:
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
tensor([[6., 5., 6., 6.],
[6., 5., 6., 6.],
[6., 5., 6., 6.],
[6., 5., 6., 6.]])
注意:
自动赋值运算虽然可以节省内存, 但在求导时会因为丢失了中间过程而导致一些问题, 所以我们并不鼓励使用它。
Tensor与Numpy的转化
张量和Numpy array
数组在CPU上可以共用一块内存区域, 改变其中一个另一个也会随之改变。
1. 由张量变换为Numpy array数组
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
输出:
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
修改张量的值,则Numpy array
数组值也会随之改变。
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
输出:
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
2. 由Numpy array数组转为张量
n = np.ones(5)
t = torch.from_numpy(n)
修改Numpy array
数组的值,则张量值也会随之改变。
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
输出:
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
脚本的总运行时间:(0 分钟 0.045 秒)
下载 Python 源码:tensor_tutorial.py
下载 Jupyter 笔记本:tensor_tutorial.ipynb
由 Sphinx 画廊生成的画廊
标签:pytorch60,tensor,torch,张量,Tensor,print,Numpy,入门 来源: https://blog.csdn.net/kevin198528/article/details/113573070
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。