【问题标题】:curve fitting and matplotlib曲线拟合和matplotlib
【发布时间】:2020-01-21 19:28:31
【问题描述】:

我有这三个变量,我想绘制其中两个变量之间的关系:

x = [0.125735  , 0.11753342, 0.11572967, 0.11963533, 0.1255283 ,
       0.13183589, 0.13904629, 0.14754317, 0.15548172, 0.16429631,
       0.17474308, 0.18641375]
y = [0.11917991, 0.10663986, 0.09897077, 0.09291739, 0.08743263,
       0.08346636, 0.08161819, 0.08132199, 0.08216186, 0.0834759 ,
       0.08551088, 0.08770163]
z = [1, 2, 3, 4, 5,
       6, 7, 8, 9, 10 ,
       11, 12]

图片显示x,y。我想拟合一条穿过所有这些点的线,并用z标记每个点。

【问题讨论】:

  • 但它不是functionie它没有每个y唯一的x,所以你不能用多项式 function 来拟合它。也许你能把它翻译成极坐标?
  • @MarkMikofski 抱歉,我注意到这个问题缺乏进一步的解释。我更新了问题。
  • 感谢您的解释,所以 IIUC,点 1 (0.126, 12) 位于图的顶部,点 2 (0.12, 0.11) 是下一个逆时针方向绕到最后一点 12 (0.186, 0.09) 在右下角。所以这意味着一条穿过这些点的线会弯曲,因此在给定的 x 处,比如 0.12,会有两个 y 值,想象一条从 0.12 垂直相交的线拟合线两次。那不是函数。
  • 由于 x 和 y 的范围大致相同,我建议切换到极坐标系。 (1) 找到平均值 x 和平均值 y,并将所有点移动这些平均值,使中心现在位于 (0, 0),然后计算半径为每个点r=np.sqrt(x*x + y*y),以及到每个点的角度theta=np.arctan2(x, y),那么它将是一个可以用多项式拟合的函数

标签: python matplotlib curve-fitting


【解决方案1】:

无居中

这是一个在极坐标中拟合点的快速示例:

x = [0.125735  , 0.11753342, 0.11572967, 0.11963533, 0.1255283 ,
     0.13183589, 0.13904629, 0.14754317, 0.15548172, 0.16429631,
     0.17474308, 0.18641375]
y = [0.11917991, 0.10663986, 0.09897077, 0.09291739, 0.08743263,
     0.08346636, 0.08161819, 0.08132199, 0.08216186, 0.0834759 ,
     0.08551088, 0.08770163]
z = [1, 2, 3, 4, 5,
     6, 7, 8, 9, 10 ,
     11, 12]

# you need numpy
import numpy as np
import matplotlib.pyplot as plt

x = np.array(x)
y = np.array(y)

r = np.sqrt(x*x + y*y)
theta = np.arctan2(x, y)

plt.scatter(theta, r, z, z)
plt.colorbar()
plt.grid()
plt.title('polar coords')
plt.xlabel('$\\theta$ [rad]')
plt.ylabel('r')

p = np.polyfit(theta, r, 2)
xfit = np.linspace(0.8, 1.15, 15)
yfit = np.polyval(p, x)

plt.plot(xfit, yfit, '--')
plt.legend(['original data', 'fit'])

带居中

如果我们先将点居中,我们可能会做得更好:

# find the averages to find the centroid of the data
x_avg = x.mean()
y_avg = y.mean()

# center the data
x_star = x - x_avg
y_star = y - y_avg

# now find the radii
r = np.sqrt(x_star*x_star + y_star*y_star)

# make sure points are between 0 adn 360[degrees]
theta = np.degrees(np.arctan2(y_star, x_star)) % 360

plt.scatter(theta, r, z, z)
plt.colorbar()
plt.grid()
plt.title('polar coords')
plt.ylabel('r')
plt.xlabel('$\\theta$ [degrees]')

# fit with 3rd order polynomial
# because there are 2 inflection points
p = np.polyfit(theta, r, 3)

# plot fit
x_fit = np.linspace(90, 360, 270)
y_fit = np.polyval(p, x_fit)
plt.plot(x_fit, y_fit, '--')
plt.legend(['original data', 'fit'])

最终输出拟合线

这是通过原始数据的最终输出拟合线:

x_out = y_fit * np.cos(np.radians(x_fit)) + x_avg
y_out = y_fit * np.sin(np.radians(x_fit)) + y_avg

plt.scatter(x, y, z, z)
plt.plot(x_out, y_out, '--')
plt.colorbar()
plt.grid()
plt.title('output fit line')
plt.legend(['original data', 'fit'])

