为什么np.random.choice每次给出相同的结果?

时间:2017-10-23 10:27:17

标签: python arrays numpy multidimensional-array

在REPL中,我可以使用numpy.random.choice()执行以下操作:

>>> import numpy as np
>>> results = ["a", "b", "c"]
>>> probabilities = [0.5, 0.25, 0.25]

>>> choice = np.random.choice(results, 1, p=probabilities)
>>> choice
array(['a'],
      dtype='<U1')

>>> choice = np.random.choice(results, 1, p=probabilities)
>>> choice
array(['c'],
      dtype='<U1')

>>> choice = np.random.choice(results, 1, p=probabilities)
>>> choice
array(['b'],
      dtype='<U1')

如您所见,np.random.choice()每次调用时都会返回不同的内容。

在我的代码中,我有类似的东西:

# We start with a 2D array called areaMap
# It is already filled up to be a grid of None
# I want each square to change to a different biome instance based on its neighbours
# Our parameters are yMax and xMax, which are the maximum coordinates in each direction

yCounter = yMax
for yi in areaMap:
    xCounter = 0
    for xi in yi:
        biomeList = [woodsBiome(), desertBiome(), fieldBiome()]
        biomeProbabilities = np.array([0.1, 0.1, 0.1])

        # (perform some operations to change the probabilities)

        biomeProbabilities = biomeProbabilities / biomeProbabilities.sum()  # it should always sum to 1
        choice = np.random.choice(biomeList, 1, p=biomeProbabilities)[0]  # here we make a choice from biomeList based on biomeProbabilities
        areaMap[yCounter - 1][xCounter - 1] = choice  # set the correct area to choice
        xCounter += 1  # increment
    yCounter -= 1  # decrement (because of some other code, it can't increment)

这是生成包含不同生物群系的2D数组的函数的一部分。稍后在我的代码中,运行后,我得到一个这样的结果:

^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~
^~~__^_~_^~^^~^^^__~

其中每个字符(^~_)代表不同的生物群系。

地图为2D数组的每一行提供相同的结果。

为什么会发生这种情况,我该如何解决?

1 个答案:

答案 0 :(得分:2)

问题在于“我们从名为areaMap的2D数组开始”。首先,它不是一个真正的2D数组,它是一个列表列表。你没有展示你是如何初始化它的,但从结果来看,显然这个列表存在Eric指出的问题:areaMap[0]areaMap[1]areaMap[2],...都是对同一个清单。请参阅How to clone or copy a list?以获取解释以及如何避免这种情况。

既然您正在使用NumPy,为什么不使用实际的2D数组areaMap?喜欢

areaMap = np.empty((M, N), dtype="U1")

其中(M,N)是数组的形状,数据类型声明它将包含长度为1的字符串(在您的示例中似乎就是这种情况)。访问数组元素的语法更简单:

areaMap[yCounter - 1, xCounter - 1]

并且不会出现您遇到的任何问题。