Rahul KULKARNI
Rahul KULKARNI

Reputation: 31

scipy curve_fit raises “OptimizeWarning: Covariance of the parameters could not be estimated” for gompertz model

I am getting following error for curve_fit function for gompertz model. I am trying to fit gompertz curve into the data I have. I am getting warning 'Covariance of the parameters could not be estimated'. The curve shown is not a good fit.

RuntimeWarning -> overflow encountered in exp OptimizeWarning -> Covariance of the parameters could not be estimated category=OptimizeWarning)


enter image description here

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import wget
import json
from pandas import json_normalize as jsonNor
import requests
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from scipy.optimize import curve_fit
from sklearn.metrics import r2_score
import altair as alt



urls = [
    'https://raw.githubusercontent.com/omkarmarkad/COVID19-Pune/master/timeseries-case-counts.csv',
    'https://raw.githubusercontent.com/omkarmarkad/COVID19-Pune/master/age-wise.csv',
    'https://raw.githubusercontent.com/omkarmarkad/COVID19-Pune/master/timeseries-ward-wise.csv',
    'https://raw.githubusercontent.com/omkarmarkad/COVID19-Pune/master/daily-wardwise.csv'
]

[wget.download(url) for url in urls]


age_df = pd.read_csv('age-wise.csv')
daily_df = pd.read_csv('daily-wardwise.csv')
case_df = pd.read_csv('timeseries-case-counts.csv')
ward_df = pd.read_csv('timeseries-ward-wise.csv')

age_df['CFR'] = age_df['Deaths'] * 100 / (age_df['Male'] + age_df['Female'])


def gompertz_model(x,a=1,b=0,c=0):
    return c*np.exp(-b*np.exp(-x/a))


def fit_data_to_function(
    x, y, function, plot=True
):
    params, _ = curve_fit(function, x, y)
    plt.plot(x, y, ".", label="Observations")
    y_fit = function(x, *params)
    print(r2_score(y, y_fit))
    if plot:
        plt.plot(x, y_fit, label="Fitted curve")
        plt.legend()
        plt.show()
    return params




y = np.asarray(case_df['Total Deaths'])
x = np.arange(len(y))


params = fit_data_to_function( x, y, gompertz_model)

Upvotes: 1

Views: 4797

Answers (1)

Stef
Stef

Reputation: 30579

You need to supply sensible initial guesses for the parameters, e.g.:

params, _ = curve_fit(function, x, y, [1, 0, 0])

Result:

enter image description here

Upvotes: 2

Related Questions