Created
September 21, 2018 13:49
-
-
Save jimpea/b46e610a6b0080045c508f6206e45536 to your computer and use it in GitHub Desktop.
Matrix multiplication in Python 2.7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Use the recomended numpy array notation | |
import numpy as np | |
y = np.array([6.95,5.22,6.36,7.03,9.71,9.67,10.69,13.88,13.21,14.82]) | |
X0 = np.array(np.ones(10)) | |
X1 = np.array(range(0, 10, 1)) | |
X = np.column_stack((X0.T, X1.T)) | |
yhat = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y.T) | |
print yhat | |
''' | |
> [ 4.97309091 1.06242424] | |
''' | |
# Use the scipy array multiplication notation | |
import scipy as sp | |
y = sp.array([6.95,5.22,6.36,7.03,9.71,9.67,10.69,13.88,13.21,14.82]) | |
X0 = sp.array(np.ones(10)) | |
X1 = sp.array(range(0, 10, 1)) | |
X = sp.column_stack((X0.T, X1.T)) | |
yhat = sp.linalg.inv(X.T.dot(X)).dot(X.T).dot(y.T) | |
print yhat | |
''' | |
> [ 4.97309091 1.06242424] | |
''' | |
# use scipy matrices with the '*' infix matrix multiplication operator | |
y = sp.matrix([6.95,5.22,6.36,7.03,9.71,9.67,10.69,13.88,13.21,14.82]) | |
X0 = sp.matrix(sp.ones(10)) | |
X1 = sp.matrix(range(0, 10, 1)) | |
X = sp.column_stack((X0.T, X1.T)) | |
# the '*' operator works with matrix objects | |
yhat = sp.linalg.inv(X.T * X) * X.T * y.T | |
print yhat | |
''' | |
> [[ 4.97309091] | |
[ 1.06242424]] | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment