本文整理汇总了Python中sklearn.neighbors.NearestCentroid.predict方法的典型用法代码示例。如果您正苦于以下问题:Python NearestCentroid.predict方法的具体用法?Python NearestCentroid.predict怎么用?Python NearestCentroid.predict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.neighbors.NearestCentroid
的用法示例。
在下文中一共展示了NearestCentroid.predict方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_classification_toy
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
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)
示例2: test_predict_translated_data
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
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)
示例3: nearest_centroid_classifier
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
def nearest_centroid_classifier(X_train, categories, X_test, test_categories):
from sklearn.neighbors import NearestCentroid
clf = NearestCentroid().fit(X_train, categories)
y_roccio_predicted = clf.predict(X_test)
print "\n Here is the classification report for NearestCentroid classifier:"
print metrics.classification_report(test_categories, y_roccio_predicted)
to_latex(test_categories, y_roccio_predicted)
示例4: NC
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
def NC(data_train, data_train_vectors, data_test_vectors, **kwargs):
# Implementing classification model- using NearestCentroid
clf_nc = NearestCentroid()
clf_nc.fit(data_train_vectors, data_train.target)
y_pred = clf_nc.predict(data_test_vectors)
return y_pred
示例5: nearestNeighbour
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
def nearestNeighbour():
import numpy as np
import pylab as pl
from matplotlib.colors import ListedColormap
from sklearn import datasets
from sklearn.neighbors import NearestCentroid
n_neighbors = 15
# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features. We could
# avoid this ugly slicing by using a two-dim dataset
y = iris.target
h = .02 # step size in the mesh
# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
for shrinkage in [None, 0.1]:
# we create an instance of Neighbours Classifier and fit the data.
clf = NearestCentroid(shrink_threshold=shrinkage)
clf.fit(X, y)
y_pred = clf.predict(X)
print shrinkage, np.mean(y == y_pred)
# Plot the decision boundary. For that, we will asign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
pl.figure()
pl.pcolormesh(xx, yy, Z, cmap=cmap_light)
# Plot also the training points
pl.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
pl.title("3-Class classification (shrink_threshold=%r)"
% shrinkage)
pl.axis('tight')
示例6: test_iris_shrinkage
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
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)
示例7: BinBasedCluster
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
class BinBasedCluster(BaseEstimator):
def __init__(self, bins=[0, 0.5, 1] + range(5, 36)):
self.bins = bins
def fit(self, X, y):
biny = self.bin_data(y)
self.pred = NearestCentroid().fit(X, biny)
return self
def predict(self, X):
return self.pred.predict(X)
def score(self, X, y, is_raw=True):
clusters = self.pred.predict(X)
if is_raw:
return adjusted_rand_score(self.bin_data(y), clusters)
else:
return adjusted_rand_score(y, clusters)
def bin_data(self, y):
return np.digitize(y, self.bins)
def make_vern_points(self, X, y):
sel = SelectKBest(score_func=normalized_mutual_info_score_scorefunc)
sdata = sel.fit_transform(X, y)
print X.shape, sdata.shape
pca = PCA(n_components=2)
pca_trans = pca.fit_transform(sdata)
biny = self.bin_data(y)
pred = NearestCentroid().fit(pca_trans, biny)
x_min, x_max = pca_trans[:, 0].min() - 1, pca_trans[:, 0].max() + 1
y_min, y_max = pca_trans[:, 1].min() - 1, pca_trans[:, 1].max() + 1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 50), np.linspace(y_min, y_max, 50))
Z = pred.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
return pca_trans, biny, xx, yy, Z
示例8: nearest_centroid_classifier
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
def nearest_centroid_classifier(X_train, X_test, y_train, y_test):
from sklearn.neighbors import NearestCentroid
clf = NearestCentroid().fit(X_train, y_train)
evaluate_cross_validation(clf,X_train, y_train, 5)
y_roccio_predicted = clf.predict(X_test)
print "\n Here is the classification report for NearestCentroid classifier:"
print metrics.classification_report(y_test, y_roccio_predicted)
示例9: NCClassifier
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
class NCClassifier(Classifier):
"""Rocchio classifier"""
def __init__(self, shrink=None):
self.cl = NearestCentroid(shrink_threshold=shrink)
self.shrink = shrink
def retrain(self, vectorFeature, vectorTarget):
if self.shrink != None:
self.cl.fit([v.toarray()[0] for v in vectorFeature], vectorTarget)
else:
super(NCClassifier, self).retrain(vectorFeature, vectorTarget)
def classify(self, vectorizedTest):
if self.shrink != None:
return self.cl.predict(vectorizedTest.toarray()[0])[0]
else:
return super(NCClassifier, self).classify(vectorizedTest)
示例10: make_vern_points
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
def make_vern_points(self, X, y):
sel = SelectKBest(score_func=normalized_mutual_info_score_scorefunc)
sdata = sel.fit_transform(X, y)
print X.shape, sdata.shape
pca = PCA(n_components=2)
pca_trans = pca.fit_transform(sdata)
biny = self.bin_data(y)
pred = NearestCentroid().fit(pca_trans, biny)
x_min, x_max = pca_trans[:, 0].min() - 1, pca_trans[:, 0].max() + 1
y_min, y_max = pca_trans[:, 1].min() - 1, pca_trans[:, 1].max() + 1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 50), np.linspace(y_min, y_max, 50))
Z = pred.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
return pca_trans, biny, xx, yy, Z
示例11: test_iris
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
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)
示例12: test_precomputed
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
def test_precomputed():
clf = NearestCentroid(metric="precomputed")
clf.fit(X, y)
S = pairwise_distances(T, clf.centroids_)
assert_array_equal(clf.predict(S), true_result)
示例13: NearestCentroid
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
# Nearest Centroid
from sklearn import datasets
from sklearn import metrics
from sklearn.neighbors import NearestCentroid
# load the iris datasets
dataset = datasets.load_iris()
# fit a nearest centroid model to the data
model = NearestCentroid()
model.fit(dataset.data, dataset.target)
print(model)
# make predictions
expected = dataset.target
predicted = model.predict(dataset.data)
# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
示例14: range
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
y_test = labels[272:,i]
else:
X_train = training
y_train = labels[:172,i]
X_test = sampletest
y_test = labels[172:,i]
posterior = np.empty([100,72,6])
box = np.zeros([6,6])
for j in range(4,5):
for k in range(1,2):
accuracy = np.zeros(100)
for m in range(0,100):
ncc = NearestCentroid()
ncc.fit(X_train, y_train)
y_pred = ncc.predict(X_test)
n=0
for i in range(0,len(y_pred)):
if y_pred[i] == y_test[i]:
#print i, y_pred[i], y_test[i]
n = n+1
accuracy[m] = accuracy[m]+1
box[y_test[i]-1,y_pred[i]-1] = box[y_test[i]-1,y_pred[i]-1] + 1
#posterior[m] = knc.predict_proba(X_test)
print j, k, np.mean(accuracy)/0.72, np.std(accuracy)/0.72
#print 30, 20, sum(accuracy[0:8])/8.0, sum(accuracy[8:18])/10.0, sum(accuracy[18:30])/12.0, sum(accuracy[56:72])/16.0, sum(accuracy[30:43])/13.0, sum(accuracy[43:56])/13.0, sum(accuracy)/72.0
'''
means = np.empty([72,6])
stds = np.empty([72,6])
grid = np.empty([6,6])
示例15: writeToDisk
# 需要导入模块: from sklearn.neighbors import NearestCentroid [as 别名]
# 或者: from sklearn.neighbors.NearestCentroid import predict [as 别名]
clf5=RandomForestClassifier(n_estimators=100) #RandomForest Classifier
clf5.fit(X_train, y_train)
pred = clf5.predict(X_test)
writeToDisk(pred,"RandomForestClassifier")
clf6=Pipeline([('feature_selection', #LinearSVC with L2-based feature selection
LinearSVC(penalty="l2", dual=False, tol=1e-3)),
('classification', LinearSVC())])
clf6.fit(X_train, y_train)
pred = clf6.predict(X_test)
writeToDisk(pred,"LinearSVC")
clf7=NearestCentroid() #NearestCentroid (aka Rocchio classifier), no threshold
clf7.fit(X_train, y_train)
pred = clf7.predict(X_test)
writeToDisk(pred,"NearestCentroid")
clf8=SVC(C=1.0, class_weight=None, coef0=0.0, #SVC
decision_function_shape=None, degree=3, gamma='auto', kernel='linear',
max_iter=-1, probability=False, random_state=1, shrinking=True,
tol=0.001, verbose=False)
clf8.fit(X_train, y_train)
pred = clf8.predict(X_test)
writeToDisk(pred,"SVC")
'''
clf9=VotingClassifier(estimators=[
('Ridge',clf1),('MultiNB',clf2),('BernNB',clf3),('KNN',clf4),
('RF',clf5),('LinearSVC',clf6),('NearC',clf7),('SVC',clf8)
],voting='soft')