[英]Is there a way to wrap every single entry of an numpy.ndarray into a separate array?
I'm facing some problems getting an array into the right shape to use it as an input into a convolutional neural net:我在将数组设置为正确的形状以将其用作卷积神经网络的输入时遇到了一些问题:
My array has the shape (100,64,64)
, but I'd need it to be (100,64,64,1)
.我的数组具有形状
(100,64,64)
,但我需要它是(100,64,64,1)
。 I realize it looks a bit odd, but I basically want to pack every single entry into a separate array.我意识到它看起来有点奇怪,但我基本上想将每个条目打包到一个单独的数组中。
A simplified example, with a 2D array, where the analogous would be from (3,3)
to (3,3,1)
:一个简化的示例,使用 2D 数组,其中类似从
(3,3)
到(3,3,1)
:
[[0,1,0], [[[0],[1],[0]],
[1,1,1], [[1],[1],[1]],
[0,0,1]] [[0],[0],[1]]]
Is there a convenient way to do this using numpy?有没有使用 numpy 的便捷方法?
I've tried to use the function numpy.reshape
: With which I know, how to "add" another array wrapping the original one.我尝试使用 function
numpy.reshape
:据我所知,如何“添加”另一个包裹原始数组的数组。
import numpy as np
data = data.reshape((1,)+data.shape)
This gives the output for data.shape
: (1,100,64,64)
.这为 data.shape 提供了
data.shape
: (1,100,64,64)
。 Is there a way to add a dimension at the "inner end"?有没有办法在“内端”添加尺寸?
If I try data.reshape(data.shape+(,1))
, I get an invalid syntax error.如果我尝试
data.reshape(data.shape+(,1))
,我会收到无效的语法错误。
You can reshape using:您可以使用以下方式重塑:
a[:,:,None]
Or, programmatically (works for any number of dimensions):或者,以编程方式(适用于任意数量的维度):
a.reshape((*a.shape,1))
example例子
a = np.array([[0,1,0],
[1,1,1],
[0,0,1]])
# array([[0, 1, 0],
# [1, 1, 1],
# [0, 0, 1]])
a[:,:,None] # or a.reshape((*a.shape,1))
# array([[[0], [1], [0]],
# [[1], [1], [1]],
# [[0], [0], [1]]])
You can pass an Ellipsis plus None
to the arrays indexer:您可以将省略号加
None
传递给 arrays 索引器:
>>> a
array([[0, 1, 0],
[1, 1, 1],
[0, 0, 1]])
>>> a[..., None]
array([[[0],
[1],
[0]],
[[1],
[1],
[1]],
[[0],
[0],
[1]]])
(Credit to @hpaulj ) ( 归功于@hpaulj )
As the docs points out , when the shapes are compatible as yours are, you can directly change the shape of the array too:正如文档指出的那样,当形状与您的形状兼容时,您也可以直接更改数组的形状:
a = np.array([
[0, 1, 0],
[1, 1, 1],
[0, 0, 1]
])
a.shape += (1,)
a
# array([[[0], [1], [0]],
# [[1], [1], [1]],
# [[0], [0], [1]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.