TypeError:只有整数标量数组可以使用一维numpy indexs数组转换为标量索引 [英] TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array
问题描述
我想编写一个函数,根据提供的 bin概率从训练集中随机选择元素.我将设置的索引划分为11个容器,然后为其创建自定义概率.
I want to write a function that randomly picks elements from a training set, based on the bin probabilities provided. I divide the set indices to 11 bins, then create custom probabilities for them.
bin_probs = [0.5, 0.3, 0.15, 0.04, 0.0025, 0.0025, 0.001, 0.001, 0.001, 0.001, 0.001]
X_train = list(range(2000000))
train_probs = bin_probs * int(len(X_train) / len(bin_probs)) # extend probabilities across bin elements
train_probs.extend([0.001]*(len(X_train) - len(train_probs))) # a small fix to match number of elements
train_probs = train_probs/np.sum(train_probs) # normalize
indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)
out_images = X_train[indices.astype(int)] # this is where I get the error
我收到以下错误:
TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array
我发现这很奇怪,因为我已经检查了我创建的索引数组.它是 1-D ,它是整数,并且是标量.
I find this weird, since I already checked the array of indices that I have created. It is 1-D, it is integer, and it is scalar.
我想念什么?
注意:我试图通过astype(int)
传递indices
.同样的错误.
Note : I tried to pass indices
with astype(int)
. Same error.
推荐答案
也许错误消息有些令人误解,但要点是X_train
是一个列表,而不是一个numpy数组.您不能在其上使用数组索引.首先将其设置为数组:
Perhaps the error message is somewhat misleading, but the gist is that X_train
is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:
out_images = np.array(X_train)[indices.astype(int)]
这篇关于TypeError:只有整数标量数组可以使用一维numpy indexs数组转换为标量索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!