Numpy.nonzero() 详解 numpy module中 nonzero()函数

最近看到《机器学习实战》第6章PlattSMO算法时, 遇到了numpy.nonzero()函数, 纠结了很久才看懂用法。

简记之,共以后自己和他人参考。




首先,官方文档链接如下:http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html

numpy. nonzero ( a ) [source]

Return the indices of the elements that are non-zero.

Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with:

a[nonzero(a)]

To group the indices by element, rather than dimension, use:

transpose(nonzero(a))

The result of this is always a 2-D array, with a row for each non-zero element.

Parameters:

a : array_like

Input array.

Returns:

tuple_of_arrays : tuple

Indices of elements that are non-zero.



简单翻译:

numpy函数返回非零元素的目录。

返回值为元组, 两个值分别为两个维度, 包含了相应维度上非零元素的目录值。   可以通过a[nonzero(a)]来获得所有非零值。



个人解释,  nonzero(a)  将对矩阵a的所有非零元素, 分别安装两个维度, 一次返回其在各维度上的目录值。

如果 a=mat([ [1,0,0],                          

             [0,0,0],

             [0,0,0]])                      

 则 nonzero(a) 返回值为 (array([0]), array([0]))   , 因为矩阵a只有一个非零值, 在第0行, 第0列。


如果 a=mat([ [1,0,0],                          

             [1,0,0],

             [0,0,0]])                      

 则 nonzero(a) 返回值为 (array([0, 1]), array([0, 0]))   , 因为矩阵a只有两个非零值, 在第0行、第0列,和第1行、第0列。所以结果元组中,第一个行维度数据为(0,1) 元组第二个列维度都为(0,0)。

        



  • 16
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值