将 numpy 数组添加到 scipy.sparse.dok_matrix
我有一个 scipy.sparse.dok_matrix (尺寸 mxn),想要添加一个长度为 m 的平面 numpy 数组。
for col in xrange(n):
dense_array = ...
dok_matrix[:,col] = dense_array
但是,当此代码尝试删除不存在的键 (del self[(i,j)]
) 时,它会在 dok_matrix.__setitem__
中引发异常。
所以,现在我正在以不优雅的方式这样做:
for col in xrange(n):
dense_array = ...
for row in dense_array.nonzero():
dok_matrix[row, col] = dense_array[row]
这感觉非常低效。 那么,最有效的方法是什么?
谢谢!
I have a scipy.sparse.dok_matrix
(dimensions m x n), wanting to add a flat numpy-array with length m.
for col in xrange(n):
dense_array = ...
dok_matrix[:,col] = dense_array
However, this code raises an Exception in dok_matrix.__setitem__
when it tries to delete a non existing key (del self[(i,j)]
).
So, for now I am doing this the unelegant way:
for col in xrange(n):
dense_array = ...
for row in dense_array.nonzero():
dok_matrix[row, col] = dense_array[row]
This feels very ineffecient.
So, what is the most efficient way of doing this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这个错误已在 Scipy 0.8.0 中修复
I think that this bug has been fixed in Scipy 0.8.0
我很惊讶你的不优雅的方式没有与切片方式相同的问题。在查看 Scipy 代码后,这对我来说似乎是一个错误。当您尝试将 dok_matrix 中的某个行和列设置为零(当它已经为零时)时,会出现错误,因为它尝试删除该行和列的值而不检查它是否存在。
在回答您的问题时,您以不优雅的方式所做的正是
__setitem__
方法当前使用优雅方法所做的事情(经过几次 isinstance 检查以及其他检查之后)。如果你想使用优雅的方式,你可以通过打开 Lib/site-packages/scipy/sparse/ 中的 dok.py 并将第 222 行更改为然后
你可以使用优雅的方式,它应该工作得很好。我去提交了一个错误修复,但这已经在下一个版本中修复了,这就是修复的方式。
I'm surprised that your unelegant way doesn't have the same problems as the slice way. This looks like a bug to me upon looking at the Scipy code. When you try to set a certain row and column in a dok_matrix to zero when it is already zero, there is be an error because it tries to delete the value at that row and column without checking if it exists.
In answer to your question, what you are doing in your inelegant way is exactly what the
__setitem__
method does currently with your elegant method (after a couple of isinstance checks and what not). If you want to use the elegant way, you can fix the bug I mentioned in your own Scipy package by opening up dok.py inLib/site-packages/scipy/sparse/
and changing line 222 fromto
Then you can use the elegant way and it should work just fine. I went to submit a bug fix, but this it is already fixed for the next version and this is the way that it was fixed.