1

I am trying to fit a curve to this set of data using the optimize.curve_fit method in Spyder. I keep getting the optimize warning: cannot calculate covariance error. Could someone please explain why I keep getting this error?

time_in_days = np.array([0, 0.0831, 0.1465, 0.2587, 0.4828, 0.7448, 0.9817, 1.2563, 1.4926, 1.7299, 1.9915, 3.0011, 4.0109, 5.009, 5.9943, 7.0028])

viral_load = np.array([106000, 93240, 167000, 154000, 119000, 117000, 110000, 111000, 74388, 83291, 66435, 21125, 20450, 15798, 4785.2])

#defining function
def VL_func(time, A, B, alpha, beta):
    """

    Parameters
    ----------
    time : Time in days
    A : constant
    B : constant
    alpha : constant
    beta : constant

    Returns VL
    ------
    """
    VL = (A * np.exp(-alpha * time_in_days)) + (B * np.exp(-beta * time_in_days))
    return np.round(VL)

popt, pcov = curve_fit(VL_func, time_in_days, viral_load)
print(popt)
print("\n")
print(pcov)

error message:

OptimizeWarning: Covariance of the parameters could not be estimated
  category=OptimizeWarning
Amy Ott
  • 13
  • 2

1 Answers1

0

As you can see here, the shape of your data is important. I've reproduced your problem here, and going a little deeper I found this. Your variable time_in_days and viral_load have different lengths.

ValueError: operands could not be broadcast together with shapes (16,) (15,)

hcp
  • 319
  • 2
  • 16
  • 1
    Thanks! My original script was creating the arrays from a text file, so I didn't even realize they were different sizes! – Amy Ott Jun 12 '20 at 20:07