How do one use logarithmic regression in python?

319 Views Asked by At

I am analyzing some data, and need to do a logarithmic curve fit. I have tried to use the scipy.optimize.curve_fit() function, but it does not work. What am i doing wrong?

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

a1 = [0.156, 0.250, 0.294, 0.377, 0.474, 0.582, 0.600, 0.650, 0.800, 0.708]
a2 = [0.274, 0.242, 0.402, 0.424, 0.540, 0.564, 0.707, 0.728, 0.866, 0.582]

t1 = [30, 80.53, 120, 180, 270, 360, 450, 600, 1200, 1813]
t2 = [85.37, 120, 180, 270, 360, 460, 600, 900, 1200, 1800]

x1 = np.array(t1)
x2 = np.array(t2)

y1 = np.array(a1)
y2 = np.array(a2)

plt.scatter(x1,y1, label= 'Parallel 1', color='black')
plt.scatter(x2,y2, label= 'Parallel 2', color='green')

def logaritmic(x, a, b, c):
    return (a+b*np.log(x) + c)

x_reg = np.linspace(0,2000,50)

popt1, pcov1 = curve_fit(logaritmic, x1, y1)
popt2, pcov2 = curve_fit(logaritmic, x2, y2)


plt.plot(x_reg,logaritmic(x_reg, *popt1), color='gray')
plt.plot(x_reg,logaritmic(x_reg, *popt2), color='lightblue')
plt.legend()
plt.show()

1

There are 1 best solutions below

6
On

The function curve_fit is not part of numpy, so make sure you import it from scipy and call it directly (not as np.curve_fit).

from scipy.optimize import curve_fit

popt1, pcov1 = curve_fit(logaritmic, x1, y1) # Instead of np.curve_fit
popt2, pcov2 = curve_fit(logaritmic, x2, y2)