【问题标题】:how to fit data and then sample from the fitted function to draw curve如何拟合数据,然后从拟合函数中采样以绘制曲线
【发布时间】:2017-07-15 02:55:35
【问题描述】:

给定两个数组 x 和 y,我尝试使用 np.polyfit 函数来拟合数据,使用以下方式:

z = np.polyfit(x, y, 20)
f = np.poly1d(z)

但由于我想绘制折线图而不是平滑曲线,所以我使用此函数 f 对数组进行采样以绘制线。

x_new = np.linspace(x[0], x[-1], fitting_size)
y_new = np.zeros(fitting_size)
for t in range(fitting_size):
   y_new[t] = f(x_new[t])

plt.plot(x_new, y_new, marker='v', ms=1)

问题是上面的段代码仍然给了我一个平滑的曲线。我该如何解决?谢谢。

【问题讨论】:

    标签: python matplotlib plot regression


    【解决方案1】:

    不幸的是,这个问题背后的意图有点不清楚。但是,如果要执行线性拟合,则需要提供度数 deg=1polyfit。那么就没有理由从拟合中取样;可以简单地使用相同的输入数组并对其应用拟合函数。

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(-1,5,20)
    y = 3*x**2+np.random.rand(len(x))*10
    
    z = np.polyfit(x, y, 1)
    f = np.poly1d(z)
    
    z2 = np.polyfit(x, y, 2)
    f2 = np.poly1d(z2)
    
    
    plt.plot(x,y, marker=".", ls="", c="k", label="data")
    plt.plot(x, f(x), label="linear fit")
    plt.plot(x, f2(x), label="quadratic fit")
    plt.legend()
    plt.show()
    

    【讨论】:

    • 感谢您的真诚帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    相关资源
    最近更新 更多