![](/img/trans.png)
[英]Time performance of np.random.permutation, 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.