0

I have a set of data ([x[0],x[1]],y), many points in 3D space and use scikit-learn to fit a learn model.

How I can calculate the distance between all the points to the fitting plane?

Does sklearn provide such function? I mean perpendicular distance. My code works but too manually.

I am looking for an existing quick function in a package like sklearn. Thanks.

def Linfit3D(x,y):
    # x is a 2D array, they should be location of each bump, x_loc and y_loc
    # y is the CTV or BTV that need to be fit to the least square plane
    # three value will be returned, a,b, and c, which indicate a + b*x1 + c*x2 =y
    model = sklearn.linear_model.LinearRegression()
    model.fit(x, y)
    coefs = model.coef_
    intercept = model.intercept_
    print("Equation: y = {:.5f} + {:.5f}*x1 + {:.5f}*x2".format(intercept, coefs[0],coefs[1]))
    a=coefs[0]
    b=coefs[1]
    c=-1
    d=intercept
    return a,b,c,d

def point_to_plane_dist(x,y, a, b, c, d):    
    # the plane equation is: a*x + b*y + c*z + d = 0, and typically c=-1
    # so the plane equation typicall is z = a*x + b*y + d
    # and output has concerned the positive/negtive of point on top/bottom of the plane
    f = abs((a * x[0] + b * x[1] + c * y + d))
    e = (math.sqrt(a * a + b * b + c * c))
    zp=a*x[0]+b*x[1]+d
    # print('y = %2f, zp = %2f' %(y,zp))
    if y>=zp:
        return f/e
    elif y<zp:
        return (f/e)*(-1)
Alexander L. Hayes
  • 3,892
  • 4
  • 13
  • 34
  • Does this answer your question? [Linear Regression: How to find the distance between the points and the prediction line?](https://stackoverflow.com/questions/49859625/linear-regression-how-to-find-the-distance-between-the-points-and-the-predictio) – Alexander L. Hayes Nov 26 '22 at 18:58

0 Answers0