对象到深度为所需的数组,numpy随机选择



这是我一直在使用的代码,用于从棒球游戏模拟器中生成随机加权选择,我一直在做我的第一个 python 项目。

elements = ['1b', '2b', '3b', 'hr', 'bb', 'k', 'out']
if order_pos_away == 1:
weights = ab1
if order_pos_away == 2:
weights = ab2
if order_pos_away == 3:
weights = ab3
if order_pos_away == 4:
weights = ab4
if order_pos_away == 5:
weights = ab5
if order_pos_away == 6:
weights = ab6
if order_pos_away == 7:
weights = ab7
if order_pos_away == 8:
weights = ab8
if order_pos_away == 9:
weights = ab9
from numpy.random import choice
c = choice(elements, p=weights)

每次循环通过order_pos_away时都会增加 1,因此下一个击球手的概率列表加起来正好是 1。手动输入列表概率时,我没有问题。但是,当我尝试从存储它们的 excel 工作表导入它们时,出现错误:

ValueError: object too deep for desired array

我已经尝试了多种将excel数据放入python的方法(read_csv,xlrd,numpy,pandas(。无论我尝试什么,我总是以相同的错误告终。我没有找到解决方案,就像我搜索的那样,当我收到此错误时,甚至很难找到对正在发生的事情的良好解释。

由于问题似乎来自从文件加载的权重,让我们探讨一下choice如何处理如此权重数组的行为:

In [227]: elements=['1b', '2b', '3b', 'hr', 'bb', 'k', 'out']

默认值 - 罚款:

In [228]: np.random.choice(elements)
Out[228]: 'k'

总和为 1 的一维数组也可以:

In [229]: np.random.choice(elements, p=np.ones(7)/7)
Out[229]: '2b'

但是 2D 数组,即使是大小正确的(列或行(也会产生此错误:

In [230]: np.random.choice(elements, p=np.ones((1,7))/7)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-230-0be221b99732> in <module>()
----> 1 np.random.choice(elements, p=np.ones((1,7))/7)
mtrand.pyx in mtrand.RandomState.choice()
ValueError: object too deep for desired array
In [231]: np.random.choice(elements, p=np.ones((7,1))/7)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-231-88812915113a> in <module>()
----> 1 np.random.choice(elements, p=np.ones((7,1))/7)
mtrand.pyx in mtrand.RandomState.choice()
ValueError: object too deep for desired array

查找ValueError,我发现它通常在使用相关、卷积和各种曲线拟合任务时出现。 这让我怀疑编译函数(例如np.choice(和维度问题。 我仍然不太确定来源是什么,但是堆栈跟踪中的.pyx文件让我怀疑cython代码。

您需要做的是向我们展示从excel源加载的一个或多个问题权重。 专注于shapedtype。 显示示例csv文件以及用于加载它的方法的一个或多个方法可能会有所帮助。


网络搜索显示此错误也会出现np.convolvenp.bincount。 这些也是将一维数组作为输入的函数。

最新更新