Python sklearn.neighbors.NearestCentroid() Examples

The following are 19 code examples of sklearn.neighbors.NearestCentroid(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sklearn.neighbors , or try the search function .
Example #1
Source File: test_nearest_centroid.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def test_classification_toy():
    # Check classification on a toy dataset, including sparse versions.
    clf = NearestCentroid()
    clf.fit(X, y)
    assert_array_equal(clf.predict(T), true_result)

    # Same test, but with a sparse matrix to fit and test.
    clf = NearestCentroid()
    clf.fit(X_csr, y)
    assert_array_equal(clf.predict(T_csr), true_result)

    # Fit with sparse, test with non-sparse
    clf = NearestCentroid()
    clf.fit(X_csr, y)
    assert_array_equal(clf.predict(T), true_result)

    # Fit with non-sparse, test with sparse
    clf = NearestCentroid()
    clf.fit(X, y)
    assert_array_equal(clf.predict(T_csr), true_result)

    # Fit and predict with non-CSR sparse matrices
    clf = NearestCentroid()
    clf.fit(X_csr.tocoo(), y)
    assert_array_equal(clf.predict(T_csr.tolil()), true_result) 
Example #2
Source File: test_nearest_centroid.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_classification_toy():
    # Check classification on a toy dataset, including sparse versions.
    clf = NearestCentroid()
    clf.fit(X, y)
    assert_array_equal(clf.predict(T), true_result)

    # Same test, but with a sparse matrix to fit and test.
    clf = NearestCentroid()
    clf.fit(X_csr, y)
    assert_array_equal(clf.predict(T_csr), true_result)

    # Fit with sparse, test with non-sparse
    clf = NearestCentroid()
    clf.fit(X_csr, y)
    assert_array_equal(clf.predict(T), true_result)

    # Fit with non-sparse, test with sparse
    clf = NearestCentroid()
    clf.fit(X, y)
    assert_array_equal(clf.predict(T_csr), true_result)

    # Fit and predict with non-CSR sparse matrices
    clf = NearestCentroid()
    clf.fit(X_csr.tocoo(), y)
    assert_array_equal(clf.predict(T_csr.tolil()), true_result) 
Example #3
Source File: test_neighbors.py    From pandas-ml with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_objectmapper(self):
        df = pdml.ModelFrame([])
        self.assertIs(df.neighbors.NearestNeighbors,
                      neighbors.NearestNeighbors)
        self.assertIs(df.neighbors.KNeighborsClassifier,
                      neighbors.KNeighborsClassifier)
        self.assertIs(df.neighbors.RadiusNeighborsClassifier,
                      neighbors.RadiusNeighborsClassifier)
        self.assertIs(df.neighbors.KNeighborsRegressor,
                      neighbors.KNeighborsRegressor)
        self.assertIs(df.neighbors.RadiusNeighborsRegressor,
                      neighbors.RadiusNeighborsRegressor)
        self.assertIs(df.neighbors.NearestCentroid, neighbors.NearestCentroid)
        self.assertIs(df.neighbors.BallTree, neighbors.BallTree)
        self.assertIs(df.neighbors.KDTree, neighbors.KDTree)
        self.assertIs(df.neighbors.DistanceMetric, neighbors.DistanceMetric)
        self.assertIs(df.neighbors.KernelDensity, neighbors.KernelDensity) 
Example #4
Source File: test_plot.py    From pyDML with GNU General Public License v3.0 5 votes vote down vote up
def test_plot16(self):
        np.random.seed(seed)
        X, y = toy_datasets.balls_toy_dataset(centers=[[-1.0, 0.0], [0.0, 0.0], [1.0, 0.0]],
                                              rads=[0.3, 0.3, 0.3], samples=[50, 50, 50],
                                              noise=[0.1, 0.1, 0.1])
        y[y == 2] = 0
        y = y.astype(int)

        ncm = NearestCentroid()
        ncmc = NCMC_Classifier(centroids_num=[2, 1])
        dml_multiplot(X, y, nrow=1, ncol=2, clfs=[ncm, ncmc], cmap='rainbow',
                      subtitles=['NCM', 'NCMC'], figsize=(6, 3))
        self.newsave()
        plt.close() 
Example #5
Source File: test_nearest_centroid.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_manhattan_metric():
    # Test the manhattan metric.

    clf = NearestCentroid(metric='manhattan')
    clf.fit(X, y)
    dense_centroid = clf.centroids_
    clf.fit(X_csr, y)
    assert_array_equal(clf.centroids_, dense_centroid)
    assert_array_equal(dense_centroid, [[-1, -1], [1, 1]]) 
Example #6
Source File: test_nearest_centroid.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_predict_translated_data():
    # Test that NearestCentroid gives same results on translated data

    rng = np.random.RandomState(0)
    X = rng.rand(50, 50)
    y = rng.randint(0, 3, 50)
    noise = rng.rand(50)
    clf = NearestCentroid(shrink_threshold=0.1)
    clf.fit(X, y)
    y_init = clf.predict(X)
    clf = NearestCentroid(shrink_threshold=0.1)
    X_noise = X + noise
    clf.fit(X_noise, y)
    y_translate = clf.predict(X_noise)
    assert_array_equal(y_init, y_translate) 
Example #7
Source File: test_nearest_centroid.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_shrinkage_threshold_decoded_y():
    clf = NearestCentroid(shrink_threshold=0.01)
    y_ind = np.asarray(y)
    y_ind[y_ind == -1] = 0
    clf.fit(X, y_ind)
    centroid_encoded = clf.centroids_
    clf.fit(X, y)
    assert_array_equal(centroid_encoded, clf.centroids_) 
Example #8
Source File: test_nearest_centroid.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_pickle():
    import pickle

    # classification
    obj = NearestCentroid()
    obj.fit(iris.data, iris.target)
    score = obj.score(iris.data, iris.target)
    s = pickle.dumps(obj)

    obj2 = pickle.loads(s)
    assert_equal(type(obj2), obj.__class__)
    score2 = obj2.score(iris.data, iris.target)
    assert_array_equal(score, score2,
                       "Failed to generate same score"
                       " after pickling (classification).") 
Example #9
Source File: test_nearest_centroid.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_iris_shrinkage():
    # Check consistency on dataset iris, when using shrinkage.
    for metric in ('euclidean', 'cosine'):
        for shrink_threshold in [None, 0.1, 0.5]:
            clf = NearestCentroid(metric=metric,
                                  shrink_threshold=shrink_threshold)
            clf = clf.fit(iris.data, iris.target)
            score = np.mean(clf.predict(iris.data) == iris.target)
            assert score > 0.8, "Failed with score = " + str(score) 
Example #10
Source File: test_nearest_centroid.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_iris():
    # Check consistency on dataset iris.
    for metric in ('euclidean', 'cosine'):
        clf = NearestCentroid(metric=metric).fit(iris.data, iris.target)
        score = np.mean(clf.predict(iris.data) == iris.target)
        assert score > 0.9, "Failed with score = " + str(score) 
Example #11
Source File: test_nearest_centroid.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_precomputed():
    clf = NearestCentroid(metric='precomputed')
    with assert_raises(ValueError) as context:
        clf.fit(X, y)
    assert_equal(ValueError, type(context.exception)) 
Example #12
Source File: test_plot.py    From pyDML with GNU General Public License v3.0 5 votes vote down vote up
def test_plot13(self):
        np.random.seed(seed)
        X, y = iris_data()
        X = X[:, [0, 2]]
        dml = NCMML()
        clf = NearestCentroid()
        dml_plot(X, y, clf, cmap="gist_rainbow", figsize=(15, 8))
        self.newsave()
        dml_plot(X, y, dml=dml, clf=clf, cmap="gist_rainbow", figsize=(15, 8))
        self.newsave()
        dml_pairplots(X, y, dml=dml, clf=clf, cmap="gist_rainbow", figsize=(15, 8))
        self.newsave()
        plt.close() 
Example #13
Source File: test_nearest_centroid.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_manhattan_metric():
    # Test the manhattan metric.

    clf = NearestCentroid(metric='manhattan')
    clf.fit(X, y)
    dense_centroid = clf.centroids_
    clf.fit(X_csr, y)
    assert_array_equal(clf.centroids_, dense_centroid)
    assert_array_equal(dense_centroid, [[-1, -1], [1, 1]]) 
Example #14
Source File: test_nearest_centroid.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_predict_translated_data():
    # Test that NearestCentroid gives same results on translated data

    rng = np.random.RandomState(0)
    X = rng.rand(50, 50)
    y = rng.randint(0, 3, 50)
    noise = rng.rand(50)
    clf = NearestCentroid(shrink_threshold=0.1)
    clf.fit(X, y)
    y_init = clf.predict(X)
    clf = NearestCentroid(shrink_threshold=0.1)
    X_noise = X + noise
    clf.fit(X_noise, y)
    y_translate = clf.predict(X_noise)
    assert_array_equal(y_init, y_translate) 
Example #15
Source File: test_nearest_centroid.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_shrinkage_threshold_decoded_y():
    clf = NearestCentroid(shrink_threshold=0.01)
    y_ind = np.asarray(y)
    y_ind[y_ind == -1] = 0
    clf.fit(X, y_ind)
    centroid_encoded = clf.centroids_
    clf.fit(X, y)
    assert_array_equal(centroid_encoded, clf.centroids_) 
Example #16
Source File: test_nearest_centroid.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_pickle():
    import pickle

    # classification
    obj = NearestCentroid()
    obj.fit(iris.data, iris.target)
    score = obj.score(iris.data, iris.target)
    s = pickle.dumps(obj)

    obj2 = pickle.loads(s)
    assert_equal(type(obj2), obj.__class__)
    score2 = obj2.score(iris.data, iris.target)
    assert_array_equal(score, score2,
                       "Failed to generate same score"
                       " after pickling (classification).") 
Example #17
Source File: test_nearest_centroid.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_iris_shrinkage():
    # Check consistency on dataset iris, when using shrinkage.
    for metric in ('euclidean', 'cosine'):
        for shrink_threshold in [None, 0.1, 0.5]:
            clf = NearestCentroid(metric=metric,
                                  shrink_threshold=shrink_threshold)
            clf = clf.fit(iris.data, iris.target)
            score = np.mean(clf.predict(iris.data) == iris.target)
            assert score > 0.8, "Failed with score = " + str(score) 
Example #18
Source File: test_nearest_centroid.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_iris():
    # Check consistency on dataset iris.
    for metric in ('euclidean', 'cosine'):
        clf = NearestCentroid(metric=metric).fit(iris.data, iris.target)
        score = np.mean(clf.predict(iris.data) == iris.target)
        assert score > 0.9, "Failed with score = " + str(score) 
Example #19
Source File: test_nearest_centroid.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_precomputed():
    clf = NearestCentroid(metric='precomputed')
    with assert_raises(ValueError):
        clf.fit(X, y)