2

私は scipy.sparse 行列 (CSC) と numpy ndarray ベクトルの間の内積を計算しています:

>>> print type(np_vector), np_vector.shape
<type 'numpy.ndarray'> (200,)
>>> print type(sp_matrix), sparse.isspmatrix(sp_matrix), sp_matrix.shape
<class 'scipy.sparse.csc.csc_matrix'> True (200, 200)
>>> dot_vector = dot(np_vector, sp_matrix)

私が期待していたように、結果は新しい ndarray ベクトルのようです:

>>> print type(dot_vector), dot_vector.shape
<type 'numpy.ndarray'> (200,)

しかし、そのベクターにスカラーを追加しようとすると、例外が発生します。

>>> scalar = 3.0
>>> print dot_vector + scalar 
C:\Python27\lib\site-packages\scipy\sparse\compressed.pyc in __add__(self, other)
    173                 return self.copy()
    174             else: # Now we would add this scalar to every element.
--> 175                 raise NotImplementedError('adding a nonzero scalar to a '
    176                                           'sparse matrix is not supported')
    177         elif isspmatrix(other):

NotImplementedError: adding a nonzero scalar to a sparse matrix is not supported

結果dot_vectorが再び疎行列であるかのように。

具体的には、ndarray があるように見えますが、疎行列が演算子__add__に対して呼び出され+ます。

これは、私が呼び出されると予想されるメソッドです。

>>> print dot_vector.__add__
<method-wrapper '__add__' of numpy.ndarray object at 0x05250690>

ここで何かが足りないのでしょうか、それとも本当に奇妙に見えますか? オペレーター
に対してどのメソッドが呼び出されるかを決定するものは何ですか? このコードを IPython Notebook ( ) で実行しています。IPython --pylab またはノートブック カーネルが何らかの形で問題を引き起こしている可能性はありますか?+
ipython notebook --pylab inline

助けてくれてありがとう!

4

1 に答える 1

7

への呼び出しnp.dotが行っていることは、次のことを行った場合に得られるものとそれほど違いはありません。

>>> np.dot([1, 2, 3], 4)
array([ 4,  8, 12])

は疎行列について知らないためnp.dot、この場合の戻り値は、ベクトルの各要素と元の疎行列の積です。これはおそらく__rmul__疎行列のメソッドを呼び出して実行されるため、得られるのは 200 項目の配列で、それぞれが疎行列そのものです。そのベクトルにスカラーを追加しようとするとブロードキャストされ、各行列にスカラーを追加しようとするとエラーが発生します。

これを行う正しい.dot方法は、疎行列のメソッドを呼び出すことです。行ベクトルを事前に乗算するには、次のようにします。

>>> aa = sps.csc_matrix(np.arange(9).reshape(3, 3))
>>> bb = np.arange(3)
>>> aa.T.dot(bb)
array([15, 18, 21])

また、列ベクトルを事後乗算するには:

>>> aa.dot(bb)
array([ 5, 14, 23])

もちろん、これは配列を操作する場合と完全に同等です。

>>> aaa = np.arange(9).reshape(3,3)
>>> aaa.dot(bb)
array([ 5, 14, 23])
>>> bb.dot(aaa)
array([15, 18, 21])
于 2013-04-19T19:43:57.043 に答える