NumPy Matrix and Linear Algebra
What's difference between numpy dot() and inner()?
Let's look into 2D array as an example:
>>> a=np.array([[1,2],[3,4]]) >>> b=np.array([[11,12],[13,14]]) >>> np.dot(a,b) array([[37, 40], [85, 92]]) >>> np.inner(a,b) array([[35, 41], [81, 95]])
$\begin{bmatrix} 1 & 2 \\ 3 & 4 \\ \end{bmatrix} $ $\begin{bmatrix} 11 & 12 \\ 13 & 14 \\ \end{bmatrix} $
With dot():
$\begin{bmatrix} 1*11+2*13 & 1*12+2*14 \\ 3*11+4*13 & 3*12+4*14 \\ \end{bmatrix} $ = $\begin{bmatrix} 37 & 40 \\ 85 & 92 \\ \end{bmatrix} $With inner():
$\begin{bmatrix} 1*11+2*12 & 1*13+2*14 \\ 3*11+4*12 & 3*13+4*14 \\ \end{bmatrix} $ = $\begin{bmatrix} 35 & 41 \\ 81 & 95 \\ \end{bmatrix} $The chapters on NumPy have been using arrays (NumPy Array Basics A and NumPy Array Basics B). However, for certain areas such as linear algebra, we may instead want to use matrix.
>>> import numpy as np >>> A = np.matrix([[1.,2], [3,4], [5,6]]) >>> A matrix([[ 1., 2.], [ 3., 4.], [ 5., 6.]])
We may also take the Matlab style by giving a string rather than a list:
>>> B = np.matrix("1.,2; 3,4; 5,6") >>> B matrix([[ 1., 2.], [ 3., 4.], [ 5., 6.]])
Vectors are handled as matrices with one row or one column:
>>> x = np.matrix("10., 20.") >>> x matrix([[ 10., 20.]]) >>> x.T matrix([[ 10.], [ 20.]])
Here is an example for matrix and vector multiplication:
>>> x = np.matrix("4.;5.") >>> x matrix([[ 4.], [ 5.]]) >>> A = np.matrix([[1.,2], [3,4], [5,6]]) >>> A matrix([[ 1., 2.], [ 3., 4.], [ 5., 6.]]) >>> A*x matrix([[ 14.], [ 32.], [ 50.]])
For vectors, indexing requires two indices:
>>> print x[0,0], x[1,0] 4.0 5.0
Though np.matrix takes a real matrix form and look pleasing, usually, for most of the cases, arrays are good enough.
>>> import numpy as np >>> A = np.ones((4,3)) >>> A array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) >>> np.rank(A) 2
Note that the rank of the array is not the rank of the matrix in linear algebra (dimension of the column space) but the number of subscripts it takes!
Scalars have rank 0:
>>> x = np.array(10) >>> x array(10) >>> np.rank(x) 0
NumPy supports arrays of any dimension such as rank 3 (2x2x2):
>>> A = np.ones((2,2,2)) >>> A array([[[ 1., 1.], [ 1., 1.]], [[ 1., 1.], [ 1., 1.]]]) >>> A[1,0,1] 1.0
>>> A = np.array([[1,2],[3,4]]) >>> A array([[1, 2], [3, 4]]) >>> b = np.array([10, 20]) >>> b array([10, 20]) >>> ans = np.dot(A,b) >>> ans array([ 50, 110])
Another example:
$$A=\begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ \end{bmatrix} , B=\begin{bmatrix} 7 & 8 & 9 \\ \end{bmatrix} $$>>> A = np.array([[ 1, 2 ,3], [ 4, 5 ,6]]) >>> B = np.array([7,8,9]) >>> >>> A array([[1, 2, 3], [4, 5, 6]]) >>> >>> B array([7, 8, 9]) >>> >>> A.shape (2, 3) >>> B.shape (3,) >>> >>> A.T array([[1, 4], [2, 5], [3, 6]]) >>> >>> B.T array([7, 8, 9]) >>> >>> A.dot(B) array([ 50, 122]) >>> >>> np.dot(A,B) array([ 50, 122])
Now we want to solve Ax = b:
>>> import numpy as np >>> from numpy.linalg import solve >>> A = np.array([[1,2],[3,4]]) >>> A array([[1, 2], [3, 4]]) >>> b = np.array([10, 20]) >>> b >>> x = solve(A,b) >>> x array([ 0., 5.])
>>> import numpy as np >>> from numpy.linalg import eig >>> A = np.array([[1,2],[3,4]]) >>> eig(A) (array([-0.37228132, 5.37228132]), array([[-0.82456484, -0.41597356], [ 0.56576746, -0.90937671]]))
The eig returns two tuples: the first one is the eigen values and the second one is a matrix whose columns are the two eigen vectors.
We can unpack the tuples:
>>> eigen_val, eigen_vec = eig(A) >>> eigen_val array([-0.37228132, 5.37228132]) >>> eigen_vec array([[-0.82456484, -0.41597356], [ 0.56576746, -0.90937671]])
We want to solve $\int_0^{3}x^4dx = \frac{243}{4}$:
>>> from scipy.integrate import quad >>> def f(x): ... return x**4 ... >>> quad(f, 0., 3.) (48.599999999999994, 5.39568389967826e-13)
The returned tuple indicates (ans, error estimate).
We can get the same answer if we use lambda instead:
>>> quad(lambda x: x**4, 0, 3) (48.599999999999994, 5.39568389967826e-13)
Python tutorial
Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ == '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ...
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ...
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Python Coding Questions IX
Python Coding Questions X
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...
Flask app with Apache WSGI on Ubuntu14/CentOS7 ...
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ...
RabbitMQ(Message broker server) and Celery(Task queue) ...
OpenCV3 and Matplotlib ...
Simple tool - Concatenating slides using FFmpeg ...
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ...
Django 1.6/1.8 Web Framework ...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization