Fitting Models Exercise 1

Imports


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt

Fitting a quadratic curve

For this problem we are going to work with the following model:

$$ y_{model}(x) = a x^2 + b x + c $$

The true values of the model parameters are as follows:


In [2]:
a_true = 0.5
b_true = 2.0
c_true = -4.0

First, generate a dataset using this model using these parameters and the following characteristics:

  • For your $x$ data use 30 uniformly spaced points between $[-5,5]$.
  • Add a noise term to the $y$ value at each point that is drawn from a normal distribution with zero mean and standard deviation 2.0. Make sure you add a different random number to each point (see the size argument of np.random.normal).

After you generate the data, make a plot of the raw data (use points).


In [11]:
# YOUR CODE HERE
# raise NotImplementedError()
x = np.linspace(-5, 5, 30)
y = (x**2)*a_true + x*b_true + c_true + np.random.normal(0.0, 2.0, size=30)
plt.scatter(x, y, color = 'r')
plt.xlabel('x')
plt.ylabel('y')
plt.box(False)
plt.title('Rendomized quadratic curve')


Out[11]:
<matplotlib.text.Text at 0x7f0975340470>

In [12]:
assert True # leave this cell for grading the raw data generation and plot

Now fit the model to the dataset to recover estimates for the model's parameters:

  • Print out the estimates and uncertainties of each parameter.
  • Plot the raw data and best fit of the model.

In [13]:
# YOUR CODE HERE
# raise NotImplementedError()
def model(x, b, m):
    return m*x+b

In [14]:
theta_best, theta_cov = opt.curve_fit(model, x, y)

In [19]:
xfit = np.linspace(-5.0,5.0)
yfit = theta_best[1]*xfit + theta_best[0]
plt.plot(xfit, yfit, color ='k')
plt.scatter(x, y, color = 'r')
plt.xlabel('x')
plt.ylabel('y')
plt.box(False)
plt.title('Rendomized quadratic curve with best fit line')
plt.legend('fd')


Out[19]:
<matplotlib.legend.Legend at 0x7f09751138d0>

In [16]:
assert True # leave this cell for grading the fit; should include a plot and printout of the parameters+errors