简体   繁体   中英

Building an hyperplane from a set of points in Python

I have an hyperplane implementation that looks like this:


class Hyperplane:
    """This is a generalization of the plane in n dimensions
    
    @param unit_normal_vector: the vector that is normal to the plane.
    @param distance_to_origin: the minimal distance in meters of the plane from the origin.
    """

    def __init__(
        self,
        unit_normal_vector: np.ndarray,
        distance_to_origin: float,
    ):
        self.unit_normal_vector: np.ndarray = unit_normal_vector
        self.distance_to_origin: float = distance_to_origin
    
    @classmethod
    def from_n_points(
        cls,
        points: Union[np.ndarray,List[np.ndarray],List[List[float]]],
    ) -> 'Hyperplane':
        """Build an hyperplane from a set of points
        We need exactly n points to build the hyperplane where n is the dimension of the space.
        """
        X = np.array(points)
        k = np.ones(X.shape[0])
        a=np.dot(np.linalg.inv(X), k)
        
        unit_normal_vector: np.ndarray = a / np.linalg.norm(a)
        distance_to_origin: float = -1 / np.linalg.norm(a)
        
        return cls(
            unit_normal_vector=unit_normal_vector,
            distance_to_origin=distance_to_origin,
        )

I hope there is no error... ^_^'

What I need now is to find a way to fit a hyperplane to a set of points where there are more than n points in the points cloud.

It may be a Ransac algorithm or something like this.

Is there a proven method that can be implemented for that?

Thanks

You can use a singular value decomposition (SVD) of the point matrix.

points = ...   # An n-dim point per row
centroid = np.mean(points, axis=0)
u, s, vh = np.linalg.svd(points - centroid, full_matrices=False)

The normal to the hyperplane is the axis corresponding to the smallest singular value. As long as np.linalg.svd() sorts them from largest to smallest, the axis is the last unitary vector of vh .

normal = vh[-1]

The hyperplane is then defined by the centroid and the normal .

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