本文整理汇总了Python中sklearn.multiclass.OneVsRestClassifier方法的典型用法代码示例。如果您正苦于以下问题:Python multiclass.OneVsRestClassifier方法的具体用法?Python multiclass.OneVsRestClassifier怎么用?Python multiclass.OneVsRestClassifier使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.multiclass
的用法示例。
在下文中一共展示了multiclass.OneVsRestClassifier方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_ovr_fit_predict
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_ovr_fit_predict():
# A classifier which implements decision_function.
ovr = OneVsRestClassifier(LinearSVC(random_state=0))
pred = ovr.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ovr.estimators_), n_classes)
clf = LinearSVC(random_state=0)
pred2 = clf.fit(iris.data, iris.target).predict(iris.data)
assert_equal(np.mean(iris.target == pred), np.mean(iris.target == pred2))
# A classifier which implements predict_proba.
ovr = OneVsRestClassifier(MultinomialNB())
pred = ovr.fit(iris.data, iris.target).predict(iris.data)
assert_greater(np.mean(iris.target == pred), 0.65)
# 0.23. warning about tol not having its correct default value.
示例2: test_ovr_ovo_regressor
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_ovr_ovo_regressor():
# test that ovr and ovo work on regressors which don't have a decision_
# function
ovr = OneVsRestClassifier(DecisionTreeRegressor())
pred = ovr.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ovr.estimators_), n_classes)
assert_array_equal(np.unique(pred), [0, 1, 2])
# we are doing something sensible
assert_greater(np.mean(pred == iris.target), .9)
ovr = OneVsOneClassifier(DecisionTreeRegressor())
pred = ovr.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ovr.estimators_), n_classes * (n_classes - 1) / 2)
assert_array_equal(np.unique(pred), [0, 1, 2])
# we are doing something sensible
assert_greater(np.mean(pred == iris.target), .9)
示例3: test_ovr_multiclass
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_ovr_multiclass():
# Toy dataset where features correspond directly to labels.
X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]])
y = ["eggs", "spam", "ham", "eggs", "ham"]
Y = np.array([[0, 0, 1],
[0, 1, 0],
[1, 0, 0],
[0, 0, 1],
[1, 0, 0]])
classes = set("ham eggs spam".split())
for base_clf in (MultinomialNB(), LinearSVC(random_state=0),
LinearRegression(), Ridge(),
ElasticNet()):
clf = OneVsRestClassifier(base_clf).fit(X, y)
assert_equal(set(clf.classes_), classes)
y_pred = clf.predict(np.array([[0, 0, 4]]))[0]
assert_array_equal(y_pred, ["eggs"])
# test input as label indicator matrix
clf = OneVsRestClassifier(base_clf).fit(X, Y)
y_pred = clf.predict([[0, 0, 4]])[0]
assert_array_equal(y_pred, [0, 0, 1])
示例4: test_ovr_multilabel
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_ovr_multilabel():
# Toy dataset where features correspond directly to labels.
X = np.array([[0, 4, 5], [0, 5, 0], [3, 3, 3], [4, 0, 6], [6, 0, 0]])
y = np.array([[0, 1, 1],
[0, 1, 0],
[1, 1, 1],
[1, 0, 1],
[1, 0, 0]])
for base_clf in (MultinomialNB(), LinearSVC(random_state=0),
LinearRegression(), Ridge(),
ElasticNet(), Lasso(alpha=0.5)):
clf = OneVsRestClassifier(base_clf).fit(X, y)
y_pred = clf.predict([[0, 4, 4]])[0]
assert_array_equal(y_pred, [0, 1, 1])
assert clf.multilabel_
示例5: test_ovr_multilabel_dataset
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_ovr_multilabel_dataset():
base_clf = MultinomialNB(alpha=1)
for au, prec, recall in zip((True, False), (0.51, 0.66), (0.51, 0.80)):
X, Y = datasets.make_multilabel_classification(n_samples=100,
n_features=20,
n_classes=5,
n_labels=2,
length=50,
allow_unlabeled=au,
random_state=0)
X_train, Y_train = X[:80], Y[:80]
X_test, Y_test = X[80:], Y[80:]
clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train)
Y_pred = clf.predict(X_test)
assert clf.multilabel_
assert_almost_equal(precision_score(Y_test, Y_pred, average="micro"),
prec,
decimal=2)
assert_almost_equal(recall_score(Y_test, Y_pred, average="micro"),
recall,
decimal=2)
示例6: test_ovr_single_label_predict_proba
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_ovr_single_label_predict_proba():
base_clf = MultinomialNB(alpha=1)
X, Y = iris.data, iris.target
X_train, Y_train = X[:80], Y[:80]
X_test = X[80:]
clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train)
# Decision function only estimator.
decision_only = OneVsRestClassifier(svm.SVR(gamma='scale')
).fit(X_train, Y_train)
assert not hasattr(decision_only, 'predict_proba')
Y_pred = clf.predict(X_test)
Y_proba = clf.predict_proba(X_test)
assert_almost_equal(Y_proba.sum(axis=1), 1.0)
# predict assigns a label if the probability that the
# sample has the label is greater than 0.5.
pred = np.array([l.argmax() for l in Y_proba])
assert not (pred - Y_pred).any()
示例7: test_multiclass_multioutput_estimator
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_multiclass_multioutput_estimator():
# test to check meta of meta estimators
svc = LinearSVC(random_state=0)
multi_class_svc = OneVsRestClassifier(svc)
multi_target_svc = MultiOutputClassifier(multi_class_svc)
multi_target_svc.fit(X, y)
predictions = multi_target_svc.predict(X)
assert_equal((n_samples, n_outputs), predictions.shape)
# train the forest with each column and assert that predictions are equal
for i in range(3):
multi_class_svc_ = clone(multi_class_svc) # create a clone
multi_class_svc_.fit(X, y[:, i])
assert_equal(list(multi_class_svc_.predict(X)),
list(predictions[:, i]))
示例8: test_classifier_chain_vs_independent_models
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_classifier_chain_vs_independent_models():
# Verify that an ensemble of classifier chains (each of length
# N) can achieve a higher Jaccard similarity score than N independent
# models
X, Y = generate_multilabel_dataset_with_correlations()
X_train = X[:600, :]
X_test = X[600:, :]
Y_train = Y[:600, :]
Y_test = Y[600:, :]
ovr = OneVsRestClassifier(LogisticRegression())
ovr.fit(X_train, Y_train)
Y_pred_ovr = ovr.predict(X_test)
chain = ClassifierChain(LogisticRegression())
chain.fit(X_train, Y_train)
Y_pred_chain = chain.predict(X_test)
assert_greater(jaccard_score(Y_test, Y_pred_chain, average='samples'),
jaccard_score(Y_test, Y_pred_ovr, average='samples'))
示例9: test_thresholded_scorers_multilabel_indicator_data
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_thresholded_scorers_multilabel_indicator_data():
# Test that the scorer work with multilabel-indicator format
# for multilabel and multi-output multi-class classifier
X, y = make_multilabel_classification(allow_unlabeled=False,
random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# Multi-output multi-class predict_proba
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_proba = clf.predict_proba(X_test)
score1 = get_scorer('roc_auc')(clf, X_test, y_test)
score2 = roc_auc_score(y_test, np.vstack([p[:, -1] for p in y_proba]).T)
assert_almost_equal(score1, score2)
# Multi-output multi-class decision_function
# TODO Is there any yet?
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
clf._predict_proba = clf.predict_proba
clf.predict_proba = None
clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)]
y_proba = clf.decision_function(X_test)
score1 = get_scorer('roc_auc')(clf, X_test, y_test)
score2 = roc_auc_score(y_test, np.vstack([p for p in y_proba]).T)
assert_almost_equal(score1, score2)
# Multilabel predict_proba
clf = OneVsRestClassifier(DecisionTreeClassifier())
clf.fit(X_train, y_train)
score1 = get_scorer('roc_auc')(clf, X_test, y_test)
score2 = roc_auc_score(y_test, clf.predict_proba(X_test))
assert_almost_equal(score1, score2)
# Multilabel decision function
clf = OneVsRestClassifier(LinearSVC(random_state=0))
clf.fit(X_train, y_train)
score1 = get_scorer('roc_auc')(clf, X_test, y_test)
score2 = roc_auc_score(y_test, clf.decision_function(X_test))
assert_almost_equal(score1, score2)
示例10: train_expert
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def train_expert(history_context, history_action):
n_round = len(history_context)
history_context = np.array([history_context[t] for t in range(n_round)])
history_action = np.array([history_action[t] for t in range(n_round)])
logreg = OneVsRestClassifier(LogisticRegression())
mnb = OneVsRestClassifier(MultinomialNB())
logreg.fit(history_context, history_action)
mnb.fit(history_context, history_action)
return [logreg, mnb]
示例11: train_expert
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def train_expert(action_context):
logreg = OneVsRestClassifier(LogisticRegression())
mnb = OneVsRestClassifier(MultinomialNB(), )
logreg.fit(action_context.iloc[:, 2:], action_context.iloc[:, 1])
mnb.fit(action_context.iloc[:, 2:], action_context.iloc[:, 1])
return [logreg, mnb]
示例12: _one_vs_rest
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def _one_vs_rest(self,X,Y):
self.cls = OneVsRestClassifier(KOMD(**self.get_params())).fit(X,Y)
self.is_fitted = True
return self
示例13: __init__
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def __init__(self, *args, **kwargs):
self.model = sklearn.svm.SVC(*args, **kwargs)
if self.model.decision_function_shape == 'ovr':
self.decision_function_shape = 'ovr'
# sklearn's ovr isn't real ovr
self.model = OneVsRestClassifier(self.model)
示例14: train_one_vs_rest_SVM
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def train_one_vs_rest_SVM(path_boxes_np,CAE_model_path,K,args):
data=extract_features(path_boxes_np,CAE_model_path,args)
print('feature extraction finish!')
# clusters, the data to be clustered by Kmeans
# clusters=KMeans(n_clusters=K,init='k-means++',n_init=10,algorithm='full',max_iter=300).fit(data)
centers=kmeans(data,num_centers=K,initialization='PLUSPLUS',num_repetitions=10,
max_num_comparisons=100,max_num_iterations=100,algorithm='LLOYD',num_trees=3)
labels=kmeans_quantize(data,centers)
# to get the sparse matrix of labels
sparse_labels=np.eye(K)[labels]
sparse_labels=(sparse_labels-0.5)*2
# nums=np.zeros(10,dtype=int)
# for item in clusters.labels_:
# nums[item]+=1
# print(nums)
print('clustering finished!')
# SGDC classifier with onevsrest classifier to replace the ovc-svm with hinge loss and SDCA optimizer in the paper
base_estimizer=SGDClassifier(max_iter=10000,warm_start=True,loss='hinge',early_stopping=True,n_iter_no_change=50,l1_ratio=0)
ovr_classifer=OneVsRestClassifier(base_estimizer)
#clf=svm.LinearSVC(C=1.0,multi_class='ovr',max_iter=len(labels)*5,loss='hinge',)
ovr_classifer.fit(data,sparse_labels)
joblib.dump(ovr_classifer,svm_save_dir+args.dataset+'.m')
print('train finished!')
示例15: test_multilabel
# 需要导入模块: from sklearn import multiclass [as 别名]
# 或者: from sklearn.multiclass import OneVsRestClassifier [as 别名]
def test_multilabel():
"""Check if error is raised for multilabel classification."""
X, y = make_multilabel_classification(n_classes=2, n_labels=1,
allow_unlabeled=False,
random_state=123)
clf = OneVsRestClassifier(SVC(kernel='linear'))
eclf = VotingClassifier(estimators=[('ovr', clf)], voting='hard')
try:
eclf.fit(X, y)
except NotImplementedError:
return