稀疏矩阵和numpy数组之间的点积给出ValueError [英] Dot product between scipy sparse matrix and numpy array give ValueError

查看:125
本文介绍了稀疏矩阵和numpy数组之间的点积给出ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算scipy解析矩阵和numpy数组之间的点积.

首先,我使用了一个numpy矩阵,您可以在以下代码中看到它:

def power_iteration(matrix, n):
    b_k = np.random.rand(matrix.shape[1])
    for _ in range(n):
        b_k = np.dot(matrix, b_k)

    return b_k 

这里的矩阵是一个numpy矩阵,没有错误发生.

如果将稀疏稀疏矩阵作为参数传递,则会发生以下错误:ValueError:形状(6762,6762)和(1,6762)不对齐:6762(dim 1)!= 1(dim 0)

我已经改变

b_k = np.random.rand(matrix.shape[1])

进入

b_k = np.random.rand(matrix.shape[1], 1)

使点积起作用,但不返回正确的b_k形状.我需要的形状是:(6762,)

到目前为止,我已经尝试过像这样重塑:

b_k = np.reshape(b_k, (matrix.shape[1],))

但是这会将形状(6762,1)转换为(1,6762),而不是(6762,)

有什么秘诀吗?谢谢!

解决方案

似乎要在稀疏矩阵上使用np.dot,您需要先使用matrix.toarray()将其转换为密集矩阵. 另请参见 https://docs.scipy.org/doc/scipy/reference/sparse.html#matrix-vector-product

I'm trying to calculate the dot product between a scipy parse matrix and a numpy array.

First I was using a numpy matrix, which you can see in the following code:

def power_iteration(matrix, n):
    b_k = np.random.rand(matrix.shape[1])
    for _ in range(n):
        b_k = np.dot(matrix, b_k)

    return b_k 

Here the matrix is a numpy matrix and no error occurs.

If you pass a scipy sparse matrix as a parameter, the following error occurs: ValueError: shapes (6762,6762) and (1,6762) not aligned: 6762 (dim 1) != 1 (dim 0)

I have changed

b_k = np.random.rand(matrix.shape[1])

into

b_k = np.random.rand(matrix.shape[1], 1)

which makes the dot product work, but doesn't return the right b_k shape. The shape I need is: (6762,)

Edit: so far I've tried to reshape like this:

b_k = np.reshape(b_k, (matrix.shape[1],))

but this transforms the shape (6762, 1) into (1, 6762), instead of (6762,)

Any tips? Thanks!

解决方案

Seems like in order to use np.dot on sparse matrix you'd need to convert it to dense matrix first with matrix.toarray(). Also see https://docs.scipy.org/doc/scipy/reference/sparse.html#matrix-vector-product

这篇关于稀疏矩阵和numpy数组之间的点积给出ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