Skip to content

Instantly share code, notes, and snippets.

@dottyz
Created May 2, 2019 18:44
Show Gist options
  • Save dottyz/ba3dd0dc62d8415baed54f1fb7738ca9 to your computer and use it in GitHub Desktop.
Save dottyz/ba3dd0dc62d8415baed54f1fb7738ca9 to your computer and use it in GitHub Desktop.
from kneed import KneeLocator
from scipy.optimize import curve_fit
# Define the curve fitting equations
def linear(x, m, b):
return m*x + b
def exp_growth_no_shift(x, a, b):
return a * np.exp(-b * x)
def exp_growth(x, a, b, c):
return a * np.exp(-b * x) + c
x = data['Mean Temp'].values
y = data['Casual Trips'].values
# Estimate curve for each of the method used and graph the fitted curve
fig, axes = plt.subplots(1, 3, figsize=(20, 10))
for ax, func in zip(axes, [linear, exp_growth_no_shift, exp_growth]):
popt, pcov = curve_fit(func, x, y, maxfev=2000)
y_fit = func(x, *popt)
r2 = 1 - (np.sum((y - y_fit) ** 2) / np.sum((y - np.mean(y)) ** 2))
ax.plot(x, y, '.')
ax.plot(x, y_fit, 'r-')
ax.set_ylim(-100, 4200)
ax.set_title('{0} (r2={1})'.format(func.__name__, np.round(r2, 2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment