python - 拟合数据集的指数曲线
问题描述
import numpy as np
import matplotlib.pyplot as plt
points = np.array([
(333, 195.3267),
(500, 223.0235),
(1000, 264.5914),
(2000, 294.8728),
(5000, 328.3523),
(10000, 345.4688)
])
# get x and y vectors
x = points[:,0]
y = points[:,1]
为了创建适合图表的指数曲线,我的下一步是什么?
解决方案
这是一个将数据拟合到对数二次方程的示例,该对数二次方程拟合数据比指数要好一些,并根据原始数据的散点图绘制拟合曲线。代码不是最优的,例如它重复获取 X 的日志,而不是只做一次。通过直接使用线性拟合方法也可以更有效地拟合 log(x) 数据,但是在这里您可以用更少的代码更改更轻松地用指数替换拟合方程。
import numpy
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
points = numpy.array([(333, 195.3267), (500, 223.0235), (1000, 264.5914), (2000, 294.8728
), (5000, 328.3523), (10000, 345.4688)])
# get x and y vectors
xData = points[:,0]
yData = points[:,1]
# function to be fitted
def LogQuadratic(x, a, b, c):
return a + b*numpy.log(x) + c*numpy.power(numpy.log(x), 2.0)
# some initial parameter values
initialParameters = numpy.array([1.0, 1.0, 1.0])
fittedParameters, pcov = curve_fit(LogQuadratic, xData, yData, initialParameters)
# values for display of fitted function
a, b, c = fittedParameters
# for plotting the fitting results
xPlotData = numpy.linspace(min(xData), max(xData), 50)
y_plot = LogQuadratic(xPlotData, a, b, c)
plt.plot(xData, yData, 'D') # plot the raw data as a scatterplot
plt.plot(xPlotData, y_plot) # plot the equation using the fitted parameters
plt.show()
print('fitted parameters:', fittedParameters)
推荐阅读
- ios - 是否可以将分段控件标题的对齐方式设置为左侧?
- python - 在行间依赖中添加列的最快方法是什么?
- sql - BigQuery/SQL:填补空白作为年份之间的重复行
- php - 使用 PHP PDO 插入多个数组
- java - 在 Pacman 游戏中创建自动运行 PacMan 的 Java 代码
- java - 如何在 Java 中将 Arraylist 添加到另一个 Arraylist
- canoe - 如何在 CANoe 中实时回放 .blf 文件?
- python - Linux 上的 Libarchive 未正确安装(对于 Python)
- arrays - 在 JMeter 中从固定集合中随机选择值
- swift - 如何将 Swift 声明标记为在 iOS 中可用而在 macOS 中不可用