python-3.x 拟合3D数据

yrwegjxp  于 2024-06-14  发布在  Python
关注(0)|答案(2)|浏览(498)

我想把一个函数拟合到一个3D数据上。我用pandas读取数据:

  1. df = pd.read_csv('data.csv')
  2. Ca = df.Ca
  3. q = df.q
  4. L = df.L0

字符串
然后,我将3d函数(z=f(x,y))定义为:

  1. def func(q, Ca, l0, v0, beta):
  2. return l0 + q*v0*(1+beta/(q*Ca))


然后我使用curve_fit来找到最佳拟合参数:

  1. from scipy.optimize import curve_fit
  2. guess = (1,1,1)
  3. popt, pcov = curve_fit(func, q,Ca,L, guess)


它给了我以下错误:

  1. ValueError: `sigma` has incorrect shape.


你知道什么是错误和如何解决它吗?非常感谢你的帮助

2nbm6dog

2nbm6dog1#

这是一个图形化的3D拟合与3D散点图,3D表面图,和3D轮廓图。

  1. import numpy, scipy, scipy.optimize
  2. import matplotlib
  3. from mpl_toolkits.mplot3d import Axes3D
  4. from matplotlib import cm # to colormap 3D surfaces from blue to red
  5. import matplotlib.pyplot as plt
  6. graphWidth = 800 # units are pixels
  7. graphHeight = 600 # units are pixels
  8. # 3D contour plot lines
  9. numberOfContourLines = 16
  10. def SurfacePlot(func, data, fittedParameters):
  11. f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
  12. matplotlib.pyplot.grid(True)
  13. axes = Axes3D(f)
  14. x_data = data[0]
  15. y_data = data[1]
  16. z_data = data[2]
  17. xModel = numpy.linspace(min(x_data), max(x_data), 20)
  18. yModel = numpy.linspace(min(y_data), max(y_data), 20)
  19. X, Y = numpy.meshgrid(xModel, yModel)
  20. Z = func(numpy.array([X, Y]), *fittedParameters)
  21. axes.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=1, antialiased=True)
  22. axes.scatter(x_data, y_data, z_data) # show data along with plotted surface
  23. axes.set_title('Surface Plot (click-drag with mouse)') # add a title for surface plot
  24. axes.set_xlabel('X Data') # X axis data label
  25. axes.set_ylabel('Y Data') # Y axis data label
  26. axes.set_zlabel('Z Data') # Z axis data label
  27. plt.show()
  28. plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems
  29. def ContourPlot(func, data, fittedParameters):
  30. f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
  31. axes = f.add_subplot(111)
  32. x_data = data[0]
  33. y_data = data[1]
  34. z_data = data[2]
  35. xModel = numpy.linspace(min(x_data), max(x_data), 20)
  36. yModel = numpy.linspace(min(y_data), max(y_data), 20)
  37. X, Y = numpy.meshgrid(xModel, yModel)
  38. Z = func(numpy.array([X, Y]), *fittedParameters)
  39. axes.plot(x_data, y_data, 'o')
  40. axes.set_title('Contour Plot') # add a title for contour plot
  41. axes.set_xlabel('X Data') # X axis data label
  42. axes.set_ylabel('Y Data') # Y axis data label
  43. CS = matplotlib.pyplot.contour(X, Y, Z, numberOfContourLines, colors='k')
  44. matplotlib.pyplot.clabel(CS, inline=1, fontsize=10) # labels for contours
  45. plt.show()
  46. plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems
  47. def ScatterPlot(data):
  48. f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
  49. matplotlib.pyplot.grid(True)
  50. axes = Axes3D(f)
  51. x_data = data[0]
  52. y_data = data[1]
  53. z_data = data[2]
  54. axes.scatter(x_data, y_data, z_data)
  55. axes.set_title('Scatter Plot (click-drag with mouse)')
  56. axes.set_xlabel('X Data')
  57. axes.set_ylabel('Y Data')
  58. axes.set_zlabel('Z Data')
  59. plt.show()
  60. plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems
  61. def func(data, a, alpha, beta):
  62. x = data[0]
  63. y = data[1]
  64. return a * (x**alpha) * (y**beta)
  65. if __name__ == "__main__":
  66. xData = numpy.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
  67. yData = numpy.array([11.0, 12.1, 13.0, 14.1, 15.0, 16.1, 17.0, 18.1, 90.0])
  68. zData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.0, 9.9])
  69. data = [xData, yData, zData]
  70. initialParameters = [1.0, 1.0, 1.0] # these are the same as scipy default values in this example
  71. # here a non-linear surface fit is made with scipy's curve_fit()
  72. fittedParameters, pcov = scipy.optimize.curve_fit(func, [xData, yData], zData, p0 = initialParameters)
  73. ScatterPlot(data)
  74. SurfacePlot(func, data, fittedParameters)
  75. ContourPlot(func, data, fittedParameters)
  76. print('fitted prameters', fittedParameters)
  77. modelPredictions = func(data, *fittedParameters)
  78. absError = modelPredictions - zData
  79. SE = numpy.square(absError) # squared errors
  80. MSE = numpy.mean(SE) # mean squared errors
  81. RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
  82. Rsquared = 1.0 - (numpy.var(absError) / numpy.var(zData))
  83. print('RMSE:', RMSE)
  84. print('R-squared:', Rsquared)

