本文整理汇总了Python中sklearn.base.ClassifierMixin方法的典型用法代码示例。如果您正苦于以下问题:Python base.ClassifierMixin方法的具体用法?Python base.ClassifierMixin怎么用?Python base.ClassifierMixin使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.base
的用法示例。
在下文中一共展示了base.ClassifierMixin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_base_chain_fit_and_predict
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def test_base_chain_fit_and_predict():
# Fit base chain and verify predict performance
X, Y = generate_multilabel_dataset_with_correlations()
chains = [RegressorChain(Ridge()),
ClassifierChain(LogisticRegression())]
for chain in chains:
chain.fit(X, Y)
Y_pred = chain.predict(X)
assert_equal(Y_pred.shape, Y.shape)
assert_equal([c.coef_.size for c in chain.estimators_],
list(range(X.shape[1], X.shape[1] + Y.shape[1])))
Y_prob = chains[1].predict_proba(X)
Y_binary = (Y_prob >= .5)
assert_array_equal(Y_binary, Y_pred)
assert isinstance(chains[1], ClassifierMixin)
示例2: __init__
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def __init__(self, classifier=None, predictors="all"):
"""Create an instance of the MissingnessClassifier.
The MissingnessClassifier inherits from sklearn BaseEstimator and
ClassifierMixin. This inheritence and this class' implementation
ensure that the MissingnessClassifier is a valid classifier that will
work in an sklearn pipeline.
Args:
classifier (classifier, optional): valid classifier from sklearn.
If None, default is xgboost. Note that classifier must
conform to sklearn style. This means it must implement the
`predict_proba` method and act as a porper classifier.
predictors (str, iter, dict, optiona): defaults to all, i.e.
use all predictors. If all, every column will be used for
every class prediction. If a list, subset of columns used for
all predictions. If a dict, specify which columns to use as
predictors for each imputation. Columns not specified in dict
will receive `all` by default.
"""
self.classifier = classifier
self.predictors = predictors
示例3: test_template_1
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def test_template_1():
"""Assert that TPOT template option generates pipeline when each step is a type of operator."""
tpot_obj = TPOTClassifier(
random_state=42,
verbosity=0,
template='Selector-Transformer-Classifier'
)
tpot_obj._fit_init()
pop = tpot_obj._toolbox.population(n=10)
for deap_pipeline in pop:
operator_count = tpot_obj._operator_count(deap_pipeline)
sklearn_pipeline = tpot_obj._toolbox.compile(expr=deap_pipeline)
assert operator_count == 3
assert issubclass(sklearn_pipeline.steps[0][1].__class__, SelectorMixin)
assert issubclass(sklearn_pipeline.steps[1][1].__class__, TransformerMixin)
assert issubclass(sklearn_pipeline.steps[2][1].__class__, ClassifierMixin)
示例4: test_template_2
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def test_template_2():
"""Assert that TPOT template option generates pipeline when each step is operator type with a duplicate main type."""
tpot_obj = TPOTClassifier(
random_state=42,
verbosity=0,
template='Selector-Selector-Transformer-Classifier'
)
tpot_obj._fit_init()
pop = tpot_obj._toolbox.population(n=10)
for deap_pipeline in pop:
operator_count = tpot_obj._operator_count(deap_pipeline)
sklearn_pipeline = tpot_obj._toolbox.compile(expr=deap_pipeline)
assert operator_count == 4
assert issubclass(sklearn_pipeline.steps[0][1].__class__, SelectorMixin)
assert issubclass(sklearn_pipeline.steps[1][1].__class__, SelectorMixin)
assert issubclass(sklearn_pipeline.steps[2][1].__class__, TransformerMixin)
assert issubclass(sklearn_pipeline.steps[3][1].__class__, ClassifierMixin)
示例5: test_template_3
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def test_template_3():
"""Assert that TPOT template option generates pipeline when one of steps is a specific operator."""
tpot_obj = TPOTClassifier(
random_state=42,
verbosity=0,
template='SelectPercentile-Transformer-Classifier'
)
tpot_obj._fit_init()
pop = tpot_obj._toolbox.population(n=10)
for deap_pipeline in pop:
operator_count = tpot_obj._operator_count(deap_pipeline)
sklearn_pipeline = tpot_obj._toolbox.compile(expr=deap_pipeline)
assert operator_count == 3
assert sklearn_pipeline.steps[0][0] == 'SelectPercentile'.lower()
assert issubclass(sklearn_pipeline.steps[0][1].__class__, SelectorMixin)
assert issubclass(sklearn_pipeline.steps[1][1].__class__, TransformerMixin)
assert issubclass(sklearn_pipeline.steps[2][1].__class__, ClassifierMixin)
示例6: test_template_4
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def test_template_4():
"""Assert that TPOT template option generates pipeline when one of steps is a specific operator."""
tpot_obj = TPOTClassifier(
population_size=5,
generations=2,
random_state=42,
verbosity=0,
config_dict = 'TPOT light',
template='SelectPercentile-Transformer-Classifier'
)
tpot_obj.fit(pretest_X, pretest_y)
assert isinstance(tpot_obj._optimized_pipeline, creator.Individual)
assert not (tpot_obj._start_datetime is None)
sklearn_pipeline = tpot_obj.fitted_pipeline_
operator_count = tpot_obj._operator_count(tpot_obj._optimized_pipeline)
assert operator_count == 3
assert sklearn_pipeline.steps[0][0] == 'SelectPercentile'.lower()
assert issubclass(sklearn_pipeline.steps[0][1].__class__, SelectorMixin)
assert issubclass(sklearn_pipeline.steps[1][1].__class__, TransformerMixin)
assert issubclass(sklearn_pipeline.steps[2][1].__class__, ClassifierMixin)
示例7: _get_child_predict
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def _get_child_predict(self, clf, X, index=None):
if self.stack_by_proba and hasattr(clf, 'predict_proba'):
if self.save_stage0 and index is not None:
proba = util.saving_predict_proba(clf, X, index)
else:
proba = clf.predict_proba(X)
return proba[:, 1:]
elif hasattr(clf, 'predict'):
predict_result = clf.predict(X)
if isinstance(clf, ClassifierMixin):
lb = LabelBinarizer()
lb.fit(predict_result)
return lb.fit_transform(predict_result)
else:
return predict_result.reshape((predict_result.size, 1))
else:
return clf.fit_transform(X)
示例8: test_classifier_chain_fit_and_predict_with_logistic_regression
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def test_classifier_chain_fit_and_predict_with_logistic_regression():
# Fit classifier chain and verify predict performance
X, Y = generate_multilabel_dataset_with_correlations()
classifier_chain = ClassifierChain(LogisticRegression())
classifier_chain.fit(X, Y)
Y_pred = classifier_chain.predict(X)
assert_equal(Y_pred.shape, Y.shape)
Y_prob = classifier_chain.predict_proba(X)
Y_binary = (Y_prob >= .5)
assert_array_equal(Y_binary, Y_pred)
assert_equal([c.coef_.size for c in classifier_chain.estimators_],
list(range(X.shape[1], X.shape[1] + Y.shape[1])))
assert isinstance(classifier_chain, ClassifierMixin)
示例9: test_sample_weight
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def test_sample_weight():
"""Tests sample_weight parameter of VotingClassifier"""
clf1 = LogisticRegression(random_state=123)
clf2 = RandomForestClassifier(random_state=123)
clf3 = SVC(gamma='scale', probability=True, random_state=123)
eclf1 = VotingClassifier(estimators=[
('lr', clf1), ('rf', clf2), ('svc', clf3)],
voting='soft').fit(X, y, sample_weight=np.ones((len(y),)))
eclf2 = VotingClassifier(estimators=[
('lr', clf1), ('rf', clf2), ('svc', clf3)],
voting='soft').fit(X, y)
assert_array_equal(eclf1.predict(X), eclf2.predict(X))
assert_array_almost_equal(eclf1.predict_proba(X), eclf2.predict_proba(X))
sample_weight = np.random.RandomState(123).uniform(size=(len(y),))
eclf3 = VotingClassifier(estimators=[('lr', clf1)], voting='soft')
eclf3.fit(X, y, sample_weight)
clf1.fit(X, y, sample_weight)
assert_array_equal(eclf3.predict(X), clf1.predict(X))
assert_array_almost_equal(eclf3.predict_proba(X), clf1.predict_proba(X))
# check that an error is raised and indicative if sample_weight is not
# supported.
clf4 = KNeighborsClassifier()
eclf3 = VotingClassifier(estimators=[
('lr', clf1), ('svc', clf3), ('knn', clf4)],
voting='soft')
msg = ('Underlying estimator KNeighborsClassifier does not support '
'sample weights.')
with pytest.raises(ValueError, match=msg):
eclf3.fit(X, y, sample_weight)
# check that _parallel_fit_estimator will raise the right error
# it should raise the original error if this is not linked to sample_weight
class ClassifierErrorFit(BaseEstimator, ClassifierMixin):
def fit(self, X, y, sample_weight):
raise TypeError('Error unrelated to sample_weight.')
clf = ClassifierErrorFit()
with pytest.raises(TypeError, match='Error unrelated to sample_weight'):
clf.fit(X, y, sample_weight=sample_weight)
示例10: test_sample_weight_kwargs
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def test_sample_weight_kwargs():
"""Check that VotingClassifier passes sample_weight as kwargs"""
class MockClassifier(BaseEstimator, ClassifierMixin):
"""Mock Classifier to check that sample_weight is received as kwargs"""
def fit(self, X, y, *args, **sample_weight):
assert 'sample_weight' in sample_weight
clf = MockClassifier()
eclf = VotingClassifier(estimators=[('mock', clf)], voting='soft')
# Should not raise an error.
eclf.fit(X, y, sample_weight=np.ones((len(y),)))
示例11: _generate_bases_test
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def _generate_bases_test(est, pd_est):
def test(self):
self.assertTrue(isinstance(pd_est, FrameMixin), pd_est)
self.assertFalse(isinstance(est, FrameMixin))
self.assertTrue(isinstance(pd_est, base.BaseEstimator))
try:
mixins = [
base.ClassifierMixin,
base.ClusterMixin,
base.BiclusterMixin,
base.TransformerMixin,
base.DensityMixin,
base.MetaEstimatorMixin,
base.ClassifierMixin,
base.RegressorMixin]
except:
if _sklearn_ver > 17:
raise
mixins = [
base.ClassifierMixin,
base.ClusterMixin,
base.BiclusterMixin,
base.TransformerMixin,
base.MetaEstimatorMixin,
base.ClassifierMixin,
base.RegressorMixin]
for mixin in mixins:
self.assertEqual(
isinstance(pd_est, mixin),
isinstance(est, mixin),
mixin)
return test
示例12: _exposed_methods_mapping
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def _exposed_methods_mapping(self) -> Dict[str, str]:
ret = {
'predict': 'predict'
}
if isinstance(self.model, ClassifierMixin):
ret['predict_proba'] = 'predict_proba'
return ret
示例13: transform
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def transform(self, X):
X = check_array(X)
X_transformed = np.copy(X)
# add class probabilities as a synthetic feature
if issubclass(self.estimator.__class__, ClassifierMixin) and hasattr(self.estimator, 'predict_proba'):
X_transformed = np.hstack((self.estimator.predict_proba(X), X))
# add class prodiction as a synthetic feature
X_transformed = np.hstack((np.reshape(self.estimator.predict(X), (-1, 1)), X_transformed))
return X_transformed
示例14: transform
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def transform(self, X):
"""Transform data by adding two synthetic feature(s).
Parameters
----------
X: numpy ndarray, {n_samples, n_components}
New data, where n_samples is the number of samples and n_components is the number of components.
Returns
-------
X_transformed: array-like, shape (n_samples, n_features + 1) or (n_samples, n_features + 1 + n_classes) for classifier with predict_proba attribute
The transformed feature set.
"""
X = check_array(X)
X_transformed = np.copy(X)
# add class probabilities as a synthetic feature
if issubclass(self.estimator.__class__, ClassifierMixin) and hasattr(self.estimator, 'predict_proba'):
y_pred_proba = self.estimator.predict_proba(X)
# check all values that should be not infinity or not NAN
if np.all(np.isfinite(y_pred_proba)):
X_transformed = np.hstack((y_pred_proba, X))
# add class prediction as a synthetic feature
X_transformed = np.hstack((np.reshape(self.estimator.predict(X), (-1, 1)), X_transformed))
return X_transformed
示例15: score
# 需要导入模块: from sklearn import base [as 别名]
# 或者: from sklearn.base import ClassifierMixin [as 别名]
def score(self, X, y):
"""Force use of accuracy score since we don't inherit
from ClassifierMixin"""
from sklearn.metrics import accuracy_score
return accuracy_score(y, self.predict(X))