![](/img/trans.png)
[英]Numpy Error: only size-1 arrays can be converted to python scalars when I use math.exp
[英]When I get the row index from numpy array: only size-1 arrays can be converted to Python scalars
我试图为背包问题实施“蛮力”,我随机生成值和成本表。 我的 BruteForce 返回正确答案,但有时它返回 TypeError: only size-1 arrays 可以转换为 Python 标量。 问题出在“bestItems.append(int(np.where(np.all(table==element,axis=1))[0]))那一行
def BruteForce(table):
wholeWeight = table[:,0].sum()
bagWeight = 0.5 * wholeWeight
bestScore = 0
bestItems = []
for num in range(len(table)):
for com in combinations(table,num+1):
WEIGHT = sum([elem[0] for elem in com])
COST = sum([elem[1] for elem in com])
if WEIGHT <= bagWeight and bestScore < COST:
bestScore = COST
bestItems = []
for element in com:
bestItems.append(int(np.where(np.all(table==element, axis=1))[0]))
return bestScore, bestItems
例如:
np.array([[2, 8],
[2, 8],
[6 ,7],
[6, 5],
[6, 1]])
返回:TypeError:只有 size-1 arrays 可以转换为 Python 标量
但是如果表=:
np.array([[9, 6],
[4, 7],
[8 ,9],
[9, 7],
[3, 4]])
返回:(20, [1, 2, 4])
In [45]: table = np.array([[2, 8],
...: [2, 8],
...: [6 ,7],
...: [6, 5],
...: [6, 1]])
In [47]: np.all(table==[2,8], axis=1)
Out[47]: array([ True, True, False, False, False])
In [48]: np.where(np.all(table==[2,8], axis=1))
Out[48]: (array([0, 1]),)
In [49]: np.where(np.all(table==[2,8], axis=1))[0]
Out[49]: array([0, 1])
In [50]: int(np.where(np.all(table==[2,8], axis=1))[0])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-50-cb698d9f7e05> in <module>
----> 1 int(np.where(np.all(table==[2,8], axis=1))[0])
TypeError: only size-1 arrays can be converted to Python scalars
where
产生一个元组 integer arrays。 int()
包装器仅在只有一个匹配项时才有效。
In [51]: int(np.where(np.all(table==[2,7], axis=1))[0])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-51-294e3139501e> in <module>
----> 1 int(np.where(np.all(table==[2,7], axis=1))[0])
TypeError: only size-1 arrays can be converted to Python scalars
In [52]: int(np.where(np.all(table==[6,7], axis=1))[0])
Out[52]: 2
您需要更稳健地处理比赛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.