Unsuitable fit for tanh function in python

Question:

I am trying to fit a tanh function for the dataset shown below. The code has always worked, but there seem to be problems with this dataset. The displayed fit does not fit the data points at all.

I have already tried a few things but have not been able to find a solution.

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

xdata = [26, -30, -60, 80, 110, 60, 40]
ydata = [53, 12.6, 15.8, 100, 102.1, 90.4, 70.2]

def tanh(x, a, b, c, d ):
    return a * np.tanh( b * x + c ) + d

p0 = [max(ydata), np.median(xdata),1,min(ydata)]
popt, pcov = curve_fit(tanh, xdata, ydata, p0, method='dogbox')

xModel = np.linspace(min(xdata), max(xdata))
yModel = tanh(xModel, *popt)

def Plot(graphWidth, graphHeight):
    fig = plt.figure(figsize=(16,9))
    ax = fig.add_subplot(111)
    ax.plot(xdata, ydata,  'D', label="data")
    ax.plot(xModel, yModel, label="fit")
    ax.legend()
    plt.show()

graphWidth = 800
graphHeight = 600

Plot(graphWidth, graphHeight)

Tanh fit

How can I improve the fitting?

Asked By: Gopala

||

Answers:

Provide suitable starting parameters, for example, in the curve_fit call, use:

p0=(100, 0.01, 1, 1)
Answered By: 9769953
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.