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?
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 toY.shape
, but only the last dimension:Furthermore the number of dimensions - the
.ndim
(which is thelen(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:Now we only have to rely on the fact that
numpy
has implemented the logic of the inner matrix correctly, and will raise aValueError
in case the inner product cannot be calculated.The difference with the dot product is that it works with the second last dimension of
Y
(instead of the last that is used innp.inner()
). So in case you would work withnumpy.dot(..)
the check would be:But again, you can make use of a
try
-except
structure here.