简体   繁体   English

如何展平(n,)形状numpy数组

[英]how to flatten (n, ) shape numpy array

I have a variable called data, and i want to flatten it. 我有一个名为data的变量,我想将其展平。

Right now data.shape = (10, ) . 现在, data.shape = (10, ) Each element in data has a shape (5000, 64). 数据中的每个元素都有一个形状(5000,64)。 I want to make my data.shape = (10, 5000, 64) . 我想让我的data.shape = (10, 5000, 64)

How can I do that? 我怎样才能做到这一点? I've tried many below, but none of them work: 我在下面尝试了许多方法,但是它们都不起作用:

b = np.concatenate(t for t in data)
b = np.stack(t for t in data)
b = np.hstack(t for t in data)

anyone any idea about this? 任何人对此有任何想法吗?

In [50]: t = np.zeros(3,object)
In [51]: t[0]=np.ones((3,2),int)
In [52]: t[1]=np.ones((3,2),int)
In [53]: t[2]=np.ones((3,2),int)
In [54]: t
Out[54]: 
array([array([[1, 1],
       [1, 1],
       [1, 1]]),
       array([[1, 1],
       [1, 1],
       [1, 1]]),
       array([[1, 1],
       [1, 1],
       [1, 1]])], dtype=object)
In [55]: np.stack(t)
Out[55]: 
array([[[1, 1],
        [1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1],
        [1, 1]]])
In [56]: _.shape
Out[56]: (3, 3, 2)

np.stack(x for x in t) also works, but the extra layer of iteration isn't needed. np.stack(x for x in t)也可以使用,但是不需要额外的迭代层。

When you say something isn't working, you need to elaborate. 当您说某事不起作用时,您需要详细说明。 What exactly was the error? 错误到底是什么? Was it the same error for each of things you tried? 您尝试过的每件事都是一样的错误吗? Without information like that you'll get answers like mine - a test case that appears to match your description which works. 没有这样的信息,您将得到我的答案-一个似乎与您的描述匹配的测试用例。

hstack works, but joins the arrays in a different way. hstack可以工作,但是以不同的方式加入数组。

concatenate doesn't work with the (t for t in x) input, but is ok with (x) . concatenate不适(t for t in x)输入,但可以使用(x)

Assuming my guess about it being a object dtype array is right, this isn't a case of flatten . 假设我对它是一个对象dtype数组的猜测是正确的,那么这不是flatten的情况。 numpy flatten is like ravel, a shape changer. numpy flatten就像ravel一样,可以改变形状。 But this is different. 但这是不同的。 I have arrays inside an object array, effectively a list of arrays, not a multidimensional array. 我在对象数组中有数组,实际上是数组列表,而不是多维数组。

I solved this problem. 我解决了这个问题。 The problem is that my data is a numpy array of tensors, and you have to use tf.stack to do the thing. 问题是我的数据是张量的numpy数组,您必须使用tf.stack来执行此操作。

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

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