填写非对角线numpy的阵列出现故障 [英] fill off diagonal of numpy array fails

查看:374
本文介绍了填写非对角线numpy的阵列出现故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想填充偏移矩阵对角线:

  loss_matrix = np.zeros((125,125))np.diagonal(loss_matrix,3).fill伪(4)ValueError错误:分配的目标是只读的

两个问题:

1)在不遍历索引,我怎么可以设置numpy的数组的偏移对角线?

2)为什么 np.diagonal 的结果只读?对于numpy.diagonal的文件写道:在numpy的1.10,它会返回一个读/写视图,并书面向返回数​​组将改变你原来的阵列

  NP .__ version__1.10.1


解决方案

讨论来看在numpy的问题跟踪,它看起来像功能是停留在地狱,他们从来没有得到周围固定的文件说,它推迟了。

如果您需要可写,你可以强制它。这只会在numpy的1.9和后续工作,因为 np.diagonal 使得在较低版本的副本:

 诊断= np.diagonal(loss_matrix,3)#这不是写。使其可写。
diag.setflags(写= TRUE)diag.fill(4)

I'm trying to the fill the offset diagonals of a matrix:

loss_matrix = np.zeros((125,125))

np.diagonal(loss_matrix, 3).fill(4)

ValueError: assignment destination is read-only

Two questions:

1) Without iterating over indexes, how can I set the offset diagonals of a numpy array?

2) Why is the result of np.diagonal read only? The documentation for numpy.diagonal reads: "In NumPy 1.10, it will return a read/write view and writing to the returned array will alter your original array."

np.__version__

'1.10.1'

解决方案

Judging by the discussion on the NumPy issue tracker, it looks like the feature is stuck in limbo and they never got around to fixing the documentation to say it was delayed.

If you need writability, you can force it. This will only work on NumPy 1.9 and up, since np.diagonal makes a copy on lower versions:

diag = np.diagonal(loss_matrix, 3)

# It's not writable. MAKE it writable.
diag.setflags(write=True)

diag.fill(4)

这篇关于填写非对角线numpy的阵列出现故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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