python - 在 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()
解决方案
正如 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()
推荐阅读
- cordova - 在加载当前加载现有 IONIC 项目的当前房屋之前建立新的初始视图以加载
- ruby - git push 和 jekyll build for jekyll blog 有什么区别
- docker - 詹金斯无法连接守护进程
- python - 如何使用 python 读取 .odt?
- ios - 使用本地通知 api 在 swift 3 中触发每周通知
- twitter-bootstrap - 如何使用 Bootstrap 3 或 4 - 16 & 24 网格系统
- spring-boot - springboot2.0中使用@cacheable时如何为每个redis缓存配置不同的ttl
- php - 用 PHP 格式化日期时间
- api - Eventbrite api - 我无法按 category_id "music" 排序
- css - 纯 CSS 阅读更多/更少按钮不起作用