从np.random.choice获取{ValueError}'a'必须是1-dimensoinal

dis*_*ame 6 python numpy

我想从XOR函数创建一个玩具训练集:

xor = [[0, 0, 0],
       [0, 1, 1],
       [1, 0, 1],
       [1, 1, 0]]

input_x = np.random.choice(a=xor, size=200)
Run Code Online (Sandbox Code Playgroud)

但是,这给了我

{ValueError} 'a' must be 1-dimensoinal
Run Code Online (Sandbox Code Playgroud)

但是,如果我在此列表中添加例如一个数字:

xor = [[0, 0, 0],
       [0, 1, 1],
       [1, 0, 1],
       [1, 1, 0],
       1337]       # With this it will work

input_x = np.random.choice(a=xor, size=200)
Run Code Online (Sandbox Code Playgroud)

它开始工作。为什么会这样,又如何在不必向xor列表中添加其他原语的情况下进行这项工作?

Ano*_*tra 6

如果您想要来自 的随机列表xor,您可能应该这样做。

xor[np.random.choice(len(xor),1)]
Run Code Online (Sandbox Code Playgroud)


Blo*_*dyD 6

如果是数组,我将执行以下操作:

xor = np.array([[0,0,0],
       [0,1,1],
       [1,0,1],
       [1,1,0]])
indices = np.arange(len(xor))
rnd_indices = np.random.choice(indices, size=200)

xor_data = xor[rnd_indices]
Run Code Online (Sandbox Code Playgroud)

  • 您还可以优化代码,如其他人建议的那样,使用np.random.choice(len(xor),size = 200);) (2认同)