字符串

展开查看全部
xa9qqrwz

xa9qqrwz2#

我不确定你的Model-func的正确性,我确定你传递参数的方式不正确。从James菲利普斯的代码中得到空图,只需绘制他的Model-func以适应他的数据

  1. from scipy.optimize import curve_fit
  2. import numpy as np
  3. x_ = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
  4. y_ = np.array([11.0, 12.1, 13.0, 14.1, 15.0, 16.1, 17.0, 18.1, 90.0])
  5. z_ = np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.0, 9.9])
  6. def func(data, a, alpha, beta):
  7. x = data[0]
  8. y = data[1]
  9. return a * (x**alpha) * (y**beta)
  10. # Perform curve fitting
  11. popt, pcov = curve_fit(func, (x_, y_), z_)
  12. # As a quick check of whether the model may be overparameterized (resulting depedencies among dims, or Multicollinearity), calculate the condition number of the covariance matrix:
  13. print(np.linalg.cond(pcov))
  14. # Print optimized parameters
  15. print(popt)
  16. import matplotlib.pyplot as plt
  17. from mpl_toolkits.mplot3d import Axes3D
  18. # Create 3D plot of the data points and the fitted curve
  19. fig = plt.figure()
  20. ax = fig.add_subplot(111, projection='3d')
  21. ax.scatter(x_, y_, z_, color='blue')
  22. x_range = np.linspace(0, 100, 100)
  23. y_range = np.linspace(0, 100, 100)
  24. X, Y = np.meshgrid(x_range, y_range)
  25. Z = func([X, Y], *popt)
  26. ax.plot_surface(X, Y, Z, color='red', alpha=0.7)
  27. ax.set_xlabel('X')
  28. ax.set_ylabel('Y')
  29. ax.set_zlabel('Z')
  30. plt.show()

字符串
x1c 0d1x的数据
但请始终注意fit中pcov的条件号-np.linalg.cond(pcov)-参见docs
较大的值会引起关注。与拟合的不确定性相关的协方差矩阵的对角元素提供了更多信息:np.diag(pcov)阵列([1.48814742e+29,3.78596560e-02,5.39253738e-03,2.76417220e+28])#可以变化-例如注意,第一项和最后一项比其他元素大得多,这表明这些参数的最佳值是模糊的,并且在模型中仅需要这些参数中的一个。
或使用/变更缩放
P.S. ref. curve_fit

展开查看全部

相关问题