【问题标题】:How to resolve this TypeError: only integer scalar arrays can be converted to a scalar index如何解决此类型错误:只有整数标量数组可以转换为标量索引
【发布时间】:2021-09-25 12:38:58
【问题描述】:

我使用 np.random.choice 获取随机索引但遇到以下错误。

TypeError:只有整数标量数组可以转换为标量索引。任何建议将不胜感激。

x_train = [0,1,2,3,4]
train_size = 4
batch_size =3
batch_mask = np.random.choice(train_size, batch_size)
print(batch_mask)
x_batch = x_train[batch_mask]
print(x_batch)

【问题讨论】:

标签: python


【解决方案1】:

x_train 是一个简单的 python 列表。 您正在尝试使用 NumPy 数组作为索引;这是不合法的。 改为将 x_train 设为 numpy 数组。

x_train = np.array([0,1,2,3,4])
train_size = 4
batch_size =3
batch_mask = np.random.choice(train_size, batch_size)
print(batch_mask)
x_batch = x_train[batch_mask]
print(x_batch)

输出:

[3 3 2]
[13 13 12]

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 2019-11-07
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2021-03-26
    相关资源
    最近更新 更多