最近看到《机器学习实战》第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:
To group the indices by element, rather than dimension, use:
The result of this is always a 2-D array, with a row for each non-zero element.
Parameters: | a : array_like
|
---|---|
Returns: | tuple_of_arrays : tuple
|
简单翻译:
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)。