[Tutor] Problem understanding the asarray function of numpy
Peter Otten
__peter__ at web.de
Thu Sep 11 16:13:20 CEST 2014
Radhika Gaonkar wrote:
> I have an implementation of lsa, that I need to modify. I am having some
> trouble understanding the code. This is the line where I am stuck:
>
> DocsPerWord = sum(asarray(self.A > 0, 'i'), axis=1)
>
> The link for this implementation is :
> http://www.puffinwarellc.com/index.php/news-and-articles/articles/33-latent-semantic-analysis-tutorial.html?showall=1
>
> Here, A is a matrix of size vocabulary_Size X number_ofDocs
> As far as the documentation of asarray is concerned, this should return an
> array interpretation of the matrix A. But, we need to sum each row. What
> is happening here?
A numpy array can be multidimensional:
>>> import numpy
>>> a = numpy.asarray([[1,2,3],[4,5,6],[7,8,9]])
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> a.shape
(3, 3)
>>> a[0,0]
1
>>> a[2,2]
9
So this "array" works very much like a 3x3 matrix. Now let's investigate
numpy.sum() (which must not be confused with the Python's built-in sum()
function):
>>> numpy.sum(a)
45
>>> numpy.sum(a, axis=0)
array([12, 15, 18])
>>> numpy.sum(a, axis=1)
array([ 6, 15, 24])
Playing around in interactive interpreter is often helpful to learn what a
function or snippet of code does.
More information about the Tutor
mailing list