前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Numpy中的stack,轴,广播以及CNN介绍

Numpy中的stack,轴,广播以及CNN介绍

原创
作者头像
无情剑客
修改2021-04-08 11:24:18
1K0
修改2021-04-08 11:24:18
举报
文章被收录于专栏:Android逆向Android逆向

神经网络学习之Ndarray对象和CNN入门 中,主要介绍了Ndarray维度的概念和CNN的大体流程图,本文基于此介绍Ndarray中比较重要的一个函数stack函数的使用以及numpy中的广播, 简单介绍下CNN。

Stack函数

官方API介绍,我是没看懂,不排除有大神看一眼就懂,如果没看懂也没关系,可以继续往下读,相信一定能理解stack究竟是怎么工作的。

代码语言:javascript
复制
numpy.stack(arrays, axis=0, out=None)[source]

Join a sequence of arrays along a new axis.

The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

笔者查阅了大量的资料,不过总感觉少了点什么,就是感觉始终不能理解诶stack是怎么堆叠的。于是就只好去看源码了,如果从一开始就看源码,或许可以节省很多时间。

源码

源码:

代码语言:javascript
复制
@array_function_dispatch(_stack_dispatcher)
def stack(arrays, axis=0, out=None):
    if not overrides.ARRAY_FUNCTION_ENABLED:
        # raise warning if necessary
        _arrays_for_stack_dispatcher(arrays, stacklevel=2)

    arrays = [asanyarray(arr) for arr in arrays]
    if not arrays:
        raise ValueError('need at least one array to stack')

    shapes = {arr.shape for arr in arrays}
    if len(shapes) != 1:
        raise ValueError('all input arrays must have the same shape')

    result_ndim = arrays[0].ndim + 1
    axis = normalize_axis_index(axis, result_ndim)

    sl = (slice(None),) * axis + (_nx.newaxis,)
    expanded_arrays = [arr[sl] for arr in arrays]
    return _nx.concatenate(expanded_arrays, axis=axis, out=out)

@的作用

@在python中是函数装饰器,和Java中的注解是不一样的。 猜猜下面下面的代码会出现什么样子的结果(注意这里funB是多参数的)

代码语言:javascript
复制
def funA(fn):
    print("funA is invoked first")
    # 定义一个嵌套函数,和JavaScript有点类似
    def innerFun(*args, **kwargs):
        fn(*args, **kwargs)
    return innerFun

@funA
def funB(name, value):
    print("迎关注我的微信公众号" + name + ",", "phpMyAdmin端口配置和mysql主从复制这篇文章" + value)

funB("无情剑客", "很棒");

使用函数装饰器 A() 去装饰另一个函数 B(),其底层执行了如下 2 步操作:

1.将 B 作为参数传给 A() 函数;2.将 A() 函数执行完成的返回值反馈回B。

以上代码等价于下面的代码:

代码语言:javascript
复制
funB = funA(funB)
funB("无情剑客", "很棒")

最终的运行结果:

funA is invoked first 迎关注我的微信公众号无情剑客, phpMyAdmin端口配置和mysql主从复制这篇文章很棒

知道了@的作用具体的过程可以自己动手debug,过程比较复杂,后续抽空补上。

关键代码解读

asanyarray

代码语言:javascript
复制
arrays = [asanyarray(arr) for arr in arrays]

举个例子:

代码语言:javascript
复制
import numpy as np

a = np.arange(24)
print(a.ndim)

b = a.reshape(2, 3, 4)
print(b)

c = np.stack(b, axis=2)
print(c.shape)
print(c)

当调用stack方法步过这段代码的时候,arrays的结果是一个list,里面的元素如下图所示:

在这里插入图片描述
在这里插入图片描述

看下面这段代码,就基本知道上面的list是怎么来的的,

代码语言:javascript
复制
arr = [1,2,5]
list_arr = [arr1 for arr1 in arr]
print(list_arr)

arrs = [asanyarray(arr1) for arr1 in arr]
print(arrs)

运行结果是:

[1, 2, 5] [array(1), array(2), array(5)]

关于asanyarray: Convert the input to an ndarray, but pass ndarray subclasses through.

维度+1

这是和concatenate函数很重要的一个区别,也体现了API中的new axis.

代码语言:javascript
复制
result_ndim = arrays[0].ndim + 1
axis = normalize_axis_index(axis, result_ndim)

expanded_arrays

如何实现维度+1的那,下面这段代码是关键:

代码语言:javascript
复制
sl = (slice(None),) * axis + (_nx.newaxis,)
expanded_arrays = [arr[sl] for arr in arrays]
在这里插入图片描述
在这里插入图片描述

可知s1的值是个tuple。 这个sl是怎么计算出来的,举个例子:

代码语言:javascript
复制
sl = (slice(None),) *2 + (None,)
sl

运行结果如下: (slice(None, None, None), slice(None, None, None), None)

代码语言:javascript
复制
e = slice(None)
e

运行结果是: slice(None, None, None)

那么arr[sl]是怎么计算出来的那?

numpy.newaxis The newaxis object can be used in all slicing operations to create an axis of length one. newaxis is an alias for ‘None’, and ‘None’ can be used in place of this with the same result

(1)slice基本语法

在这里插入图片描述
在这里插入图片描述

按照公式计算一下: i = 1, j =7, k=2 1, 3, 1+(m-1)*2 m = q+r q = (7-1)/2 = 3 r = 0 m = 3 因此最终结果是[1, 3, 5] (1)slice default处理

