深入理解Numpy和Tensorflow中的Axis操作

in #cn-stem5 years ago (edited)

image.png
image from unsplash by Joshua Sortino

机器学习中我们需要对多维度的数据进行处理,所以搞清楚数据的维度以及numpy 和 tensorflow 对于维度的定义就非常关键了。这里我们以 numpy 为例,因为 Tensorflow 的数据格式与 numpy 类似。

1. Axis的数量即为数据的维度

在数学和物理中,维度通常被解释为空间中描述一个位置所需的最少坐标个数(基底的位数)。然而在 numpy 中 axis 的个数就是数据的维度,体现在具体数据上就是括号的层数

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

举个例子a,看似一个3x3的三维矩阵,然而,实际上只有两层括号的嵌套,所以a只有两个维度,也即两个axis。只不过每个axis的长度为3。

>>> a.shape
(3, 3)

我们要引用"5"这个元素,只需要索引axis[0] = 1,axis[1] = 1 即

>>> a[1,1]
5

2. 从内到外"扒开"张量

要写一个高维度的数据还是比较麻烦,不过我们可以用rehape,将一个4x3的二维张量转换成一个2x2x3 的三维张量,注意这里: 4x3 = 2x2x3

>>> b=np.array([[1,4,8],[2,3,5],[2,5,1],[1,10,7]])    
>>> b.shape
(4, 3)
>>> b=b.reshape(2,2,3)
>>> b
array([[[ 1,  4,  8],
        [ 2,  3,  5]],

       [[ 2,  5,  1],
        [ 1, 10,  7]]])
>>> b.shape
(2, 2, 3)

我发现,要引用一个元素,比如'7',从内到外"扒开"来看,通常比较容易。最内层的括号 "7"排在第3个,即axis[2] = 2;中间层"7",所在的括号排在第2个,即 axis[1] = 1;最外层"7"所嵌套的括号排在第2个,即axis[0] = 1。所以要引用"7" 这个元素,我们需要

>>> b[1,1,2]
7

3. 对axis进行操作

在 numpy 中队axis = n 的操作,即是对第n层(n从0开始)的操作。我们这里以 sum 求和函数为例。同样的从内到外理解 sum 是如何对不同 axis (层) 进行操作的。

>>> b
array([[[ 1,  4,  8],
        [ 2,  3,  5]],

       [[ 2,  5,  1],
        [ 1, 10,  7]]])

首先如果对最内层 (axis = -1 或 2)操作,可以想象,将最内层括号内的元素进行"挤压","挤压"(求和)后最内层括号消失即:

[ 1, 4, 8] —> 13

[ 2, 3, 5] —> 10

[ 2, 5, 1] —> 8

[ 1, 10, 7] —> 18

同时外层结构(括号嵌套)不变

>>> b.sum(axis = 2)
array([[13, 10],
       [ 8, 18]])

中间层 (axis = 1)的操作,即可以想象,将中间层括号内的元素进行"挤压",完成后,中间层括号消失。

[ 1, 4, 8] + [ 2, 3, 5] —> [ 3, 7, 13]

[ 2, 5, 1] + [ 1, 10, 7]—>[ 3, 15, 8]

同时内层和外层结构(括号嵌套)不变

>>> b.sum(axis = 1)
array([[ 3,  7, 13],
       [ 3, 15,  8]])

最外层(axis = 0)的操作,即可以想象,将最外层内的元素进行"挤压",完成后,最外层括号消失。

[[ 1, 4, 8], [ 2, 3, 5]] + [[ 2, 5, 1], [ 1, 10, 7]] —>[[ 3, 7, 13],[ 3, 15, 8]]

同时内两层结构(括号嵌套)不变

>>> b.sum(axis = 1)
array([[ 3,  7, 13],
       [ 3, 15,  8]])

4. 总结

刚开始接触 axis 操作的时候与大多数人理解一样,axis = 0 即代表往跨行操作,axis = 1即代表往跨列操作。这种理解方式仅对二维矩阵有效,遇到高维张量就束手无策了。希望今天介绍的这种从内到外"扒开"张量的理解方式对读者有所启发。


同步到我的简书
https://www.jianshu.com/u/bd506afc6fc1

Sort:  

你那里天气如何?想要玩STEEM的第一款卡牌对战游戏吗?快来steemmonsters.com如果不想再收到我的留言,请回复“取消”。



This post has been voted on by the SteemSTEM curation team and voting trail. It is elligible for support from @curie.

If you appreciate the work we are doing, then consider supporting our witness stem.witness. Additional witness support to the curie witness would be appreciated as well.

For additional information please join us on the SteemSTEM discord and to get to know the rest of the community!

Please consider setting @steemstem as a beneficiary to your post to get a stronger support.

Please consider using the steemstem.io app to get a stronger support.

Coin Marketplace

STEEM 0.30
TRX 0.11
JST 0.033
BTC 64106.00
ETH 3129.71
USDT 1.00
SBD 4.16