当前位置: 首页>>代码示例>>Python>>正文


Python neighbors.NearestNeighbors方法代码示例

本文整理汇总了Python中sklearn.neighbors.NearestNeighbors方法的典型用法代码示例。如果您正苦于以下问题:Python neighbors.NearestNeighbors方法的具体用法?Python neighbors.NearestNeighbors怎么用?Python neighbors.NearestNeighbors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sklearn.neighbors的用法示例。


在下文中一共展示了neighbors.NearestNeighbors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fit

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def fit(self, X, y):	
        '''	
            Set's up the train set and self.NN object	
        '''	
        # Create a NearestNeighbors (NN) object. We will use it in `predict` function 	
        self.NN = NearestNeighbors(n_neighbors=max(self.k_list), 	
                                      metric=self.metric, 	
                                      n_jobs=1, 	
                                      algorithm='brute' if self.metric=='cosine' else 'auto')	
        self.NN.fit(X)	

        # Store labels 	
        self.y_train = y	

        # Save how many classes we have	
        self.n_classes = np.unique(y).shape[0] if self.n_classes_ is None else self.n_classes_ 
开发者ID:lampts,项目名称:wsdm19cup,代码行数:18,代码来源:make_knn_feats.py

示例2: nearest_neighbor

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def nearest_neighbor(src, dst):
    '''
    Find the nearest (Euclidean) neighbor in dst for each point in src
    Input:
        src: Nxm array of points
        dst: Nxm array of points
    Output:
        distances: Euclidean distances of the nearest neighbor
        indices: dst indices of the nearest neighbor
    '''

    assert src.shape == dst.shape

    neigh = NearestNeighbors(n_neighbors=1)
    neigh.fit(dst)
    distances, indices = neigh.kneighbors(src, return_distance=True)
    return distances.ravel(), indices.ravel() 
开发者ID:val-iisc,项目名称:3d-lmnet,代码行数:19,代码来源:icp.py

示例3: point_add_sem_label

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def point_add_sem_label(pt, sem, k=10):
    sem_pt = sem[:, 0:3]
    sem_label = sem[:,3]
    pt_label = np.zeros(pt.shape[0])
    if pt.shape[0]==0:
        return pt_label
    else:
        nbrs = NearestNeighbors(n_neighbors=k,algorithm='ball_tree').fit(sem_pt)
        distances, indices = nbrs.kneighbors(pt)
        for i in range(pt.shape[0]):
            labels = sem_label[indices[i]]
            l, count = stats.mode(labels, axis=None)
            pt_label[i] = l
        return pt_label


    
# ----------------------------------------
# Testing
# ---------------------------------------- 
开发者ID:zaiweizhang,项目名称:H3DNet,代码行数:22,代码来源:pc_util.py

示例4: testGPUFaissNearestNeighborsExecution

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def testGPUFaissNearestNeighborsExecution(self):
        rs = np.random.RandomState(0)

        raw_X = rs.rand(10, 5)
        raw_Y = rs.rand(8, 5)

        # test faiss execution
        X = mt.tensor(raw_X, chunk_size=7).to_gpu()
        Y = mt.tensor(raw_Y, chunk_size=8).to_gpu()

        nn = NearestNeighbors(n_neighbors=3, algorithm='faiss', metric='l2')
        nn.fit(X)

        ret = nn.kneighbors(Y)

        snn = SkNearestNeighbors(n_neighbors=3, algorithm='auto', metric='l2')
        snn.fit(raw_X)
        expected = snn.kneighbors(raw_Y)

        result = [r.fetch() for r in ret]
        np.testing.assert_almost_equal(result[0].get(), expected[0], decimal=6)
        np.testing.assert_almost_equal(result[1].get(), expected[1]) 
开发者ID:mars-project,项目名称:mars,代码行数:24,代码来源:test_nearest_neighbors.py

示例5: find_best_eps

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def find_best_eps(data, q=0.05):
    """
    Find best maximal distance (eps) between dots for DBSCAN clustering.

    Parameters
    -------
    data: pd.DataFrame
        Dataframe with features for clustering indexed as in ``retention_config.index_col``
    q: float, optional
        Quantile of nearest neighbor positive distance between dots. The value of it will be an eps. Default: ``0.05``

    Returns
    -------
    Optimal eps

    Return type
    -------
    Float
    """
    nn = NearestNeighbors()
    nn.fit(data)
    dist = nn.kneighbors()[0]
    dist = dist.flatten()
    dist = dist[dist > 0]
    return np.quantile(dist, q) 
