SciPy : Scientific Python

http://scipy.org

A framework for numerical computing using Python.

  • Special functions (scipy.special)
  • Integration (scipy.integrate)
  • Optimization (scipy.optimize)
  • Interpolation (scipy.interpolate)
  • Fourier Transforms (scipy.fftpack)
  • Signal Processing (scipy.signal)
  • Linear Algebra (scipy.linalg)
  • Sparse Eigenvalue Problems (scipy.sparse)
  • Statistics (scipy.stats)
  • Multi-dimensional image processing (scipy.ndimage)
  • File IO (scipy.io)

Some great examples are here: https://scipy-lectures.github.io/intro/scipy.html


Q. Import and explore the library.


In [18]:
import scipy.optimize

In [19]:
scipy.optimize??

Q. Find the minimum of the following function: $ f(x)= x^2 + 10\cdot\sin(x)$


In [20]:
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return x**2 + 10*np.sin(x)

Plot the function using matplotlib.


In [21]:
x = np.arange(-10, 10, 0.1)
fig, ax = plt.subplots(figsize=(10,5))
ax.plot(x, f(x));
ax.hlines(0,-10, 10, alpha=0.1);



In [22]:
initial_x = 5.0

In [23]:
minimum_x = scipy.optimize.fmin_bfgs(f, initial_x)


Optimization terminated successfully.
         Current function value: -7.945823
         Iterations: 5
         Function evaluations: 24
         Gradient evaluations: 8

Plot the found minimum.


In [24]:
%matplotlib inline

x = np.arange(-10, 10, 0.1)
fig, ax = plt.subplots(figsize=(10,5))
ax.plot(x, f(x));
ax.hlines(0,-10, 10, alpha=0.1);
ax.plot(initial_x, f(initial_x), 'or')
ax.plot(minimum_x, f(minimum_x), 'og')


Out[24]:
[<matplotlib.lines.Line2D at 0x8649390>]

Q. Approximate the density of the following superposition of normals: $\mathcal{N}(-1.0, 0.5) + \mathcal{N}(1.0, 0.5)$


In [25]:
import scipy.stats as stats

N0 = stats.norm.rvs(loc=-1.0,scale=.5,size=1000)
N1 = stats.norm.rvs(loc=1.0,scale=.5,size=1000)
samp = np.hstack([N0, N1])

Plot the distribution of the data, using a histogram. Using the hist method.


In [26]:
fig, ax = plt.subplots(figsize=(10,5))
ax.hist(samp, 100, normed=1)
ax.set_xlim(-5, 5);
ax.grid()


Estimate the distribution of the data using a kernel density estimation.

http://en.wikipedia.org/wiki/Kernel_density_estimation


In [27]:
pdf = stats.gaussian_kde(samp)
fig, ax = plt.subplots(figsize=(10,5))
x = np.linspace(-5, 5, 100)
ax.plot(x, pdf(x),'r')
ax.hist(samp, 100, normed=1, alpha=.5);



In [28]:
pdf(0.)


Out[28]:
array([ 0.14291297])

In [29]:
pdf(-1.), pdf(1.0)


Out[29]:
(array([ 0.35811933]), array([ 0.34182221]))

In [ ]: