create account

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

View this thread on: hive.blogpeakd.comecency.com
· @hongtao · (edited)
$2.61
深入理解Numpy和Tensorflow中的Axis操作
![image.png](https://ipfs.busy.org/ipfs/QmenrrLAVzm6bFTjeKfrsoNbk9ZHTEjKQscoregsMERcFU)
image from [unsplash](https://images.unsplash.com/photo-1488229297570-58520851e868?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1649&q=80) by Joshua Sortino

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

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

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

```python
>>> 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。

```python
>>> a.shape
(3, 3)
```

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

```python
>>> a[1,1]
5
```

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

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

```python
>>> 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" 这个元素,我们需要

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

### 3. 对axis进行操作

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

```python
>>> 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

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

```python
>>> 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]

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

```python
>>> 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]]

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

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

### 4. 总结

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

------
同步到我的简书
https://www.jianshu.com/u/bd506afc6fc1
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 378 others
properties (23)
authorhongtao
permlinknumpy-tensorflow-axis
categorycn-stem
json_metadata{"community":"busy","app":"busy/2.5.6","format":"markdown","tags":["cn-stem","numpy","tensorflow","matrix","busy"],"users":[],"links":["https://images.unsplash.com/photo-1488229297570-58520851e868?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1649&q=80","https://www.jianshu.com/u/bd506afc6fc1"],"image":["https://ipfs.busy.org/ipfs/QmenrrLAVzm6bFTjeKfrsoNbk9ZHTEjKQscoregsMERcFU"]}
created2019-06-12 15:31:42
last_update2019-06-13 08:57:57
depth0
children2
last_payout2019-06-19 15:31:42
cashout_time1969-12-31 23:59:59
total_payout_value2.004 HBD
curator_payout_value0.610 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length2,507
author_reputation3,241,267,862,629
root_title深入理解Numpy和Tensorflow中的Axis操作
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id86,506,193
net_rshares4,453,844,218,501
author_curate_reward""
vote details (442)
@cnbuddy ·
你那里天气如何?想要玩STEEM的第一款卡牌对战游戏吗?快来[steemmonsters.com](https://steemmonsters.com?ref=davidchen)如果不想再收到我的留言,请回复“取消”。
properties (22)
authorcnbuddy
permlinkre-hongtao-numpy-tensorflow-axis-20190612t155634212z
categorycn-stem
json_metadata""
created2019-06-12 15:56:33
last_update2019-06-12 15:56:33
depth1
children0
last_payout2019-06-19 15:56:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length110
author_reputation-1,449,160,991,441
root_title深入理解Numpy和Tensorflow中的Axis操作
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id86,507,373
net_rshares0
@steemstem ·
re-hongtao-numpy-tensorflow-axis-20190614t022753966z
<div class='text-justify'> <div class='pull-left'> <center> <br /> <img width='200' src='https://res.cloudinary.com/drrz8xekm/image/upload/v1553698283/weenlqbrqvvczjy6dayw.jpg'> </center>  <br/> </div> 

This post has been voted on by the **SteemSTEM** curation team and voting trail. It is elligible for support from <b><a href='https://www.steemstem.io/#!/@curie'>@curie</a></b>.<br /> 

If you appreciate the work we are doing, then consider supporting our witness [**stem.witness**](https://steemconnect.com/sign/account_witness_vote?approve=1&witness=stem.witness). Additional witness support to the [**curie witness**](https://steemconnect.com/sign/account_witness_vote?approve=1&witness=curie) would be appreciated as well.<br /> 

For additional information please join us on the [**SteemSTEM discord**]( https://discord.gg/BPARaqn) and to get to know the rest of the community!<br />

Please consider setting <b><a href='https://www.steemstem.io/#!/@steemstem'>@steemstem</a></b> as a beneficiary to your post to get a stronger support.<br />

Please consider using the <b><a href='https://www.steemstem.io'>steemstem.io</a></b> app to get a stronger support.</div>
properties (22)
authorsteemstem
permlinkre-hongtao-numpy-tensorflow-axis-20190614t022753966z
categorycn-stem
json_metadata{"app":"bloguable-bot"}
created2019-06-14 02:27:57
last_update2019-06-14 02:27:57
depth1
children0
last_payout2019-06-21 02:27:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,174
author_reputation262,017,435,115,313
root_title深入理解Numpy和Tensorflow中的Axis操作
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id86,592,493
net_rshares0