2017-07-07 221 views
2

我試圖解決以下問題:Python的矩陣內積

''' 
     Take in two matrices as numpy arrays, X and Y. Determine whether they have an inner product. 
     If they do not, return False. If they do, return the resultant matrix as a numpy array. 
     ''' 

用下面的代碼:

def mat_inner_product(X,Y): 

    if X.shape != Y.shape: 
     return False 
    else: 
     return np.inner(X,Y) 

,我得到了以下錯誤消息:

.F 
====================================================================== 
FAIL: test_mat_inner_product (test_methods.TestPython1) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "/usr/src/app/test_methods.py", line 27, in test_mat_inner_product 
    self.assertTrue(np.array_equal(result2, correct2)) 
AssertionError: False is not true 

---------------------------------------------------------------------- 
Ran 2 tests in 0.001s 

FAILED (failures=1) 

什麼這是否意味着「錯誤是不正確的」?我有邏輯錯誤嗎?或者我應該使用.dot()而不是.inner()?有什麼不同?

+0

這意味着你的函數返回了'False',但那是不正確的,你的函數應該返回'True'。 –

+0

向我們展示測試代碼 – hpaulj

+0

@hpaulj測試用例位於我無法訪問的場景後面 – Meruemu

回答

4

一個可以計算內積鑑於兩個矩陣的最後一維是相同。所以,你不應該檢查X.shape是否等於Y.shape,但只有最後一個維度:

def mat_inner_product(X,Y): 
    if X.shape[-1] != Y.shape[-1]: 
     return False 
    else: 
     return np.inner(X,Y)

而且維數 - 的.ndim(這是len(X.shape) - 不必是相同的兩種:可以用3D計算張二維矩陣的內積

但是,您可以省略檢查,並使用try - except項目:

def mat_inner_product(X,Y): 
    try: 
     return np.inner(X,Y) 
    except ValueError: 
     return False

現在我們只需要依靠numpy已經正確實現了內部矩陣的邏輯的事實,並且在內部產品不能被計算的情況下將提高ValueError

或者我應該使用.dot()而不是.inner()?有什麼不同?

與點積不同的是,它的工作原理與所述Y第二最後尺寸(代替了在np.inner()使用的最後一個)。所以,如果你將與numpy.dot(..)工作的檢查將是:

def mat_dot_product(X,Y): 
    if X.shape[-1] != Y.shape[-2]: 
     return False 
    else: 
     return np.dot(X,Y)

但同樣,你可以使用一個try的 - except結構在這裏。

+0

通過「維數」你談論的排名? –

+0

@DietrichEpp:重讀您的評論之後。我的意思是'X.shape'的'len(..)'等。 –

+0

我覺得是什麼讓我感到「3D矩陣」的概念。你可以有一個3級張量,或者你可以有一個3D數組,但是3D矩陣可以混合一些術語。根據定義,矩陣總是2D。 –