Python中多维矩阵的多维索引

问题描述

我想使用多维索引矩阵来访问另一个多维矩阵。 我的问题是,由于广播问题(形状不匹配),诸如np.newaxis之类的方法无法正常工作。

我的数据矩阵的形状为(5001、3、240、16)。

import numpy as np

# n_examples,n_channels,n_pictures,n_Meta_information
data = np.ones((5001,3,240,16))

# select randomly 32 examples
batch_size = 32
possible_indices = np.arange(5001,dtype=np.int)
random_example_indices = np.random.choice(possible_indices,size=batch_size,replace=True)


# select all three channels
n_channels = 3
channel_indices = np.arange(n_channels)
#channel_indices = np.expand_dims(channel_indices,axis=0)
#channel_indices = np.repeat(channel_indices,batch_size,axis=0)

final_pictures_indices = []
for random_sample_idx in range(batch_size):
    # select a random start index and take 120 successive indices
    # is the same for all three channels
    start_index = np.random.randint(0,max(1,240 - 120 + 1))
    end_index = start_index + 120
    pictures_indices = np.arange(start_index,end_index,dtype=np.int)
    final_pictures_indices.append(pictures_indices)

# batch_size x n_pictures
final_pictures_indices = np.array(final_pictures_indices)


# should have the shape: (32,120,16)
result = data[random_example_indices[:,np.newaxis],channel_indices,final_pictures_indices].shape
print(result)

不幸的是,我遇到了以下错误

result = data[random_example_indices[:,final_pictures_indices].shape
IndexError: shape mismatch: indexing arrays Could not be broadcast together with shapes (32,1) (3,) (32,120)

我还尝试将所有索引信息融合到一个矩阵中,但是我遇到的问题是无法堆叠具有不同形状的矩阵。

感谢您的每一个提示

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)