Meruemu
Meruemu

Reputation: 611

Python matrix inner product

I am trying to solve the below question:

'''
        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.
        '''

with the following code:

def mat_inner_product(X,Y):

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

I got the following error message:

.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)

What does it mean "False is not true"? Do I have a logic error? Or should I use .dot() rather than .inner()? What is the difference?

Upvotes: 2

Views: 2402

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477230

One can calculate the inner product given that the last dimension of both matrices are the same. So you should not check whether X.shape is equal to Y.shape, but only the last dimension:

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

Furthermore the number of dimensions - the .ndim (which is the len(X.shape) - do not have to be the same either: you can calculate the inner product of a 2d matrix with a 3d tensor.

You can however omit the check and use a try-except item:

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

Now we only have to rely on the fact that numpy has implemented the logic of the inner matrix correctly, and will raise a ValueError in case the inner product cannot be calculated.

Or should I use .dot() rather than .inner()? What is the difference?

The difference with the dot product is that it works with the second last dimension of Y (instead of the last that is used in np.inner()). So in case you would work with numpy.dot(..) the check would be:

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

But again, you can make use of a try-except structure here.

Upvotes: 4

Related Questions