在这里插入图片描述
在这里插入图片描述

等价于x[5:4:1]

(3) 高维数组处理

在这里插入图片描述
在这里插入图片描述

通过下面的note可知,x[1:2]等价于x[(1:2), ],很明显,它的纬度是小于N(=2)的。因此这里面的1代表的是取索引是1的二维数组

可以将3维数组想象成行和列的组合,只不过这里的列是一个二维数组。

对于二维数组可以通过下图来看,解释一下第一个,其他的同理。

arr[:2,1:]代表取到第一行(<2),从第一列到最后一列,显然shape就是(2,2)

在这里插入图片描述
在这里插入图片描述

Note: In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the latter is just syntactic sugar for the former.

(4) 省略号

在这里插入图片描述
在这里插入图片描述

使选择元组的长度与数组的维度相同。显然选择元组的长度是2,数组的维度也是2。 (5) newaxis

在这里插入图片描述
在这里插入图片描述

以前是(2,3,1),因为The added dimension is the position of the newaxis object in the selection tuple, 所以新的数组的shape是(2,1,3,1)。翻译下就是2个三维数组,每个3维数组中有1个2维数组,每个2维数组中有3个1维数组,每个1维数组中有1也元素。

在这里插入图片描述
在这里插入图片描述

(6) slice构造函数 Remember that a slicing tuple can always be constructed as obj and used in the x[obj] notation. Slice objects can be used in the construction in place of the [start:stop:step] notation. For example, x[1:10:5,::-1] can also be implemented as obj = (slice(1,10,5), slice(None,None,-1)); x[obj] . This can be useful for constructing generic code that works on arrays of arbitrary dimension.

通过前面的分析可知arr[sl]是这样算出来的的: arr[(slice(None, None, None), slice(None, None, None), None)] 等价与:arr[: , :, np.newaxis] 以前的arr的shape是(3,4),经过这样的操作之后,就变成了(3,4,1),也就是3个2维数组,每个2维度数组中有4个1维数组,每个1维数组中有1个元素。

因此expanded_arraays最终的结果就是:

在这里插入图片描述
在这里插入图片描述

concatenate

从最内侧的轴进行拼接。

在这里插入图片描述
在这里插入图片描述

轴的概念

在这里插入图片描述
在这里插入图片描述

我在图中标注出了哪些是外边的轴,哪些是第二个轴,哪些是最里边的轴,有一个比较简单的方法来判断这些轴,就是观察一下方括号,方括号数量越多的轴,越是在外层的轴,在这个例子中,最外侧的轴有两层方括号,从外边数第二个轴有一层方括号,这里还好一点,最难理解的是最里边的轴,最后来看一下最内侧的轴。

在这里插入图片描述
在这里插入图片描述

numpy中的广播

广播(Broadcast)是 numpy 对不同形状(shape)的数组进行数值计算的方式。

在这里插入图片描述
在这里插入图片描述

下面的图片展示了数组 b 如何通过广播来与数组 a 兼容。

在这里插入图片描述
在这里插入图片描述

卷积神经网络入门

卷积神经网络主要用在图像领域。当然也可以用在文本分类,不过NLP领域,在NLP领域需要一些处理技巧。后续文章会详细介绍。

简单看看CNN网络能够做什么:

代码语言:javascript
复制
输入 -> CNN 网络 ->输出

如果做图像识别,输入就是要识别的图像,输出就是可能的图像的概率,概率越大,自然可能性越大。

在这里插入图片描述
在这里插入图片描述

CNN 网络这个黑盒要2个重要的概念: (1)卷积核,也就是特征是CNN网路uo自动生成的。通过大量的训集来不断调整特征和优化参数,提高准确度,因此数据阅读自然越准确 (2)感受野,类比人的眼睛,看的越多,自然提取的特征就越多。横看成岭侧成峰

对于分类人任务,需要标签。监督学习的类别

后续会详细介绍CNN,这里先有一个初步的印象。

参考

•Indexing[1]•numpy数组的索引和切片[2]•NumPy 广播(Broadcast)[3]•numpy数组的各种拼接方法:stack和vstack,hstack,concatenate[4]•numpy.stack 与 numpy.concatenate 用法[5]

公众号

更多机器学习内容,欢迎关注我的微信公众号: 无情剑客。

References

[1] Indexing: https://numpy.org/doc/stable/reference/arrays.indexing.html [2] numpy数组的索引和切片: https://www.cnblogs.com/mengxiaoleng/p/11616869.html [3] NumPy 广播(Broadcast): https://www.runoob.com/numpy/numpy-broadcast.html [4] numpy数组的各种拼接方法:stack和vstack,hstack,concatenate: https://zhuanlan.zhihu.com/p/82996332 [5] numpy.stack 与 numpy.concatenate 用法: https://www.pianshen.com/article/1767127443/

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Stack函数
  • 源码
  • @的作用
  • 关键代码解读
  • asanyarray
  • 维度+1
  • expanded_arrays
  • concatenate
  • 轴的概念
  • numpy中的广播
  • 卷积神经网络入门
  • 参考
  • 公众号
  • References
相关产品与服务
图像识别
腾讯云图像识别基于深度学习等人工智能技术,提供车辆,物体及场景等检测和识别服务, 已上线产品子功能包含车辆识别,商品识别,宠物识别,文件封识别等,更多功能接口敬请期待。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档