簡體   English   中英

當我從 numpy 數組中獲取行索引時:只有 size-1 arrays 可以轉換為 Python 標量

[英]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.

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