Python矩阵内积

Python矩阵内积,python,python-2.7,numpy,inner-product,Python,Python 2.7,Numpy,Inner Product,我试图解决以下问题: ''' 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_pro

我试图解决以下问题:

'''
        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?区别是什么?

如果两个矩阵的最后一个维度相同,则可以计算内积。因此,不应检查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)
现在,我们只需要依赖这样一个事实,即numpy已经正确地实现了内矩阵的逻辑,并且在无法计算内积的情况下会产生一个值错误

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

这意味着您的函数返回False,但这是不正确的,您的函数应该返回Truewell@hpaulj测试用例在幕后,我无法访问它正在对您的函数运行一些测试,它失败了。这是在测试你的结果是否正确。它没有告诉我们正在测试什么或者它期望什么。你自己做过测试吗?给我们看一些你自己的测试。它们看起来对吗。尤其是你的形状测试是对的吗?根据维度的数量,你是在谈论排名吗?@DietrichEpp:在重读你的评论之后。我指的是蓝。。关于X.形状等等,我想让我大吃一惊的是3D矩阵的想法。你们可以有一个秩3张量,或者你们可以有一个3D数组,但3D矩阵混合了一些术语。矩阵的定义总是二维的。@DietrichEpp:是的,正确的名称确实是张量。我修改了它。较好的
def mat_dot_product(X,Y):
    if X.shape[-1] != Y.shape[-2]:
        return False
    else:
        return np.dot(X,Y)