python - 类型错误 : only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

标签 python python-3.x numpy

我想编写一个函数,根据提供的 bin 概率 从训练集中随机挑选元素。我将集合索引分成 11 个 bin,然后为它们创建自定义概率

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

我觉得这很奇怪,因为我已经检查了我创建的索引数组。它是一维,是整数,并且是标量

我错过了什么?

注意:我试图通过 astype(int) 传递 indices。同样的错误。

最佳答案

也许错误消息有些误导,但要点是 X_train 是一个列表,而不是一个 numpy 数组。您不能对其使用数组索引。先做一个数组:

out_images = np.array(X_train)[indices.astype(int)]

关于python - 类型错误 : only integer scalar arrays can be converted to a scalar index with 1D numpy indices array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50997928/

相关文章:

python - Pandas:合并重复的索引值

python - 如何从 Python Set 或 Dict 向 Sqlite 数据库插入值?

python - 用 python 展平 numpy 数组

python-3.x - 如何使该 Sprite 可点击,然后关闭它以便渲染新 map ?

python-3.x - 获取 'str' 对象没有属性 '_max_attempts' python 中的云 firestore 事务错误

用于匹配 3 个和 16 个字符的 Python 正则表达式

python - 编写类似于 sys.getrecursionlimit 的递归函数

python - 将 bz2 压缩二进制文件导入为 numpy 数组

python - Pygame 运行游戏的速度非常慢

python - 将点列表转换为 numpy 二维数组