【讨论】:

    【解决方案2】:

    这是一个带有 3D 散点图、3D 表面图和等高线图的图形 3D 表面拟合器。等高线图显示表面明显弯曲,这就是为什么这个例子的方程比平面更适合。您应该能够在 3D 图上单击并拖动它们并在 3 空间中旋转它们以进行目视检查。使用您的数据和一个简单的幂方程“z = a * pow(x, b) + c * pow(y, d)”,拟合参数 a = 2.14091547e+02, b = 1.56841786e+00, c = -2.24366942 e+03 和 d = 2.69437535e+00 得出 RMSE = 0.1122 和 R-sqiared = 0.9989

    import numpy, scipy, scipy.optimize
    import matplotlib
    from mpl_toolkits.mplot3d import  Axes3D
    from matplotlib import cm # to colormap 3D surfaces from blue to red
    import matplotlib.pyplot as plt
    
    graphWidth = 800 # units are pixels
    graphHeight = 600 # units are pixels
    
    # 3D contour plot lines
    numberOfContourLines = 16
    
    
    xData = numpy.array([0.125735  , 0.11753342, 0.11572967, 0.11963533, 0.1255283 , 0.13183589, 0.13904629, 0.14754317, 0.15548172, 0.16429631, 0.17474308, 0.18641375], dtype=float)
    yData = numpy.array([0.11917991, 0.10663986, 0.09897077, 0.09291739, 0.08743263, 0.08346636, 0.08161819, 0.08132199, 0.08216186, 0.0834759 , 0.08551088, 0.08770163], dtype=float)
    zData = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12], dtype=float)
    
    
    def func(data, a, b, c, d):
        x = data[0]
        y = data[1]
        return a * numpy.power(x, b) + c * numpy.power(y, d)
    
    
    def SurfacePlot(func, data, fittedParameters):
        f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    
        matplotlib.pyplot.grid(True)
        axes = Axes3D(f)
    
        x_data = data[0]
        y_data = data[1]
        z_data = data[2]
    
        xModel = numpy.linspace(min(x_data), max(x_data), 20)
        yModel = numpy.linspace(min(y_data), max(y_data), 20)
        X, Y = numpy.meshgrid(xModel, yModel)
    
        Z = func(numpy.array([X, Y]), *fittedParameters)
    
        axes.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=1, antialiased=True)
    
        axes.scatter(x_data, y_data, z_data) # show data along with plotted surface
    
        axes.set_title('Surface Plot (click-drag with mouse)') # add a title for surface plot
        axes.set_xlabel('X Data') # X axis data label
        axes.set_ylabel('Y Data') # Y axis data label
        axes.set_zlabel('Z Data') # Z axis data label
    
        plt.show()
        plt.close('all') # clean up after using pyplot or else there can be memory and process problems
    
    
    def ContourPlot(func, data, fittedParameters):
        f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
        axes = f.add_subplot(111)
    
        x_data = data[0]
        y_data = data[1]
        z_data = data[2]
    
        xModel = numpy.linspace(min(x_data), max(x_data), 20)
        yModel = numpy.linspace(min(y_data), max(y_data), 20)
        X, Y = numpy.meshgrid(xModel, yModel)
    
        Z = func(numpy.array([X, Y]), *fittedParameters)
    
        axes.plot(x_data, y_data, 'o')
    
        axes.set_title('Contour Plot') # add a title for contour plot
        axes.set_xlabel('X Data') # X axis data label
        axes.set_ylabel('Y Data') # Y axis data label
    
        CS = matplotlib.pyplot.contour(X, Y, Z, numberOfContourLines, colors='k')
        matplotlib.pyplot.clabel(CS, inline=1, fontsize=10) # labels for contours
    
        plt.show()
        plt.close('all') # clean up after using pyplot or else there can be memory and process problems
    
    
    def ScatterPlot(data):
        f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    
        matplotlib.pyplot.grid(True)
        axes = Axes3D(f)
        x_data = data[0]
        y_data = data[1]
        z_data = data[2]
    
        axes.scatter(x_data, y_data, z_data)
    
        axes.set_title('Scatter Plot (click-drag with mouse)')
        axes.set_xlabel('X Data')
        axes.set_ylabel('Y Data')
        axes.set_zlabel('Z Data')
    
        plt.show()
        plt.close('all') # clean up after using pyplot or else there can be memory and process problems
    
    
    if __name__ == "__main__":
    
        data = [xData, yData, zData]
    
        initialParameters = [100.0, 1.0, 1000.0, 1.0]
    
        # here a non-linear surface fit is made with scipy's curve_fit()
        fittedParameters, pcov = scipy.optimize.curve_fit(func, [xData, yData], zData, p0 = initialParameters)
    
        ScatterPlot(data)
        SurfacePlot(func, data, fittedParameters)
        ContourPlot(func, data, fittedParameters)
    
        print('fitted prameters', fittedParameters)
    
        modelPredictions = func(data, *fittedParameters) 
    
        absError = modelPredictions - zData
    
        SE = numpy.square(absError) # squared errors
        MSE = numpy.mean(SE) # mean squared errors
        RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
        Rsquared = 1.0 - (numpy.var(absError) / numpy.var(zData))
        print('RMSE:', RMSE)
        print('R-squared:', Rsquared)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 2021-01-19
      • 2015-03-02
      • 2013-09-04
      相关资源
      最近更新 更多