Fitting a line in 3D

前端 未结 2 1030
夕颜
夕颜 2020-11-29 01:05

Are there any algorithms that will return the equation of a straight line from a set of 3D data points? I can find plenty of sources which will give the equation of a line f

2条回答
  •  猫巷女王i
    2020-11-29 01:43

    If your data is fairly well behaved then it should be sufficient to find the least squares sum of the component distances. Then you can find the linear regression with z independent of x and then again independent of y.

    Following the documentation example:

    import numpy as np
    
    pts = np.add.accumulate(np.random.random((10,3)))
    x,y,z = pts.T
    
    # this will find the slope and x-intercept of a plane
    # parallel to the y-axis that best fits the data
    A_xz = np.vstack((x, np.ones(len(x)))).T
    m_xz, c_xz = np.linalg.lstsq(A_xz, z)[0]
    
    # again for a plane parallel to the x-axis
    A_yz = np.vstack((y, np.ones(len(y)))).T
    m_yz, c_yz = np.linalg.lstsq(A_yz, z)[0]
    
    # the intersection of those two planes and
    # the function for the line would be:
    # z = m_yz * y + c_yz
    # z = m_xz * x + c_xz
    # or:
    def lin(z):
        x = (z - c_xz)/m_xz
        y = (z - c_yz)/m_yz
        return x,y
    
    #verifying:
    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = Axes3D(fig)
    zz = np.linspace(0,5)
    xx,yy = lin(zz)
    ax.scatter(x, y, z)
    ax.plot(xx,yy,zz)
    plt.savefig('test.png')
    plt.show()
    

    If you want to minimize the actual orthogonal distances from the line (orthogonal to the line) to the points in 3-space (which I'm not sure is even referred to as linear regression). Then I would build a function that computes the RSS and use a scipy.optimize minimization function to solve it.

提交回复
热议问题