In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pylab as plt
In [2]:
import scipy.optimize
import pandas as pd
In [4]:
d = pd.read_csv("data/dataset_0.csv")
plt.plot(d.x,d.y,'o')
Out[4]:
In [5]:
def linear(x,a,b):
return a + b*x
Defines a linear function of x
with the slope a
and the intercept b
.
In [6]:
def linear(x,a,b):
return a + b*x
def linear_r(param,x,y):
return linear(x,param[0],param[1]) - y
linear
that compares the output of linear
to whatever's in y
. params
holds a
and b
in a list.
In [6]:
def linear_r(param,x,y): # copied from previous cell
return linear(x,param[0],param[1]) - y # copied from previous cell
param_guesses = [0,0]
fit = scipy.optimize.least_squares(linear_r,param_guesses,
args=(d.x,d.y))
fit_a = fit.x[0]
fit_b = fit.x[1]
sum_of_square_residuals = fit.cost
print(fit.x)
least_squares
regression to find values of a
and b
that minimize linear_r
given d.x
and d.y
. fit_a
and fit_b
sum_of_square_residuals
In [8]:
x_range = np.linspace(np.min(d.x),np.max(d.x),100)
plt.plot(d.x,d.y,"o")
plt.plot(x_range,linear(x_range,fit_a,fit_b))
plt.plot(x_range,linear(x_range,0,0))
Out[8]:
In [12]:
def linear(x,a,b):
"""Linear model of x using a (slope) and b (intercept)"""
return a + b*x
def linear_r(param,x,y):
"""Residuals function for linear"""
return linear(x,param[0],param[1]) - y
# Read data
d = pd.read_csv("data/dataset_0.csv")
plt.plot(d.x,d.y,'o')
# Perform regression
param_guesses = [1,1]
fit = scipy.optimize.least_squares(linear_r,param_guesses,args=(d.x,d.y))
fit_a = fit.x[0]
fit_b = fit.x[1]
sum_of_square_residuals = fit.cost
# Plot result
x_range = np.linspace(np.min(d.x),np.max(d.x),100)
plt.plot(x_range,linear(x_range,fit_a,fit_b))
print(fit.cost)
In [17]:
def binding(x,a,b):
"""binding equation with b"""
return a*(b*x/(1 + b*x))
def binding_r(param,x,y):
"""Residuals function for binding"""
return binding(x,param[0],param[1]) - y
# Read data
d = pd.read_csv("data/dataset_0.csv")
plt.plot(d.x,d.y,'o')
# Perform regression
param_guesses = [5,0.3]
fit = scipy.optimize.least_squares(binding_r,param_guesses,args=(d.x,d.y))
fit_a = fit.x[0]
fit_b = fit.x[1]
sum_of_square_residuals = fit.cost
# Plot result
x_range = np.linspace(np.min(d.x),np.max(d.x),100)
plt.plot(x_range,binding(x_range,fit_a,fit_b))
print(fit)
In [ ]:
In [19]:
def model(a,b,x):
return a*(b*x/(1 + b*x))
#Residuals function
def model_r(param,x,y):
return model(param[0],param[1],x) - y
# Read data
d = pd.read_csv("data/dataset_0.csv")
plt.plot(d.x,d.y,'o')
# Perform regression
param_guesses = [5,0.3]
fit = scipy.optimize.least_squares(model_r,param_guesses,args=(d.x,d.y))
fit_a = fit.x[0]
fit_b = fit.x[1]
sum_of_square_residuals = fit.cost
# Plot result
x_range = np.linspace(np.min(d.x),np.max(d.x),100)
plt.plot(x_range,model(x_range,fit_a,fit_b))
print(fit.cost)
In [ ]: