如何最小化3次线性拟合的X平方 [英] How to minimize chi squared for 3 linear fits

查看:0
本文介绍了如何最小化3次线性拟合的X平方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from numpy import *
import matplotlib.pyplot as plt
import numpy as np

# This is my data set
x = [15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240]
y = [1, 0.9, 0.8, 0.7, 0.6, 0.55, 0.5, 0.45, 0.4, 0.35, 0.33, 0.31, 0.29, 0.27, 0.25, 0.23]

我想将3个线性回归添加到此数据集。通过用PYPLATE绘制我的数据集,我可以直观地看到结点开始形成的位置(大约在x=105和x=165处)。因此我可以创建3个线性回归(从x是0到105、105到165和165到240)。但我怎么才能科学地做到这一点呢?换句话说,我想在我的数据中添加3个线性回归,以最小化X平方。有没有办法用代码来实现这一点?

推荐答案

您可以在下面找到使用scipy.stats.linregress的自动化过程的代码和输出;解释可以在代码下面找到。输出如下:

斜坡和截流条款如下:

  • 曲线1:-0.0066*x+1.1
  • 曲线2:-0.0033*x+0.85
  • 曲线3:-0.0013*x+0.55

代码如下:

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

x = np.array([15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240])
y = np.array([1, 0.9, 0.8, 0.7, 0.6, 0.55, 0.5, 0.45, 0.4, 0.35, 0.33, 0.31, 0.29, 0.27, 0.25, 0.23])

# get slope of your data
dif = np.diff(y) / np.diff(x)

# determine the change of the slope
difdif = np.diff(dif)

# define a threshold for the allowed change of the slope
threshold = 0.001

# get indices where the diff returns value larger than a threshold
indNZ = np.where(abs(difdif) > threshold)[0]

# this makes plotting easier and avoids a couple of if clauses
indNZ += 1
indNZ = np.append(indNZ, len(x))
indNZ = np.insert(indNZ, 0, 0)

# plot the data
plt.scatter(x, y)

for indi, ind in enumerate(indNZ):

    if ind < len(x):
        slope, intercept, r_value, p_value, std_err = stats.linregress(x[ind:indNZ[indi+1]], y[ind:indNZ[indi+1]])
        plt.plot(x[ind:indNZ[indi+1]], slope * x[ind:indNZ[indi+1]] + intercept)

plt.show()
首先,可以使用np.diff计算斜率。对坡度应用np.diff可以得到坡度显著变化的点;在上面的代码中,我对此使用了一个阈值(如果您总是处理完美的直线,则可以将其设置为一个非常小的值;如果您有噪声数据,则必须调整此值)。

有了斜率显著变化的指数,就可以在相应的部分进行线性回归,并相应地绘制结果。

更详细的for循环:

indNZ

array([ 0,  4,  9, 16])

它给出了三行之间的间隔。因此,蓝线对应于x[0]x[3]的部分,绿线对应于x[4]x[8]的部分,红线对应于x[9]x[15]的部分。在for循环中,选择这些范围,使用scipy.stats.linregress进行线性拟合(如果您愿意,也可以替换为polyfit),然后使用公式slope * x + intercept绘制直线。

这篇关于如何最小化3次线性拟合的X平方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