TypeError:只有整数标量数组可以转换为具有 1D 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

我觉得这很奇怪,因为我已经检查了我创建的索引数组。它是 1-D ,它是 integer ,它是 scalar

我错过了什么?

注意:我试图通过 indicesastype(int) 。同样的错误。

原文由 Bedir Yilmaz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 383
2 个回答

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

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

原文由 DYZ 发布,翻译遵循 CC BY-SA 4.0 许可协议

每当我以错误的方式使用 np.concatenate 时,我都会收到此错误:

 >>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

正确的方法是将两个数组作为元组输入:

 >>> np.concatenate((a, a))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

原文由 Simon Alford 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题