Skip to content

Instantly share code, notes, and snippets.

@jaradc
Created December 1, 2017 21:11
Show Gist options
  • Save jaradc/360cc0857a4f3ecc1c941e51382509af to your computer and use it in GitHub Desktop.
Save jaradc/360cc0857a4f3ecc1c941e51382509af to your computer and use it in GitHub Desktop.
Curve fitting for Polynomial, Logarithmic, and Power
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
df = pd.DataFrame({
'y': [0.996559203, 0.99161362, 0.9925214090000001, 0.986498352,
0.9826329420000001, 0.977550635, 0.9542758440000001, 0.941359915,
0.933388103, 0.929990698, 0.920058004, 0.90789857, 0.909764261,
0.8944469829999999, 0.912682288, 0.913135466, 0.913485262,
0.911788038, 0.912034259, 0.910293632, 0.9170476590000001,
0.907575858, 0.9098013140000001, 0.90602062, 0.8972021179999999,
0.9008619929999999, 0.891679112, 0.909098825, 0.8898716590000001,
0.90187596, 0.8846790999999999, 0.902215421, 0.900445068,
0.894368245, 0.891844857, 0.893816449, 0.885442787, 0.887642119,
0.877802234, 0.8745246609999999, 0.8620522279999999, 0.825483603],
'X': [
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 31, 33, 35, 38,
41, 45, 49, 55, 61, 70, 82, 98, 122, 163, 244, 487]},
columns=['X', 'y'])
x = np.linspace(df['X'].min(), df['X'].max(), 1000)
for i in range(1, 5):
poly = np.polyfit(df['X'], df['y'], i)
curve = np.polyval(poly, x)
if i == 1:
plt.scatter(df['X'], df['y'], label='Correlations')
plt.plot(x, curve, label='Deg: {}'.format(i))
# logarithmic curve fit y = A + B log x
popt, pcov = curve_fit(lambda t,a,b: a+b*np.log(t), df['X'], df['y'])
logy = popt[0] + popt[1]*np.log(df['X'])
plt.plot(df['X'], logy, label='log-fit')
# power curve fit y = A x^-B
# note that df['X'] is passed in as t and we're solving for a and b variables
popt, pcov = curve_fit(lambda t,a,b: a*t**-b, df['X'], df['y'])
powery = popt[0]*df['X']**-popt[1]
plt.plot(df['X'], powery, label='power-fit')
plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment