簡體   English   中英

ValueError:無法將輸入數組從形狀 (2,2,5) 廣播到形狀 (2,)

[英]ValueError: could not broadcast input array from shape (2,2,5) into shape (2,)

我在嘗試修復該錯誤時遇到問題。 我不太確定它在尋找什么。 我嘗試過它的不同變體。 有什么想法嗎 ?

def matrix_split(matrix):
    matrix = np.array(matrix) # ValueError: could not broadcast input array from shape (2,2,5) 
                                into shape (2,)
    row = matrix.shape[0]
    col = matrix.shape[1]
    row2, col2 = int(row / 2), int(col / 2)
    # print(matrix)
    return matrix[:row2, :col2], matrix[:row2, col2:], matrix[row2:, :col2], matrix[row2:, col2:]

def strassen_mult(m1, m2):
    if m1 == 1:
        return m1 * m2

    a = b = c = d = matrix_split(m1)
    e = f = g = h = matrix_split(m2)

    p1 = strassen_mult(a, f + h)
    p2 = strassen_mult(a + b, h)
    p3 = strassen_mult(c + d, e)
    p4 = strassen_mult(d, g - e)
    p5 = strassen_mult(a + d, e + h)
    p6 = strassen_mult(b - d, g + h)
    p7 = strassen_mult(a - c, e + f)

    c11 = p5 + p4 - p2 + p6
    c12 = p1 + p2
    c21 = p3 + p4
    c22 = p1 + p5 - p3 - p7

    c = np.vstack((np.hstack((c11, c12)), np.hstack((c21, c22))))

    return c

我可以用這個例子重現你的錯誤:

In [53]: alist = [np.ones((2,2,5)), np.ones((2,4,3))]

In [54]: np.array(alist)
C:\Users\paul\AppData\Local\Temp\ipykernel_8352\2629805649.py:1: VisibleDeprecationWarning: Creating 
an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or 
 ndarrays with different lengths or shapes) is deprecated. If you meant to do 
this, you must specify 'dtype=object' when creating the ndarray.
  np.array(alist)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [54], in <cell line: 1>()
----> 1 np.array(alist)

ValueError: could not broadcast input array from shape (2,2,5) into shape (2,)

它試圖從形狀不同的 2 個數組中創建一個數組 - 但在第一個維度上匹配。 這是警告所說的“參差不齊的數組”的一個子案例。

暫無
暫無

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

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