Python Forum
matrixes product - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: matrixes product (/thread-19890.html)



matrixes product - paul18fr - Jul-18-2019

Hi all

I'm a Matlab user and I'm progressively rewritting codes into Python using mainly Numpy library and scientific ones (for vectorization - slicing and so); recently I've been confronted to wrong results ; finally I found that it came from the matrixes product; indeed it's necessary to use numpy.dot or "@" character but not "*" one as I did; the strangest thing is that all my previous codes using "*" went to good results.

Thus I'm wondering what's the origin of such behaviour? Dodgy

Just bellow some trials I made in order to test accury and performance of some solutions.

Additional question: why F1 is here a matrix and not a vector? there something I've probably not understood so far Undecided

Thanks for any advice

Paul

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import time

################## pure (n,c) matrix with c > 1
n = 5_000;
A = np.random.random( (n,n) );
B = np.random.random( (n,n) );
C = np.random.random( (n,1) );

# using numpy
t0 = time.time();
D1 = np.dot(np.dot(A,B),C);
t1 = time.time();
print("Duration method 1: {}".format(t1-t0));

# using @
t0 = time.time();
D2 =A @ B @ C;
t1 = time.time();
print("Duration method 2: {}".format(t1-t0));

# using *
t0 = time.time();
D3 = A * B * C;
t1 = time.time();
print("Duration (wrong) method 3: {}".format(t1-t0));

################ (Matrix * vector) => vector
F1 = A * C;
F2 = np.dot(A,C); max_F2_minus_F1 = np.max(np.absolute(F2 - F1)); print("Max (F2 - F1) = {}".format(max_F2_minus_F1));
F3 = A @ C; max_F3_minus_F2 = np.max(np.absolute(F3 - F2)); print("Max (F3 - F2) = {}".format(max_F3_minus_F2));

Finally I guess I've found where my confusion comes from:
  • implicitly numpy uses vectorization (where we need to use " .* " under Matlab, so using (A*B) uner Python it multiplies each row
  • to perform matrix product (linear algebra), then it's necessary to use numpy.dot or "@"

Here after a basic example.

Paul

import numpy as np
import time
n = 5_000;
C = np.random.random( (n,1) );
D = np.random.random( (n,1) );

G1 = D * C;
D = np.transpose(D)
G2 = D @ C;