Scientific Python (By Stanford)
Scientific Python (By Stanford)
stanford.edu/~schmit/cme193
5-1
Contents
Numpy
Scipy
Matplotlib
Exercises
5-2
Up to now
Covered the basics of Python
Worked on a bunch of tough exercises
From now
Cover specific topics
Less exercises
Time for project
5-3
Feedback
5-4
Remaining topics
5-5
Contents
Numpy
Scipy
Matplotlib
Exercises
5-6
Numpy
5-7
Numpy
5-8
import numpy as np
Basics:
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
print A
# [[1 2 3]
# [4 5 6]]
Af = np.array([1, 2, 3], float)
Slicing as usual.
5-9
More basics
np.arange(0, 1, 0.2)
# array([ 0. , 0.2,
0.4,
0.6,
0.8])
np.linspace(0, 2*np.pi, 4)
# array([ 0.0, 2.09, 4.18, 6.28])
A = np.zeros((2,3))
# array([[ 0., 0.,
#
[ 0., 0.,
# np.ones, np.diag
A.shape
# (2, 3)
0.],
0.]])
5-10
More basics
np.random.random((2,3))
# array([[ 0.78084261, 0.64328818,
#
[ 0.24611092, 0.37011213,
0.55380341],
0.83313416]])
5-11
A = np.zeros((2, 2))
# array([[ 0., 0.],
#
[ 0., 0.]])
C = A
C[0, 0] = 1
print A
# [[ 1.
# [ 0.
0.]
0.]]
5-12
Array attributes
a = np.arange(10).reshape((2,5))
a.ndim
a.shape
a.size
a.T
a.dtype
#
#
#
#
#
2 dimension
(2, 5) shape of array
10 # of elements
transpose
data type
5-13
Basic operations
# array([ 0, 3, 4, 12])
# array([2, 2, 0, 1])
c = [2, 3, 4, 5]
a * c # array([ 0,
3,
8, 15])
5-14
Array broadcasting
5-15
Array broadcasting
5-16
5-17
Vector operations
inner product
outer product
dot product (matrix multiplication)
# note: numpy automatically converts lists
u = [1, 2, 3]
v = [1, 1, 1]
np.inner(u, v)
# 6
np.outer(u, v)
# array([[1, 1, 1],
#
[2, 2, 2],
#
[3, 3, 3]])
np.dot(u, v)
# 6
5-18
Matrix operations
2))
1.],
1.],
1.]])
1.,
1.,
1.],
1.]])
B = np.ones((2, 3))
# array([[ 1., 1.,
#
[ 1., 1.,
1.],
1.]])
5-19
Matrix operations
np.dot(A, B)
# array([[ 2.,
#
[ 2.,
#
[ 2.,
2.,
2.,
2.,
np.dot(B, A)
# array([[ 3.,
#
[ 3.,
3.],
3.]])
np.dot(B.T, A.T)
# array([[ 2., 2.,
#
[ 2., 2.,
#
[ 2., 2.,
2.],
2.],
2.]])
2.],
2.],
2.]])
np.dot(A, B.T)
# Traceback (most recent call last):
#
File "<stdin>", line 1, in <module>
# ValueError: shapes (3,2) and (3,2) not aligned:
# ... 2 (dim 1) != 3 (dim 0)
5: Numpy, Scipy, Matplotlib
...
5-20
a = np.random.random((2,3))
# array([[ 0.9190687 , 0.36497813, 0.75644216],
#
[ 0.91938241, 0.08599547, 0.49544003]])
a.sum()
# 3.5413068994445549
a.sum(axis=0) # column sum
# array([ 1.83845111, 0.4509736 , 1.25188219])
a.cumsum()
# array([ 0.9190687 , 1.28404683, 2.04048899, 2.9598714 ,
#
3.04586687, 3.5413069 ])
a.cumsum(axis=1) # cumulative row sum
# array([[ 0.9190687 , 1.28404683, 2.04048899],
#
[ 0.91938241, 1.00537788, 1.50081791]])
a.min()
# 0.0859954690403677
a.max(axis=0)
# array([ 0.91938241, 0.36497813, 0.75644216])
5-21
Slicing arrays
5-22
5-23
Reshaping
Try it!
5-24
Reshaping
Try it!
5-25
Reshaping
Try it!
5-26
Matrix operations
import numpy.linalg
eye(3)
Identity matrix
trace(A)
Trace
column_stack((A,B))
row_stack((A,B,A))
5-27
Linear algebra
import numpy.linalg
qr
cholesky
inv(A)
Inverse
solve(A,b)
lstsq(A,b)
eig(A)
Eigenvalue decomposition
eig(A)
eigvals(A)
Computes eigenvalues.
svd(A, full)
pinv(A)
Computes pseudo-inverse of A
5-28
Fourier transform
import numpy.fft
fft 1-dimensional DFT
fft2 2-dimensional DFT
fftn N-dimensional DFT
ifft 1-dimensional inverse DFT (etc.)
rfft Real DFT (1-dim)
ifft Imaginary DFT (1-dim)
5-29
Random sampling
import numpy.random
rand(d0,d1,...,dn)
Sample from a
shuffle(a)
Permutation (in-place)
permutation(a)
5-30
Distributions in random
import numpy.random
The list of distributions to sample from is quite long, and includes
beta
binomial
chisquare
exponential
dirichlet
gamma
laplace
lognormal
pareto
poisson
power
5: Numpy, Scipy, Matplotlib
5-31
Contents
Numpy
Scipy
Matplotlib
Exercises
5-32
What is SciPy?
5-33
5-34
Scipy Optimization
5-35
Scipy Statistics
5-36
Scipy sparse
5-37
Scipy signal
Convolutions
B-splines
Filtering
Continuous-time linear system
Wavelets
Peak finding
5-38
Scipy IO
5-39
Contents
Numpy
Scipy
Matplotlib
Exercises
5-40
What is Matplotlib?
5-41
Scatter Plot
import numpy as np
import matplotlib . pyplot as p l t
x = np . linspace (0 , 10, 1000)
y = np . power(x , 2)
p l t . plot (x , y)
p l t . show()
5-42
5-43
Scatter Plot
Adding titles and labels
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
f, ax = plt.subplots(1, 1, figsize=(5,4))
x = np.linspace(0, 10, 1000)
y = np.power(x, 2)
ax.plot(x, y)
ax.set_xlim((1, 5))
ax.set_ylim((0, 30))
ax.set_xlabel(my x label)
ax.set_ylabel(my y label)
ax.set_title(plot title, including $\Omega$)
plt.tight_layout()
plt.savefig(line_plot_plus.pdf)
5-44
Scatter Plot
plot title, including
30
my y label
25
20
15
10
5
0
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
my x label
5-45
Scatter Plot
Adding multiple lines and a legend
x = np . linspace (0 , 10, 50)
y1 = np . power(x , 2)
y2 = np . power(x , 3)
plt . plot (x , y1 , b , label=$x^2$ )
plt . plot (x , y2 , go , label=$x^3$ )
plt . xlim ((1 , 5))
plt . ylim ((0 , 30))
plt . xlabel ( my x label )
plt . ylabel ( my y label )
plt . t i t l e ( plot t i t l e , including $\Omega$ )
plt . legend ()
plt . savefig ( line_plot_plus2 . pdf )
5-46
Scatter Plot
30
x2
x3
25
my y label
20
15
10
0
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0
my x label
5-47
Histogram
5-48
Histogram
0.45
1.0
0.40
0.8
0.35
0.30
0.6
0.25
0.20
0.4
0.15
0.10
0.2
0.05
0.00
4 3 2 1 0
0.0
4 3 2 1 0
5-49
Box Plot
5-50
Box Plot
6
4
sample 1
sample 2
sample 3
5-51
Image Plot
A = np.random.random((100, 100))
plt.imshow(A)
plt.hot()
plt.colorbar()
plt.savefig(imageplot.pdf)
5-52
Image Plot
1.0
0.9
0.8
20
0.7
0.6
40
0.5
0.4
60
0.3
80
0.2
0.1
0
20
40
60
80
0.0
5-53
Wire Plot
5-54
Wire Plot
30
20
10
0
10
20
10
20
3030
100
80
60
40
20
0
20
40
60
80
30
20
10
5-55
Possibilities
5-56
Contents
Numpy
Scipy
Matplotlib
Exercises
5-57
Exercises
5-58