使用Scipy最小二乘的3D平面拟合产生完全错误的拟合

时间:2019-04-16 15:27:34

标签: python numpy scipy

我从网格表面提取了一组节点的坐标,并将它们放置在数组中,如下所示:

[[-2.5      4.       0.     ]
 [-6.5      0.       0.     ]
 [-6.5      0.      20.     ]
 ...
 [-3.5      3.      10.5    ]
 [-3.16667  3.33333 10.5    ]
 [-2.83333  3.66667 10.5    ]]

该数据集中的点来自一个我想从中获取方程的平面。我基于此gist的代码创建了python代码。我再次绘制面部以验证计算的平面是否正确/

我拥有的代码如下(其中数据是上面显示的数组):

def least_sq(self, data, order=1):

        # regular grid covering the domain of the data
        X,Y = np.meshgrid(np.arange(-3.0, 3.0, 0.5), np.arange(-3.0, 3.0, 0.5))
        XX = X.flatten()
        YY = Y.flatten()

        #1: linear, 2: quadratic
        if order == 1:
            # best-fit linear plane
            A = np.c_[data[:,0], data[:,1], np.ones(data.shape[0])]
            C,_,_,_ = scipy.linalg.lstsq(A, data[:,2])    # coefficients
            print(C)
            # evaluate it on grid
            #Z = C[0]*X + C[1]*Y + C[2]

            #or expressed using matrix/vector product
            Z = np.dot(np.c_[XX, YY, np.ones(XX.shape)], C).reshape(X.shape)

        elif order == 2:
            # best-fit quadratic curve
            A = np.c_[np.ones(data.shape[0]), data[:,:2], np.prod(data[:,:2], axis=1), data[:,:2]**2]
            C,_,_,_ = scipy.linalg.lstsq(A, data[:,2])
            print(C)
            # evaluate it on a grid
            Z = np.dot(np.c_[np.ones(XX.shape), XX, YY, XX*YY, XX**2, YY**2], C).reshape(X.shape)

        # plot points and fitted surface
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        ax.plot_surface(X, Y, Z, rstride=1, cstride=1, alpha=0.8)
        ax.scatter(data[:,0], data[:,1], data[:,2], c='r', s=50)
        plt.xlabel('X')
        plt.ylabel('Y')
        ax.set_zlabel('Z')
        ax.axis('equal')
        ax.axis('tight')
        plt.show()

我唯一更改的是提供的数据。但是,结果不正确,如您在此处看到的:

IMG1 IMG2

1 个答案:

答案 0 :(得分:0)

对于平面/直线飞机:输入代码“ order = 1 ” 在if行之前

* Z = C [0] * X + C [1] Y + C [2] 不加注释! #Z = np.dot(np.c_ [XX,YY,np.ones(XX.shape)],C).reshape(X.shape)

对于正交平面: order = 2

顺便说一句:您用于拟合的飞机使我想到了安斯科姆四重奏的情况。