prototypemethods.py 文件源码

python
阅读 29 收藏 0 点赞 0 评论 0

项目:ML-lib 作者: christopherjenness 项目源码 文件源码
def predict(self, x, k=1, model='regression'):
        """
        Note: currenly only works on single vector and not matrices

        Args:
            x (np.ndarray): Training data of shape[1, n_features]
            k (int): number of nearest neighbor to consider
            model: {'regression', 'classification'}
                K nearest neighbor classification or regression.
                Choice most likely depends on the type of data the
                model was fit with.

        Returns:
            float: Returns predicted value

        Raises:
            ValueError if model has not been fit
        """
        if not self.learned:
            raise NameError('Fit model first')
        distances = np.array([])
        for row in range(np.shape(self.samples)[0]):
            # Add distance from x to sample row to distances vector
            distances = np.append(distances,
                                  np.linalg.norm(x - self.samples[row, :]))
            nearestneighbors = distances.argsort()[:k]
        if model == 'regression':
            prediction = self.values[nearestneighbors].mean()
        if model == 'classification':
            prediction = stats.mode(self.values[nearestneighbors]).mode
        return prediction
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号