我需要用有限的训练数据评估我的模型的性能。我随机选择 p 个原始训练数据。在这种情况下假设 p 为 0.2。这是一些 intil 代码行:
p = p*100
data_samples = (data.shape[0] * p)/100 # data.shape= (100, 50, 50, 3)
# for randomly selecting data
import random
random.seed(1234)
filter_indices=[random.randrange(0, data.shape[0]) for _ in range(data_samples)]
它给我的总过滤器索引随机地介于 0 和总数据大小之间。
现在,我想从等同于 filter_indices 但包括所有维度的“数据”中获取那些索引样本。我怎样才能有效且高效地做到这一点?
您可以使用 numpy 的整数数组索引 将生成的索引列表直接用作索引。单独使用时,尾部尺寸会自动添加到结果中!较小的例子:
import numpy as np
# Your data goes here
data = np.arange(90).reshape(10, 3, 3)
N = data.shape[0]
p = 0.2
# Generating random indices
n_samples = int(N * p)
np.random.seed(0)
filter_indices = np.random.choice(N, size=n_samples)
# Indexing magic:
out = data[filter_indices]
np.random.choice
稍微简化您的代码。
结果:
>>> filter_indices
array([5, 0])
>>> out
array([[[45, 46, 47],
[48, 49, 50],
[51, 52, 53]],
[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]]])
>>> out.shape
(2, 3, 3)
out
恰好是 (3, 3)
中索引 5 和 0 处的 2 个形状 data
子数组。因此结果具有形状 (2, 3, 3)
而不是 (10, 3, 3)
.