[英]slicing 2d numpy array
I have a numpy array padded_train_x
of shape (2500,500)
. 我有一个numpy数组
padded_train_x
的形状(2500,500)
。
The problem is, when I try to get the shape of an element of this array like padded_train_x[0].shape
it outputs (500,)
but when I run it as padded_train_x[0:1]
it outputs (1,500)
. 问题是,当我尝试获取像
padded_train_x[0].shape
这样的数组元素的形状时,它输出(500,)
但是当我以padded_train_x[0:1]
运行它时,它输出(1,500)
。 Why does this happen? 为什么会这样?
I'm trying to make prediction in an LSTM model using keras but I have to use padded_train_x[0:1]
as the input instead of simply padded_train_x[0]
我正在尝试使用keras在LSTM模型中进行预测,但我必须使用
padded_train_x[0:1]
作为输入而不是简单的padded_train_x[0]
That is because making slice by padded_train_x[0:1]
you get 2d array: 那是因为通过
padded_train_x[0:1]
制作切片得到2d数组:
a = np.linspace(1024).reshape(64,-1)
b = a[0]
c = a[0:1]
b
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
b[0]
0
c
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]])
c[0]
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
As to why it happens, let's wait for someone more expert, not sure there really is a reason. 至于它为什么会发生,让我们等一个更专家的人,不确定是否真的有原因。
NumPy keeps dimensions when slicing and drops them when indexing. NumPy在切片时保留尺寸,并在索引时将其丢弃。 It's actually a Python thing, the same happens with lists.
它实际上是一个Python的东西,列表也是如此。
You can drop single-dimensional axes with np.squeeze
您可以使用
np.squeeze
删除单维轴
a = np.ones((2500, 500))
a[0].shape
(500,)
a[0:1].shape
(1, 500)
a[0:1].squeeze().shape
(500,)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.