python - 如何定量测量 SciPy 中的拟合优度?

标签 python numpy scipy mathematical-optimization curve-fitting

我正在寻找最适合给定数据的方法。我所做的是遍历 n 的各种值并使用公式 ((y_fit - y_actual)/y_actual) x 100 计算每个 p 的残差。然后我计算每个 n 的平均值,然后找到最小残差平均值以及相应的 n 值并使用该值进行拟合。可重现的代码包括:

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

x = np.array([12.4, 18.2, 20.3, 22.9, 27.7, 35.5, 53.9])
y = np.array([1, 50, 60, 70, 80, 90, 100])
y_residual = np.empty(shape=(1, len(y)))
residual_mean = []

n = np.arange(0.01, 10, 0.01)

def fit(x, a, b):
    return a * x + b
for i in range (len(n)):
    x_fit = 1 / np.log(x) ** n[i]
    y_fit = y
    fit_a, fit_b = optimize.curve_fit(fit, x_fit, y_fit)[0]
    y_fit = (fit_a * x_fit) + fit_b
    y_residual = (abs(y_fit - y) / y) * 100
    residual_mean = np.append(residual_mean, np.mean(y_residual[np.isfinite(y_residual)]))
p = n[np.where(residual_mean == residual_mean.min())]
p = p[0]
print p
x_fit = 1 / np.log(x) ** p
y_fit = y
fit_a, fit_b = optimize.curve_fit(fit, x_fit, y_fit)[0]
y_fit = (fit_a * x_fit) + fit_b
y_residual = (abs(y_fit - y) / y) * 100

fig = plt.figure(1, figsize=(5, 5))
fig.clf()
plot = plt.subplot(111)
plot.plot(x, y, linestyle = '', marker='^')
plot.plot(x, y_fit, linestyle = ':')
plot.set_ylabel('y')
plot.set_xlabel('x')
plt.show()

fig_1 = plt.figure(2, figsize=(5, 5))
fig_1.clf()
plot_1 = plt.subplot(111)
plot_1.plot(1 / np.log(x) ** p, y, linestyle = '-')
plot_1.set_xlabel('pow(x, -p)' )
plot_1.set_ylabel('y' )
plt.show()

fig_2 = plt.figure(2, figsize=(5, 5))
fig_2.clf()
plot_2 = plt.subplot(111)
plot_2.plot(n, residual_mean, linestyle = '-')
plot_2.set_xlabel('n' )
plot_2.set_ylabel('Residual mean')
plt.show()

用 n 绘制残差均值,这是我得到的:

enter image description here

我需要知道此方法是否正确才能确定最合适的方法。如果它可以通过 SciPy 或任何其他包中的其他功能来完成。本质上我想要的是定量地知道哪个是最合适的。我已经通过了Goodness of fit tests in SciPy但这对我帮助不大。

最佳答案

可能最常用的拟合优度度量是 coefficient of determination (又名 R2 值)。

公式为:

enter image description here

哪里:

enter image description here

enter image description here

此处,yi 指的是您输入的 y 值,fi 指的是您的拟合 y -values,̅y 指的是平均输入 y 值。

很容易计算:

# residual sum of squares
ss_res = np.sum((y - y_fit) ** 2)

# total sum of squares
ss_tot = np.sum((y - np.mean(y)) ** 2)

# r-squared
r2 = 1 - (ss_res / ss_tot)

关于python - 如何定量测量 SciPy 中的拟合优度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29003241/

相关文章:

python - 在计算大型 numpy 数组的逆累积分布函数时如何避免 numpy.place 中的错误?

python - 包括半径的余弦距离 - python 特定

python - 科学图像显示python

python - 使用机器学习解码回溯

python - 计算积分的有效方法?

python - 尝试解压 simple.txt 文件时出现 ValueError : too many values to unpack,

python - 与 numpy 并行初始化矩阵

python - 检查 Tkinter Entry 小部件的值

python - 生成用户/项目交互

.net - 从多页 TIFF 文件中删除/删除页面