python - scipy.curve_fit() 返回多行

标签 python matplotlib scipy curve-fitting

我是 python 的新手,正在尝试使用以下代码来适应数据集分布。实际数据是一个包含两列的列表 - 预测市场价格和实际市场价格。我试图使用 scipy.curve_fit() 但它给了我在同一个地方绘制的许多线。感谢您的帮助。

# import the necessary modules and define a func.
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt

def func(x, a, b, c):
    return a * x** b + c

# my data
pred_data = [3.0,1.0,1.0,7.0,6.0,1.0,7.0,4.0,9.0,3.0,5.0,5.0,2.0,6.0,8.0]
actu_data =[ 3.84,1.55,1.15,7.56,6.64,1.09,7.12,4.17,9.45,3.12,5.37,5.65,1.92,6.27,7.63]
popt, pcov = curve_fit(func, pred_data, actu_data)

#adjusting y 
yaj = func(pred_data, popt[0],popt[1], popt[2])

# plot the data
plt.plot(pred_data,actu_data, 'ro', label = 'Data')
plt.plot(pred_data,yaj,'b--', label = 'Best fit')

plt.legend()
plt.show()

enter image description here

最佳答案

Scipy 不会生成多行,奇怪的输出是由您将未排序的数据呈现给 matplotlib 的方式引起的。对您的 x 值进行排序,您将获得所需的输出:

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

def func(x, a, b, c):
    return a * x** b + c

# my data
pred_data = [3.0,1.0,1.0,7.0,6.0,1.0,7.0,4.0,9.0,3.0,5.0,5.0,2.0,6.0,8.0]
actu_data =[ 3.84,1.55,1.15,7.56,6.64,1.09,7.12,4.17,9.45,3.12,5.37,5.65,1.92,6.27,7.63]
popt, pcov = curve_fit(func, pred_data, actu_data)

#adjusting y 
yaj = func(sorted(pred_data), *popt)

# plot the data
plt.plot(pred_data,actu_data, 'ro', label = 'Data')
plt.plot(sorted(pred_data),yaj,'b--', label = 'Best fit')

plt.legend()
plt.show()

enter image description here

当然,更好的方法是为您的 x 值定义一个均匀间隔的高分辨率数组,并计算该数组的拟合,以更平滑地表示您的拟合函数:

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

def func(x, a, b, c):
    return a * x** b + c

# my data
pred_data = [3.0,1.0,1.0,7.0,6.0,1.0,7.0,4.0,9.0,3.0,5.0,5.0,2.0,6.0,8.0]
actu_data =[ 3.84,1.55,1.15,7.56,6.64,1.09,7.12,4.17,9.45,3.12,5.37,5.65,1.92,6.27,7.63]
popt, pcov = curve_fit(func, pred_data, actu_data)

xaj = np.linspace(min(pred_data), max(pred_data), 1000)
yaj = func(xaj, *popt)

# plot the data
plt.plot(pred_data,actu_data, 'ro', label = 'Data')
plt.plot(xaj, yaj,'b--', label = 'Best fit')

plt.legend()
plt.show()

关于python - scipy.curve_fit() 返回多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50516862/

相关文章:

python - 删除网格线,但保留框架(matplotlib 中的 ggplot2 样式)

python - scipy 信号 find_peaks_cwt 没有准确找到峰值?

Numpy:将矩阵与向量数组相乘

python - python中大数组的乘法

python - 检测4个有趣的像素

python - 如何反转 seaborn 图形级图的轴 (FacetGrid)

python - 来自 scipy.special 的 fadeeva 函数的二阶导数

python - Dataframe 上的多种操作

python - Odoo - create_date 字段更改为 bool 类型?

Python - xlabel 的空间