Python的Numpy库中的 nonzero函数,及应用在 hardlim硬限幅函数中

Python的Numpy库中的 nonzero函数,及应用在 hardlim硬限幅函数中


在学习 邓捷的《机器学习  算法原理与编程实践》 中 p168页的 激活函数 hardlim的时候, 看不懂。

查询相关的知识点,学习了下。


先看 python代码

#! /usr/bin/python

from   numpy import *


'''
    print a
[[-4 -3 -2]
 [-1  0  1]
 [ 2  3  4]]
    print dataset.A
[[-4 -3 -2]
 [-1  0  1]
 [ 2  3  4]]
    print  dataset.A > 0
[[False False False]
 [False False  True]
 [ True  True  True]]
    print  nonzero(  dataset.A > 0 )
(array([1, 2, 2, 2]), array([2, 0, 1, 2]))
    print hardlim( a )
[[0 0 0]
 [1 1 1]
 [1 1 1]]
'''
def hardlim(dataset):
    dataset[ nonzero( dataset.A > 0 )[0] ] = 1
    dataset[ nonzero( dataset.A <=0 )[0] ] = 0
    return dataset


if __name__ == "__main__":
    a = arange(9) - 4
    #print a
    #[-4 -3 -2 -1  0  1  2  3  4]

    a = a.reshape(3, 3)
    #print a
    #[[-4 -3 -2]
    # [-1  0  1]
    # [ 2  3  4]]

    a = mat(a)
    #print a
    #[[-4 -3 -2]
    # [-1  0  1]
    # [ 2  3  4]]

    print a
    print hardlim( a )


numpyPython用来科学计算的一个非常重要的库,numpy主要用来处理一些矩阵对象


numpy.nonzero()函数,简记如下:


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


内容如下:

numpy.nonzero

numpy. nonzero ( a )
Returnthe indices of the elements that are non-zero.
Returnsa tuple of arrays, one for each dimension of  a ,containing the indices of the non-zero elements in thatdimension. The values in  a arealways tested and returned in row-major, C-style order. Thecorresponding non-zero values can be obtained with:
a[nonzero(a)]
Togroup the indices by element, rather than dimension, use:
transpose(nonzero(a))
Theresult of this is always a 2-D array, with a row for eachnon-zero element.
Parameters:

a :array_like

Inputarray.
Returns:

tuple_of_arrays :tuple

Indicesof elements that are non-zero.

Seealso

flatnonzero
Returnindices that are non-zero in the flattened version of theinput array.
ndarray.nonzero
Equivalentndarray method.
count_nonzero
Countsthe number of non-zero elements in the input array.



举些使用的例子

>>> b1 = np.array([True, False, True, False])
>>> np.nonzero(b1)
    (array([0, 2]),)

可以看到,对于一维的array,输出的是非零值的“下标”。


>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
array([[False, False, False],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
>>> np.transpose(  np.nonzero(a > 3)  )

array([[1, 0],
 这就是非零元素的坐标
       [1, 1],

       [1, 2],

       [2, 0],

       [2, 1],

       [2, 2]])




还可以参考:http://www.cnblogs.com/itdyb/p/5766707.htmlhttp://www.th7.cn/Program/Python/201501/351495.shtml

你可能感兴趣的:(python,机器学习入门,Caffe学习,python,nonzero,numpy,hardlim,硬限幅函数)