简体   繁体   English

numpy:安排输入和输出向量的正确方法

[英]Numpy: proper way to arrange input and output vectors

I am trying to create a numpy array with 2 columns and multiple rows. 我正在尝试创建一个具有2列和多行的numpy数组。 The first column is meant to represent input vector of size 3. The 2nd column is meant to represent output vector of size 2. 第一列用于表示大小为3的输入向量。第二列用于表示大小为2的输出向量。

arr = np.array([
    [np.array([1,2,3]), np.array([1,0])]
    [np.array([4,5,6]), np.array([0,1])]
])

I was expecting: arr[:, 0].shape to return (2, 3), but it returns (2, ) 我期望: arr[:, 0].shape返回(2,3),但它返回(2,)

What is the proper way to arrange input and output vectors into a matrix using numpy? 使用numpy将输入和输出向量排列成矩阵的正确方法是什么?

If you are sure the elements in each column have the same size/length, you can select and then stack the result using numpy.row_stack : 如果确定每列中的元素都具有相同的大小/长度,则可以选择然后使用numpy.row_stack堆叠结果:

np.row_stack(arr[:,0]).shape
# (2, 3)

np.row_stack(arr[:,1]).shape
# (2, 2)

So, the code 所以,代码

arr = np.array([
[np.array([1,2,3]), np.array([1,0])],
[np.array([4,5,6]), np.array([0,1])]
])

Creates an object array, indexing the first column gives you back two rows with one object in each, which accounts for the size. 创建一个对象数组,索引第一列将为您提供两行,每行中有一个对象,这占了大小。 To get what you want you'd need to wrap it in something like 为了得到您想要的东西,您需要将其包装在类似

np.vstack(arr[:, 0])

Which creates an array out of the objects in the first column. 从第一列的对象中创建一个数组。 This isn't very convenient, it would make more sense to me to store these in a dictionary, something like 这不是很方便,将它们存储在字典中对我来说更有意义,例如

io = {'in': np.array([[1,2,3],[4,5,6]]),
'out':np.array([[1,0], [0,1]])
}

A structured array gives you a bit of both. 结构化数组为您提供了这两者。 Creation is a bit tricky, for the example given, 对于给出的示例,创建有点棘手,

arr = np.array([
    (1,2,3), (1,0)),
    ((4,5,6), (0,1)) ],
    dtype=[('in', '3int64'), ('out', '2float64')])

Creates a structured array with fields in and out , consisting of 3 integers and 2 floats respectively. 创建一个结构化数组,其字段为inout ,分别由3个整数和2个浮点数组成。 Rows can be accessed as usual, 可以照常访问行,

In[73]: arr[0]
Out[74]: ([1, 2, 3], [ 1.,  0.])

Or by the field name 或按字段名称

In [73]: arr['in']
Out[73]: 
array([[1, 2, 3],
   [4, 5, 6]])

The numpy manual has many more details ( https://docs.scipy.org/doc/numpy-1.13.0/user/basics.rec.html ). numpy手册具有更多详细信息( https://docs.scipy.org/doc/numpy-1.13.0/user/basics.rec.html )。 I can't add any details as I've been intending to use them in a project for some time, but haven't. 我无法添加任何细节,因为我打算在项目中使用它们已有一段时间了,但是没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM