首页 > 解决方案 > 在 python 中使用 scipy 进行曲线拟合以查找校正参数(不能将序列乘以非 int 类型的“numpy.float64”)

问题描述

我正在尝试将函数 h = a0 L(1-a1 L**(-w1) 拟合到我的图表中并找到参数 a0、a1 和 w1。我不知道为什么它不起作用。我不断得到错误:不能将序列乘以“numpy.float64”类型的非整数。这是我的代码片段:

L = [8, 16, 32, 64, 128, 256]
Average_height = [12.973731636721096,26.52865044449718,53.85333875018466,108.90761725203599,219.30647736483996,428.833120246036]

def correction(L, a0, a1, w1):
    return a0*L*(1-a1*L**(-w1))
popt, pcov = curve_fit(correction, L, Average_height, bounds =([0,0,-10], [10,10,10]))
a0, a1, w1 = popt
print((a0, a1, w1)) 
plt.plot(L, correction(L, *popt), 'r-')
plt.show()

标签: pythonnumpyscipycurve-fitting

解决方案


正如 hpaulj 已经提到的,您应该使用 numpy 数组。还有一个杂散的逗号,它一定是一个错字,否则,你会有不同数量的 x 值和 y 值。最后,您通常不能将 Python 幂函数**与 numpy 数组一起使用 - 为此有专用的 numpy 函数np.power。相应地更改代码会导致:

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

L = np.asarray([8, 16, 32, 64, 128, 256])
Average_height = np.asarray([12.973731636721096,26.52865044449718,53.85333875018466,108.90761725203599,219.30647736483996,428.833120246036])

def correction(L, a0, a1, w1):
    return a0*L*(1-a1* np.power(L, -w1))
popt, pcov = curve_fit(correction, L, Average_height, bounds =([0,0,-10], [10,10,10]))
print(*popt) 
#1.6836463115082618 9.999999999965157 2.717334174156468
plt.scatter(L, Average_height, label="Data")
plt.plot(L, correction(L, *popt), 'r-', label="fit")
plt.show()

输出 在此处输入图像描述


推荐阅读