为什么我的协方差不能用scipy.optimize.curve_fit来计算?
Why can't my covariance be calculated by scipy.optimize.curve_fit?
我正在尝试使用 Spyder 中的 optimize.curve_fit 方法为这组数据拟合一条曲线。我不断收到优化警告:无法计算协方差错误。有人可以解释为什么我总是收到这个错误吗?
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)
错误信息:
OptimizeWarning: Covariance of the parameters could not be estimated
category=OptimizeWarning
如您所见,数据的形状很重要。
我在这里重现了您的问题,并且更深入地发现了这一点。您的变量 time_in_days
和 viral_load
的长度不同。
ValueError: operands could not be broadcast together with shapes (16,) (15,)
我正在尝试使用 Spyder 中的 optimize.curve_fit 方法为这组数据拟合一条曲线。我不断收到优化警告:无法计算协方差错误。有人可以解释为什么我总是收到这个错误吗?
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)
错误信息:
OptimizeWarning: Covariance of the parameters could not be estimated
category=OptimizeWarning
如您所见time_in_days
和 viral_load
的长度不同。
ValueError: operands could not be broadcast together with shapes (16,) (15,)