簡體   English   中英

為什么np.random.choice每次都給出相同的結果?

[英]Why is np.random.choice giving the same result every time?

在REPL中,我可以使用numpy.random.choice()執行以下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陣列的每一行,地圖得出的結果相同。

為什么會發生這種情況,我該如何解決?

問題在“我們從一個名為areaMap的2D數組開始”這一行中。 首先,它實際上不是2D數組,而是列表列表。 您沒有顯示如何初始化它,但是從結果來看,很明顯,此列表存在Eric指出的問題: areaMap[0]areaMap[1]areaMap[2] ,...都是對同一列表的引用。 請參閱如何克隆或復制列表? 以獲得解釋以及如何避免這種情況。

由於無論如何都使用NumPy,為什么不只使用實際的2D數組areaMap? 喜歡

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

其中(M,N)是數組的形狀,並且數據類型聲明它將包含長度為1的字符串(在您的示例中似乎是這種情況)。 訪問數組元素的語法更簡單:

areaMap[yCounter - 1, xCounter - 1]

並且不會出現像您遇到的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM