2

我正在尝试解决以下问题:

'''
        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()?有什么区别?

4

1 回答 1

4

假设两个矩阵的最后一个维度相同,可以计算内积。所以你不应该检查是否等于,而只检查最后一个维度:X.shapeY.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)- - 也不必相同:您可以计算 2d 矩阵与 3d 张量的内积。

但是,您可以省略检查并使用try-except项:

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

现在我们只需要依靠numpy已经正确实现了内矩阵逻辑的事实,并且ValueError在无法计算内积的情况下会提出a。

或者我应该使用.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结构。

于 2017-07-07T19:27:53.723 回答