Python - Simple Scipy 'curve_fit' non linear regression with a basic log function

576 Views Asked by At

I am relatively new to coding and have recently been asked by my research professor to create a log regression script to fit functions to experimental data. The input data is always small values (<10 for x,y) and contains no more than 5 data points per experiment.

I have managed to write a script using scipy's curve_fit function but the results I receive don't look correct? Would anyone be able to point out my errors in this simple script?

I have performed my own research on the use of the curve_fit function but it seems everyones case is very specific and any solution that I have found doesn't work with mine for some reason...

This is my code with a small bit of sample data;

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

def func(x, a, b, c):
    return a * log(b * x) + c

x = np.array([0, 1.1029, 1.6148])
y = np.array([-8.5067, -6.8924, -6.713])

popt, pcov = curve_fit (func, x, y)

plt.figure()
plt.plot(x, y, 'k.', label = 'Raw Data')
plt.plot(x, func(x, *popt), 'k-', label = 'Fitted Curve')
plt.xlabel('ln(x)')
plt.ylabel('y')
plt.legend()
plt.show()

This is the graph output that I get;

Graphical Output

Also note after line 12 is executed (the line with the curve_fit function), the following error appears;

RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.

What does this error mean?

Also for a bonus question, does anyone know what the best way to potentially modify this into a multiple parameter regression would be? I understand if you add more variables you may be able to adjust the function in line 6,7 accordingly?

Thank you to whoever offers their expertise, it's much appreciated!

0

There are 0 best solutions below