简体   繁体   中英

Curve fitting and smoothing using python for 3D data

I am currently using polynomial defined function to create a 3d curve fitting but to no avail. image 1 scatter, image 2 curve fitting code is given below:

#import excel data 
"""
how can I improve this polynomial function, 
is there any better methods instead of polynomial? 
"""

def func(data, a, b, c, d):
    x = data[0]
    y = data[1]
    z = data[2]
    return a + b * x + c * y + d * x**2 
# using curve fitting to pass the function 
fittedParameters, pcov = scipy.optimize.curve_fit(
    func, [xData, yData, zData], 
    zData, p0 = None, method= 'lm', maxfev=5000000
) #, p0 = None, maxfev=5000

# making mesh grid 
# making meshgrid
xModel = numpy.linspace( min(x_data), max(x_data), 80) #min(x_data)
yModel = numpy.linspace( min(y_data), max(y_data), 80)
X, Y = numpy.meshgrid( xModel, yModel )

#popt = fittedparameters
a = fittedParameters[0]
b = fittedParameters[1]
c = fittedParameters[2]
d = fittedParameters[3]
x = X
y = Y
Z = a + b * x + c * y + d * x**2
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

# add a title for surface plot
axes.set_title('Surface plot of LN(PoF) and length & depth') 


axes.set_xlabel('Depth (mm)')
axes.set_ylabel('Length (mm)')
axes.set_zlabel('LN(PoF)') # Z axis data label

plt.show()

enter image description here

inbuild module


#%% splprep and splev for the 2D smoothing of x and y value 
def splprep_2d(x,y):
    tck, u = interpolate.splprep([x,y], s = 2,
                 task = 0,full_output=0,quiet = 0,
                 k = 5, t=None)
    fittedParameters = interpolate.splev(u,tck)
    xnew = np.array(fittedParameters[0])
    ynew = np.array(fittedParameters[1])
    return xnew, ynew
xnew, ynew = splprep_2d(x,y)
splprep_2d(x,y)

s = 2 is the smoothing factor, lower would result in accurate plot, using higher smoothing factor results in smoothed curve.

K = parabolic nature of the curve, upto 5th parabolic curve can be used.

These are your smoothed parameter: xnew = np.array(fittedParameters[0]) ynew = np.array(fittedParameters[1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM