Tensor(Pytorch神经网络界的Numpy)
摘要:Tensor,它可以是0维、一维以及多维的数组,你可以将它看作为神经网络界的Numpy,它与Numpy相似,二者可以共享内存,且之间的转换非常方便。本文分享自华为云社区《Tensor:Pytorch神经网络界的Numpy》,作者: 择城终老 。
Tensor Tensor,它可以是0维、一维以及多维的数组,你可以将它看作为神经网络界的Numpy,它与Numpy相似,二者可以共享内存,且之间的转换非常方便。
但它们也不相同,最大的区别就是Numpy会把ndarray放在CPU中进行加速运算,而由Torch产生的Tensor会放在GPU中进行加速运算。
对于Tensor,从接口划分,我们大致可分为2类:
- torch.function:如torch.sum、torch.add等。
- tensor.function:如tensor.view、tensor.add等。
- 不修改自身数据,如x.add(y),x的数据不变,返回一个新的Tensor。
- 修改自身数据,如x.add_(y),运算结果存在x中,x被修改。
现在,我们来实现2个数组对应位置相加,看看其效果就近如何:
import torchx = torch.tensor([1, 2])
y = torch.tensor([3, 4])
print(x + y)
print(x.add(y))
print(x)
print(x.add_(y))
print(x)
运行之后,效果如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/97f44f04a9d84ccf81938eb1223347c5.jpg)
文章图片
下面,我们来正式讲解Tensor的使用方式。
创建Tensor 与Numpy一样,创建Tensor也有很多的方法,可以自身的函数进行生成,也可以通过列表或者ndarray进行转换,同样也可以指定维度等。具体方法如下表(数组即张量):
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/1d978b65c26d4058a0852b798d0db7a9.png)
文章图片
这里需要注意Tensor有大写的方法也有小写的方法,具体效果我们先来看看代码:
import torcht1 = torch.tensor(1)
t2 = torch.Tensor(1)
print("值{0},类型{1}".format(t1, t1.type()))
print("值{0},类型{1}".format(t2, t2.type()))
运行之后,效果如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/137665f59d3642b5815fd017271804b4.jpg)
文章图片
其他示例如下:
import torch
import numpy as npt1 = torch.zeros(1, 2)
print(t1)
t2 = torch.arange(4)
print(t2)
t3 = torch.linspace(10, 5, 6)
print(t3)
nd = np.array([1, 2, 3, 4])
t4 = torch.from_numpy(nd)
print(t4)
其他例子基本与上面基本差不多,这里不在赘述。
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/7e340606e8884e7ea3a7d41b2545f273.jpg)
文章图片
修改Tensor维度 同样的与Numpy一样,Tensor一样有维度的修改函数,具体的方法如下表所示:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/5ea39e97281549c19a1fa7a7cd76d966.jpg)
文章图片
示例代码如下所示:
import torcht1 = torch.Tensor([[1, 2]])
print(t1)
print(t1.size())
print(t1.dim())
print(t1.view(2, 1))
print(t1.view(-1))
print(torch.unsqueeze(t1, 0))
print(t1.numel())
运行之后,效果如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/e84b7216717649269513b88366ea4966.jpg)
文章图片
截取元素 当然,我们创建Tensor张量,是为了使用里面的数据,那么就不可避免的需要获取数据进行处理,具体截取元素的方式如表:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/36f3e305a1b240c19d0ecb8abba46180.jpg)
文章图片
示例代码如下所示:
import torch# 设置随机数种子,保证每次运行结果一致
torch.manual_seed(100)
t1 = torch.randn(2, 3)
# 打印t1
print(t1)
# 输出第0行数据
print(t1[0, :])
# 输出t1大于0的数据
print(torch.masked_select(t1, t1 > 0))
# 输出t1大于0的数据索引
print(torch.nonzero(t1))
# 获取第一列第一个值,第二列第二个值,第三列第二个值为第1行的值
# 获取第二列的第二个值,第二列第二个值,第三列第二个值为第2行的值
index = torch.LongTensor([[0, 1, 1], [1, 1, 1]])
# 取0表示以行为索引
a = torch.gather(t1, 0, index)
print(a)
# 反操作填0
z = torch.zeros(2, 3)
print(z.scatter_(1, index, a))
运行之后,效果如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/a1d6c679d11141d9993ffae79ebb35bf.jpg)
文章图片
我们a = torch.gather(t1, 0, index)对其做了一个图解,方便大家理解。如下图所示:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/895fb7f797f749f6b1cf4dc40d6fe279.jpg)
文章图片
当然,我们直接有公司计算,因为这么多数据标线实在不好看,这里博主列出转换公司供大家参考:
当dim=0时,out[i,j]=input[index[i,j]][j]
当dim=1时,out[i,j]=input[i][index[i][j]]
简单的数学运算 与Numpy一样,Tensor也支持数学运算。这里,博主列出了常用的数学运算函数,方便大家参考:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/530909a1f66245e6a1e0fbf909c05149.jpg)
文章图片
需要注意的是,上面表格所有的函数操作均会创建新的Tensor,如果不需要创建新的,使用这些函数的下划线"_"版本。
示例如下:
t = torch.Tensor([[1, 2]])
t1 = torch.Tensor([[3], [4]])
t2 = torch.Tensor([5, 6])
# t+0.1*(t1/t2)
print(torch.addcdiv(t, 0.1, t1, t2))
# t+0.1*(t1*t2)
print(torch.addcmul(t, 0.1, t1, t2))
print(torch.pow(t,3))
print(torch.neg(t))
运行之后,效果如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/aac9e2540e2f45789cb5316dfb03cf3b.jpg)
文章图片
上面的这些函数都很好理解,只有一个函数相信没接触机器学习的时候,不大容易理解。也就是sigmoid()激活函数,它的公式如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/27cac547f57544a4a92ab44f3b0ff665.png)
文章图片
归并操作 简单的理解,就是对张量进行归并或者说合计等操作,这类操作的输入输出维度一般并不相同,而且往往是输入大于输出维度。而Tensor的归并函数如下表所示:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/6b8df62d728b4e5ca2099973ab619a79.jpg)
文章图片
示例代码如下所示:
t = torch.linspace(0, 10, 6)
a = t.view((2, 3))
print(a)
b = a.sum(dim=0)
print(b)
b = a.sum(dim=0, keepdim=True)
print(b)
运行之后,效果如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/ab902066a7c9435784aca836e57cd2e4.jpg)
文章图片
需要注意的是,sum函数求和之后,dim的元素个数为1,所以要被去掉,如果要保留这个维度,则应当keepdim=True,默认为False。
比较操作 【Tensor(Pytorch神经网络界的Numpy)】在量化交易中,我们一般会对股价进行比较。而Tensor张量同样也支持比较的操作,一般是进行逐元素比较。具体函数如下表:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/be47eec7750e48c1a38b3dc5d5e36277.png)
文章图片
示例代码如下所示:
t = torch.Tensor([[1, 2], [3, 4]])
t1 = torch.Tensor([[1, 1], [4, 4]])
# 获取最大值
print(torch.max(t))
# 比较张量是否相等
# equal直接返回True或False
print(torch.equal(t, t1))
# eq返回对应位置是否相等的布尔值与两者维度相同
print(torch.eq(t, t1))
# 取最大的2个元素,返回索引与值
print(torch.topk(t, 1, dim=0))
运行之后,输出如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/f2846084e8b248949dd7b363bae3a76e.jpg)
文章图片
矩阵运算 机器学习与深度学习中,存在大量的矩阵运算。与Numpy一样常用的矩阵运算一样,一种是逐元素相乘,一种是点积乘法。函数如下表所示:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/9e29e2cfaa83438dbebaa47c10b4a125.jpg)
文章图片
这里有3个主要的点积计算需要区分,dot()函数只能计算1维张量,mm()函数只能计算二维的张量,bmm只能计算三维的矩阵张量。示例如下:
# 计算1维点积
a = torch.Tensor([1, 2])
b = torch.Tensor([3, 4])
print(torch.dot(a, b))
# 计算2维点积
a = torch.randint(10, (2, 3))
b = torch.randint(6, (3, 4))
print(torch.mm(a, b))
# 计算3维点积
a = torch.randint(10, (2, 2, 3))
b = torch.randint(6, (2, 3, 4))
print(torch.bmm(a, b))
运行之后,输出如下:
![Tensor(Pytorch神经网络界的Numpy)](https://img.it610.com/image/info9/f25e1580e84e40ffa3b024a0bb2fbfde.jpg)
文章图片
点击关注,第一时间了解华为云新鲜技术~
推荐阅读
- pytorch|使用pytorch从头实现多层LSTM
- Pytorch|Pytorch AlexNet Fashion-MNIST
- pytorch|YOLOX 阅读笔记
- Pytorch学习|sklearn-SVM 模型保存、交叉验证与网格搜索
- 为Google|为Google Cloud配置深度学习环境(CUDA、cuDNN、Tensorflow2、VScode远程ssh等)
- 通过人工大脑刺激来检测神经网络中的后门
- 深度学习|深度学习笔记总结
- 神经网络Neural|神经网络Neural Networks
- ubuntu16.04-caffe-tensorflow安装教程
- demo1:|demo1: Tensorflow实现Linear regression