[英]Fancy indexing for numpy arrary
I want to sample len(valid_frame_id_ls)
frame from data by fancy indexing for numpy arrary.我想通过 numpy 数组的花式索引从数据中采样
len(valid_frame_id_ls)
帧。 But I received an error message when i run code1.但是当我运行 code1 时收到一条错误消息。 I don't know why the shape of
data[n, :, valid_frame_id_ls, :, :]
is not equal to the shape of new_data[n, :, :len(valid_frame_id_ls), :, :]
.Can anyone help me solve this bug.我不知道为什么
data[n, :, valid_frame_id_ls, :, :]
的形状不等于new_data[n, :, :len(valid_frame_id_ls), :, :]
的形状。谁能帮我解决这个错误。 help...帮助...
I modify my code and write in code2 block.我修改我的代码并写入 code2 块。 I did't receive any error message when i run code2.
我在运行 code2 时没有收到任何错误消息。 I don't know why code2 is correct.
我不知道为什么code2是正确的。
data = np.random.random((2, 3, 50, 25, 1))
N, C, T, V, M = data.shape
new_data = np.zeros((N, C, T, V, M))
valid_frame_id_ls = [2, 3, 4, 5, 6]
for n in range(N):
new_data[n, :, :len(valid_frame_id_ls), :, :] = data[n, :, valid_frame_id_ls, :, :]
# code1 error message:
new_data[n, :, :len(valid_frame_id_ls), :, :] = data[n, :, valid_frame_id_ls, :, :]
ValueError: could not broadcast input array from shape (5,3,25,1) into shape (3,5,25,1)
data = np.random.random((2, 3, 50, 25, 1))
N, C, T, V, M = data.shape
new_data = np.zeros((N, C, T, V, M))
valid_frame_id_ls = [2, 3, 4, 5, 11]
for n in range(N):
new_data[n][:, :len(valid_frame_id_ls), :, :] = data[n][ :, valid_frame_id_ls, :, :]
https://numpy.org/doc/stable/reference/arrays.indexing.html#combining-advanced-and-basic-indexing https://numpy.org/doc/stable/reference/arrays.indexing.html#combining-advanced-and-basic-indexing
As described in this section of the docs, putting a slice in the middle of 'advanced' indexing results in an unexpected rearrangement of dimensions.如文档的这一部分所述,将切片放在“高级”索引的中间会导致意外的维度重新排列。 Your size 5 dimension has been placed first, and the other dimensions after.
您的尺寸 5 尺寸已放在第一位,然后是其他尺寸。
This has come up occasionally on SO as well.这也偶尔出现在 SO 上。 With a scalar
n
this really shouldn't be happening, but apparently the issue occurs deep in the indexing, and isn't easily corrected.对于标量
n
这确实不应该发生,但显然问题发生在索引的深处,并且不容易纠正。
data[n][ :, valid_frame_id_ls, :, :]
breaks up the indexing, so the first ':' is no longer in the middle.打破索引,所以第一个':'不再在中间。
Another fix is to replace the slice with an equivalent array.另一个修复方法是用等效数组替换切片。 Now both sides will have the same dimensions.
现在双方将具有相同的尺寸。
new_data[n, :, np.arange(len(valid_frame_id_ls)), :, :] = data[n, :, valid_frame_id_ls, :, :]
Though in this case I don't think you need to iterate on N
at all:尽管在这种情况下,我认为您根本不需要迭代
N
:
new_data[:,:,:len(valid_frame_id_ls),:,:] = data[:,:, valid_frame_id_ls, :,:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.