A framework for numerical computing using Python.
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)
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]:
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.
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]:
In [29]:
pdf(-1.), pdf(1.0)
Out[29]:
In [ ]: