错误:使用序列设置数组元素.巨蟒/Numpy [英] Error: Setting an array element with a sequence. Python / Numpy
问题描述
尝试将一个数组分配给另一个特定于数组的位置时,我收到此错误. 在创建简单列表和进行此类分配之前,我一直在这样做.但是Numpy比简单列表要快,我现在正尝试使用它.
I'm receiving this error when trying to assign an array to another array specific position. I was doing this before creating simple lists and doing such assignment. But Numpy is faster than simple lists and I was trying to use it now.
问题是因为我有一个存储一些数据的2D数组,并且在我的代码中,例如,我要计算每个位置值的梯度,所以我创建了另一个2D数组,其中每个位置为其存储梯度值.
The problem is cause I have a 2D array that stores some data and, in my code, I have, e.g., to calculate the gradient for each position value, so I create another 2D array where each position stores the gradient for its value.
import numpy as np
cols = 2
rows = 3
# This works
matrix_a = []
for i in range(rows):
matrix_a.append([0.0] * cols)
print matrix_a
matrix_a[0][0] = np.matrix([[0], [0]])
print matrix_a
# This doesn't work
matrix_b = np.zeros((rows, cols))
print matrix_b
matrix_b[0, 0] = np.matrix([[0], [0]])
发生的事情是因为我有一个定义 np.zeros((rows,cols))对象的类,该对象存储有关某些数据的信息,从而简化了例如图像数据.
What happens is 'cause I have a class defining a np.zeros((rows, cols)) object, that stores information about some data, simplifying, e.g., images data.
class Data2D(object):
def __init__(self, rows=200, cols=300):
self.cols = cols
self.rows = rows
# The 2D data structure
self.data = np.zeros((rows, cols))
在一种特定的方法中,我必须为此数据计算梯度,该梯度是2 x 2的矩阵(因此,我想使用 ndarray 而不是简单的数组),为此,我创建了该对象的另一个实例来存储此新数据,其中每个点(像素)都应存储其梯度.我当时使用的是简单列表,但可以,但是尽管我可以通过numpy获得一些性能.
In a specific method, I have to calculate the gradient for this data, which is a 2 x 2 matrix (cause of this I would like to use ndarray, and not a simple array), and, to do this, I create another instance of this object to store this new data, in which each point (pixel) should store its gradient. I was using simple lists, which works, but I though I could gain some performance with numpy.
有办法解决这个问题吗?还是做这种事情的更好方法? 我知道我可以将数组类型定义为 object ,但是我不知道这样做是否会降低性能.
There is a way to work around this? Or a better way to do such thing? I know that I can define the array type to object, but I don't know if I lose performance doing such thing.
谢谢.
推荐答案
麻烦的是,matrix_b默认为float dtype.在我的机器上,检查
The trouble is that matrix_b is defaulting to a float dtype. On my machine, checking
matrix_b.dtype
返回dtype('float64')
.要创建一个可以容纳任何内容的numpy数组,您可以手动将dtype设置为object,这将允许您在其中放置一个矩阵:
returns dtype('float64')
. To create a numpy array that can hold anything, you can manually set dtype to object, which will allow you to place a matrix inside of it:
matrix_b = np.zeros((rows, cols), dtype=object)
matrix_b[0, 0] = np.matrix([[0], [0], [1]])
这篇关于错误:使用序列设置数组元素.巨蟒/Numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!