首页 > 解决方案 > 如何创建一个循环来为相同的 x 曲线拟合 y 的不同数据集?在 Python 中

问题描述

© 有 3 个用于 y 轴值的数据集,如下所示。

y = [0.2535       0.3552       0.456       0.489       0.5265       0.58384  1.87616  2.87328 2.55184  2.66992  2.8208   3.09632  3.51616]
 [0.116112 0.425088 0.582528 0.70192  1.07584  2.41408  3.75232  4.61824 2.55184  2.66992  2.8208   3.09632  3.51616 ]
 [0.389664 1.166368 1.60392  2.05984  2.788    4.02784  5.0184   5.60224 2.55184  2.66992  2.8208   3.09632  3.51616 ]
 

和 x 值的一组数据

x = [  0.     8.75  17.5   26.25  35.    43.75  52.5   61.25  70.    78.75
  87.5   96.25 105.  ]

我正在使用以下命令进行曲线拟合

curve = np.polyfit(x, y, 4)
poly = np.poly1d(curve)

这适用于 y 和 x 的一个数据集。如果我想为相同的 x 集的不同 y 数据集使用 3 个不同的曲线拟合方程,我应该使用什么样的循环?我是 python 新手,这就是我在这样一个基本循环中挣扎的原因。

我的预期输出是一个方程,表示给定数据集(x 和 )的曲线。我设法一一得到一个方程。但。我有大量不同的 y 数据集,我不想一一找到等效方程,因为我可以在循环中为 y 值做,但不知道怎么做?

这是一组 y 值的工作示例。实际上,我有 3 个 y 数据集。我可以更改 y 并获得 3 个不同的结果,但我想在一个循环中对所有 y 值进行

import numpy as np
import matplotlib.pyplot as plt

x =  [0, 5.25, 10.5, 21, 31.5, 42, 52.5, 63, 73.5, 84, 94.5, 99.75, 105]

y = [0,   0.116112, 0.389664, 1.739712, 3.566016, 4.860304, 5.05776,  5.04792,
 4.197744, 2.210064, 0.505776, 0.1312,  0]

curve = np.polyfit(x, y, 4)
poly = np.poly1d(curve)

new_x = []
new_y= []
for a in range(105):
    new_x.append(a+1)
    calc = poly(a+1)
    new_y.append(calc)
    
    plt.plot(new_x, new_y)
    plt.scatter(x, y)
print(poly)

标签: pythonnumpyloopsmatplotlibcurve-fitting

解决方案


以下是您的代码的一些改进。我制作了一个功能来自动处理您的数据。不要忘记 numpy 提供向量化操作,因此迭代 new_x 以获取 new_y 是没有用的。矢量化操作更具可读性和性能。我让您在数据集的循环内调用该函数。

import numpy as np
import matplotlib.pyplot as plt

def my_function(x,y):
    curve = np.polyfit(x, y, 4)
    poly = np.poly1d(curve)

    new_x = np.arange(x[0],x[-1],1)
    new_y= poly(new_x)

    plt.plot(new_x, new_y)
    plt.scatter(x, y)
    print(poly)
    
x =  [0, 5.25, 10.5, 21, 31.5, 42, 52.5, 63, 73.5, 84, 94.5, 99.75, 105]

y1 = [0,   0.116112, 0.389664, 1.739712, 3.566016, 4.860304, 5.05776,  5.04792,
 4.197744, 2.210064, 0.505776, 0.1312,  0]
y2 = [0.116112 0.425088 0.582528 0.70192  1.07584  2.41408  3.75232  4.61824 2.55184  2.66992  2.8208   3.09632  3.51616 ]
y3 = [0.389664 1.166368 1.60392  2.05984  2.788    4.02784  5.0184   5.60224 2.55184  2.66992  2.8208   3.09632  3.51616 ]

ylist = [ y1, y2, y3]

for y in ylist:    
   my_function(x,y)

推荐阅读