开发者ID:retentioneering,项目名称:retentioneering-tools,代码行数:27,代码来源:clustering.py

示例6: test_unsupervised_kneighbors

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def test_unsupervised_kneighbors(n_samples=20, n_features=5,
                                 n_query_pts=2, n_neighbors=5):
    # Test unsupervised neighbors methods
    X = rng.rand(n_samples, n_features)

    test = rng.rand(n_query_pts, n_features)

    for p in P:
        results_nodist = []
        results = []

        for algorithm in ALGORITHMS:
            neigh = neighbors.NearestNeighbors(n_neighbors=n_neighbors,
                                               algorithm=algorithm,
                                               p=p)
            neigh.fit(X)

            results_nodist.append(neigh.kneighbors(test,
                                                   return_distance=False))
            results.append(neigh.kneighbors(test, return_distance=True))

        for i in range(len(results) - 1):
            assert_array_almost_equal(results_nodist[i], results[i][1])
            assert_array_almost_equal(results[i][0], results[i + 1][0])
            assert_array_almost_equal(results[i][1], results[i + 1][1]) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:27,代码来源:test_neighbors.py

示例7: test_unsupervised_inputs

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def test_unsupervised_inputs():
    # test the types of valid input into NearestNeighbors
    X = rng.random_sample((10, 3))

    nbrs_fid = neighbors.NearestNeighbors(n_neighbors=1)
    nbrs_fid.fit(X)

    dist1, ind1 = nbrs_fid.kneighbors(X)

    nbrs = neighbors.NearestNeighbors(n_neighbors=1)

    for input in (nbrs_fid, neighbors.BallTree(X), neighbors.KDTree(X)):
        nbrs.fit(input)
        dist2, ind2 = nbrs.kneighbors(X)

        assert_array_almost_equal(dist1, dist2)
        assert_array_almost_equal(ind1, ind2) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:19,代码来源:test_neighbors.py

示例8: test_radius_neighbors_boundary_handling

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def test_radius_neighbors_boundary_handling():
    """Test whether points lying on boundary are handled consistently

    Also ensures that even with only one query point, an object array
    is returned rather than a 2d array.
    """

    X = np.array([[1.5], [3.0], [3.01]])
    radius = 3.0

    for algorithm in ALGORITHMS:
        nbrs = neighbors.NearestNeighbors(radius=radius,
                                          algorithm=algorithm).fit(X)
        results = nbrs.radius_neighbors([[0.0]], return_distance=False)
        assert_equal(results.shape, (1,))
        assert_equal(results.dtype, object)
        assert_array_equal(results[0], [0, 1]) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:19,代码来源:test_neighbors.py

示例9: test_callable_metric

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def test_callable_metric():

    def custom_metric(x1, x2):
        return np.sqrt(np.sum(x1 ** 2 + x2 ** 2))

    X = np.random.RandomState(42).rand(20, 2)
    nbrs1 = neighbors.NearestNeighbors(3, algorithm='auto',
                                       metric=custom_metric)
    nbrs2 = neighbors.NearestNeighbors(3, algorithm='brute',
                                       metric=custom_metric)

    nbrs1.fit(X)
    nbrs2.fit(X)

    dist1, ind1 = nbrs1.kneighbors(X)
    dist2, ind2 = nbrs2.kneighbors(X)

    assert_array_almost_equal(dist1, dist2) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:20,代码来源:test_neighbors.py

示例10: nearest_neighbor

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def nearest_neighbor(self,src, dst):
        '''
        Find the nearest (Euclidean) neighbor in dst for each point in src
        Input:
            src: Nxm array of points
            dst: Nxm array of points
        Output:
            distances: Euclidean distances of the nearest neighbor
            indices: dst indices of the nearest neighbor
        '''

        assert src.shape == dst.shape

        neigh = NearestNeighbors(n_neighbors=1)
        neigh.fit(dst)
        distances, indices = neigh.kneighbors(src, return_distance=True)
        return distances.ravel(), indices.ravel() 
