复制numpy的阵列的值成为稀疏矩阵的特定位置 [英] Copying values of a numpy array into specific location of sparse matrix

查看:387
本文介绍了复制numpy的阵列的值成为稀疏矩阵的特定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我试图从一个numpy的数组的值复制到一个稀疏矩阵。第一个数组是这样的:

So I am trying to copy values from one numpy array into a sparse matrix. The first array looks like this:

results_array = [[  3.00000000e+00   1.00000000e+00   4.00000000e+00   1.00000000e+03]
[  6.00000000e+00   2.00000000e+00   5.00000000e+00   7.00000000e+02]
[  1.60000000e+01   4.00000000e+00   8.00000000e+00   1.00000000e+03]}

第二个值(或 results_array [I] [1] )决定了列ID,第三个值( results_array [I] [2 ] )规定的行ID和第四值( results_array [I] [3] )决定了行,列对的值。

The second value (or results_array[i][1]) dictates the column id, the third value (results_array[i][2]) dictates the row id and the fourth value (results_array[i][3]) dictates the value of that row, column pair.

到目前为止,我有什么是这样的:

So far what I have is this:

for i in result_array:
sparse_matrix = csc_matrix((i[3],(i[1],i[2])), shape=(14,14))
print "last array", sparse_matrix

我得到的输出是:

The output I get is:

File "C:/Users/Andrew/Google Drive/Uni/Final Year/Research Project/Programming/Mine/First UEA/xl_optim/Runestone 2.py", line 13, in <module>
sparse_matrix = csc_matrix((i[3],(i[1],i[2])), shape=(14,14))
File "C:\Users\Andrew\Anaconda2\lib\site-packages\scipy\sparse\compressed.py", line 48, in __init__
other = self.__class__(coo_matrix(arg1, shape=shape))
File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 182, in __init__
self._check()
File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 219, in _check
nnz = self.nnz
File "C:\Users\###\Anaconda2\lib\site-packages\scipy\sparse\coo.py", line 194, in getnnz
nnz = len(self.data)
TypeError: len() of unsized object

我想我需要首先创建稀疏矩阵,然后值反复添加到它(我想象的有点像 .append ,但到特定位置矩阵),但我不知道如何创建一个空的稀疏矩阵,然后分配值了。

I think I need to create the sparse matrix first and then add the values to it iteratively (I'm imagining something like a .append but to a specific location in the matrix) but I have no idea how to create an empty sparse matrix and then assign values to it.

让我知道如果你需要进一步澄清。谢谢!

Let me know if you need further clarification. Thanks!

推荐答案

在您传递给元组的第一个元素 csc_matrix 需要有价值观的载体,而你正在传递一个整数。更为重要的是,你要叫 csc_matrix 构造函数中多次循环,这样它会覆盖 sparse_matrix 上每次迭代。

The first element in the tuple you pass to csc_matrix needs to be a vector of values, whereas you are passing it an integer. More fundamentally, you're trying to call the csc_matrix constructor multiple times in a loop so that it would overwrite sparse_matrix on each iteration.

您想调用 csc_matrix 一次的与每个参数矢量,是这样的:

You want to call csc_matrix once with a vector for each parameter, like this:

values = results_array[:, 3]
row_idx = results_array[:, 2]
col_idx = results_array[:, 1]

sparse_array = csc_matrix((values, (row_idx, col_idx)), shape=(14, 14))

这篇关于复制numpy的阵列的值成为稀疏矩阵的特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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