开发者ID:DLR-RM,项目名称:AugmentedAutoencoder,代码行数:19,代码来源:icp.py

示例11: fit

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def fit(self, X, y):

        # Split the training set in two
        X_fit, self.X_val_, y_fit, self.y_val_ = model_selection.train_test_split(
            X,
            y,
            test_size=self.test_ratio,
            random_state=self.random_state
        )

        # Fit the nearest neighbours
        n_neighbors = int(self.neighbors_ratio * len(self.X_val_))
        self.nn_ = neighbors.NearestNeighbors(n_neighbors=n_neighbors, algorithm=self.algorithm)
        self.nn_.fit(self.X_val_)

        # Fit the ensemble
        self.ensemble.fit(X_fit, y_fit)

        return self 
开发者ID:MaxHalford,项目名称:xam,代码行数:21,代码来源:localized_ensemble.py

示例12: __init__

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def __init__(self, states, rewards, image_plot, ax, images_path, view=0):

        self.image_plot = image_plot
        self.images_path = images_path
        self.knn = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(states)
        self.state_dim = states.shape[1]
        self.ax = ax
        self.states = states
        self.rewards = rewards
        self.view = view

        # Highlight the selected state
        self.kwargs = dict(s=130, color='green', alpha=0.7)
        coords = self.getCoords(0)
        if states.shape[1] > 2:
            self.dot = ax.scatter([coords[0]], [coords[1]], [coords[2]], **self.kwargs)
        else:
            self.dot = ax.scatter([coords[0]], [coords[1]], **self.kwargs) 
开发者ID:araffin,项目名称:srl-zoo,代码行数:20,代码来源:interactive_plot.py

示例13: _fit

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def _fit(self, X):
        n_samples, _      = X.shape
        self.n_neighbors_ = np.maximum(
            1, np.minimum(self.n_neighbors, n_samples - 1)
        )
        self.estimator_   = NearestNeighbors(
            algorithm     = self.algorithm,
            leaf_size     = self.leaf_size,
            metric        = self.metric,
            n_jobs        = self.n_jobs,
            n_neighbors   = self.n_neighbors_,
            p             = self.p,
            metric_params = self.metric_params
        ).fit(X)

        return self 
开发者ID:Y-oHr-N,项目名称:kenchi,代码行数:18,代码来源:distance_based.py

示例14: _fit

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def _fit(self, X):
        n_samples, _            = X.shape
        self.n_neighbors_       = np.minimum(self.n_neighbors, n_samples - 1)
        self.estimator_         = NearestNeighbors(
            algorithm           = self.algorithm,
            leaf_size           = self.leaf_size,
            metric              = self.metric,
            n_jobs              = self.n_jobs,
            n_neighbors         = self.n_neighbors_,
            p                   = self.p,
            metric_params       = self.metric_params
        ).fit(X)
        self._anomaly_score_min = np.max(
            self._anomaly_score(X, regularize=False)
        )

        return self 
开发者ID:Y-oHr-N,项目名称:kenchi,代码行数:19,代码来源:angle_based.py

示例15: do_classify

# 需要导入模块: from sklearn import neighbors [as 别名]
# 或者: from sklearn.neighbors import NearestNeighbors [as 别名]
def do_classify(train_x, train_y, test_x, test_y):
    train_x_bow, test_x_bow = get_all_bow(train_x, test_x)
    classifier = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(train_x_bow)
    distances, indices = classifier.kneighbors(test_x_bow)
    indices = [index[0] for index in indices]
    exact = 0.0
    dfa_equal = 0.0
    for row_index in range(len(test_x_bow)):
        gold = test_y[row_index]
        pred_index = indices[row_index]
        pred = train_y[pred_index]
        print("PRED: {}".format(pred))
        print("GOLD: {}".format(gold))
        if pred == gold:
            exact += 1.0
            print("string equal")
        if regex_equiv_from_raw(pred, gold):
            dfa_equal += 1.0
            print("dfa equal")
        print("")

    print("{} String-Equal Correct".format(exact/len(test_x_bow)))
    print("{} DFA-Equal Correct".format(dfa_equal/len(test_x_bow))) 
开发者ID:nicholaslocascio,项目名称:deep-regex,代码行数:25,代码来源:nearest_neighbors_model.py


注:本文中的sklearn.neighbors.NearestNeighbors方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。