本文整理汇总了Python中sklearn.utils.testing.assert_raises_regex函数的典型用法代码示例。如果您正苦于以下问题:Python assert_raises_regex函数的具体用法?Python assert_raises_regex怎么用?Python assert_raises_regex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了assert_raises_regex函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_graphviz_errors
def test_graphviz_errors():
# Check for errors of export_graphviz
clf = DecisionTreeClassifier(max_depth=3, min_samples_split=2)
# Check not-fitted decision tree error
out = StringIO()
assert_raises(NotFittedError, export_graphviz, clf, out)
clf.fit(X, y)
# Check if it errors when length of feature_names
# mismatches with number of features
message = ("Length of feature_names, "
"1 does not match number of features, 2")
assert_raise_message(ValueError, message, export_graphviz, clf, None,
feature_names=["a"])
message = ("Length of feature_names, "
"3 does not match number of features, 2")
assert_raise_message(ValueError, message, export_graphviz, clf, None,
feature_names=["a", "b", "c"])
# Check class_names error
out = StringIO()
assert_raises(IndexError, export_graphviz, clf, out, class_names=[])
# Check precision error
out = StringIO()
assert_raises_regex(ValueError, "should be greater or equal",
export_graphviz, clf, out, precision=-1)
assert_raises_regex(ValueError, "should be an integer",
export_graphviz, clf, out, precision="1")
开发者ID:Lavanya-Basavaraju,项目名称:scikit-learn,代码行数:32,代码来源:test_export.py
示例2: test_one_hot_encoder_specified_categories
def test_one_hot_encoder_specified_categories():
X = np.array([['a', 'b']], dtype=object).T
enc = OneHotEncoder(categories=[['a', 'b', 'c']])
exp = np.array([[1., 0., 0.],
[0., 1., 0.]])
assert_array_equal(enc.fit_transform(X).toarray(), exp)
assert enc.categories[0] == ['a', 'b', 'c']
assert enc.categories_[0].tolist() == ['a', 'b', 'c']
assert np.issubdtype(enc.categories_[0].dtype, np.str_)
# unsorted passed categories raises for now
enc = OneHotEncoder(categories=[['c', 'b', 'a']])
msg = re.escape('Unsorted categories are not yet supported')
assert_raises_regex(ValueError, msg, enc.fit_transform, X)
# multiple columns
X = np.array([['a', 'b'], [0, 2]], dtype=object).T
enc = OneHotEncoder(categories=[['a', 'b', 'c'], [0, 1, 2]])
exp = np.array([[1., 0., 0., 1., 0., 0.],
[0., 1., 0., 0., 0., 1.]])
assert_array_equal(enc.fit_transform(X).toarray(), exp)
assert enc.categories_[0].tolist() == ['a', 'b', 'c']
assert np.issubdtype(enc.categories_[0].dtype, np.str_)
assert enc.categories_[1].tolist() == [0, 1, 2]
assert np.issubdtype(enc.categories_[1].dtype, np.integer)
# when specifying categories manually, unknown categories should already
# raise when fitting
X = np.array([['a', 'b', 'c']]).T
enc = OneHotEncoder(categories=[['a', 'b']])
assert_raises(ValueError, enc.fit, X)
enc = OneHotEncoder(categories=[['a', 'b']], handle_unknown='ignore')
exp = np.array([[1., 0.], [0., 1.], [0., 0.]])
assert_array_equal(enc.fit(X).transform(X).toarray(), exp)
开发者ID:gab3s,项目名称:scikit-learn,代码行数:35,代码来源:test_encoders.py
示例3: test_fit_predict_on_pipeline_without_fit_predict
def test_fit_predict_on_pipeline_without_fit_predict():
# tests that a pipeline does not have fit_predict method when final
# step of pipeline does not have fit_predict defined
scaler = StandardScaler()
pca = PCA(svd_solver="full")
pipe = Pipeline([("scaler", scaler), ("pca", pca)])
assert_raises_regex(AttributeError, "'PCA' object has no attribute 'fit_predict'", getattr, pipe, "fit_predict")
开发者ID:cheral,项目名称:scikit-learn,代码行数:7,代码来源:test_pipeline.py
示例4: test_ridgecv_store_cv_values
def test_ridgecv_store_cv_values():
rng = np.random.RandomState(42)
n_samples = 8
n_features = 5
x = rng.randn(n_samples, n_features)
alphas = [1e-1, 1e0, 1e1]
n_alphas = len(alphas)
r = RidgeCV(alphas=alphas, cv=None, store_cv_values=True)
# with len(y.shape) == 1
y = rng.randn(n_samples)
r.fit(x, y)
assert r.cv_values_.shape == (n_samples, n_alphas)
# with len(y.shape) == 2
n_targets = 3
y = rng.randn(n_samples, n_targets)
r.fit(x, y)
assert r.cv_values_.shape == (n_samples, n_targets, n_alphas)
r = RidgeCV(cv=3, store_cv_values=True)
assert_raises_regex(ValueError, 'cv!=None and store_cv_values',
r.fit, x, y)
开发者ID:manhhomienbienthuy,项目名称:scikit-learn,代码行数:25,代码来源:test_ridge.py
示例5: test_one_hot_encoder_invalid_params
def test_one_hot_encoder_invalid_params():
enc = OneHotEncoder(drop='second')
assert_raises_regex(
ValueError,
"Wrong input for parameter `drop`.",
enc.fit, [["Male"], ["Female"]])
enc = OneHotEncoder(handle_unknown='ignore', drop='first')
assert_raises_regex(
ValueError,
"`handle_unknown` must be 'error'",
enc.fit, [["Male"], ["Female"]])
enc = OneHotEncoder(drop='first')
assert_raises_regex(
ValueError,
"The handling of integer data will change in version",
enc.fit, [[1], [2]])
enc = OneHotEncoder(drop='first', categories='auto')
assert_no_warnings(enc.fit_transform, [[1], [2]])
enc = OneHotEncoder(drop=np.asarray('b', dtype=object))
assert_raises_regex(
ValueError,
"Wrong input for parameter `drop`.",
enc.fit, [['abc', 2, 55], ['def', 1, 55], ['def', 3, 59]])
enc = OneHotEncoder(drop=['ghi', 3, 59])
assert_raises_regex(
ValueError,
"The following categories were supposed",
enc.fit, [['abc', 2, 55], ['def', 1, 55], ['def', 3, 59]])
开发者ID:manhhomienbienthuy,项目名称:scikit-learn,代码行数:33,代码来源:test_encoders.py
示例6: check_dtype_object
def check_dtype_object(name, Estimator):
# check that estimators treat dtype object as numeric if possible
rng = np.random.RandomState(0)
X = rng.rand(40, 10).astype(object)
y = (X[:, 0] * 4).astype(np.int)
y = multioutput_estimator_convert_y_2d(name, y)
with warnings.catch_warnings():
estimator = Estimator()
set_fast_parameters(estimator)
estimator.fit(X, y)
if hasattr(estimator, "predict"):
estimator.predict(X)
if hasattr(estimator, "transform"):
estimator.transform(X)
try:
estimator.fit(X, y.astype(object))
except Exception as e:
if "Unknown label type" not in str(e):
raise
X[0, 0] = {'foo': 'bar'}
msg = "argument must be a string or a number"
assert_raises_regex(TypeError, msg, estimator.fit, X, y)
开发者ID:AlexMarshall011,项目名称:scikit-learn,代码行数:26,代码来源:estimator_checks.py
示例7: test_one_hot_encoder_unsorted_categories
def test_one_hot_encoder_unsorted_categories():
X = np.array([['a', 'b']], dtype=object).T
# unsorted passed categories raises for now
enc = OneHotEncoder(categories=[['c', 'b', 'a']])
msg = re.escape('Unsorted categories are not yet supported')
assert_raises_regex(ValueError, msg, enc.fit_transform, X)
开发者ID:Th3Bakery,项目名称:scikit-learn,代码行数:7,代码来源:test_encoders.py
示例8: test_check_class_weight_balanced_linear_classifier
def test_check_class_weight_balanced_linear_classifier():
# check that ill-computed balanced weights raises an exception
assert_raises_regex(AssertionError,
"Classifier estimator_name is not computing"
" class_weight=balanced properly.",
check_class_weight_balanced_linear_classifier,
'estimator_name',
BadBalancedWeightsClassifier)
开发者ID:daniel-perry,项目名称:scikit-learn,代码行数:8,代码来源:test_estimator_checks.py
示例9: test_k_means_n_init
def test_k_means_n_init():
rnd = np.random.RandomState(0)
X = rnd.normal(size=(40, 2))
# two regression tests on bad n_init argument
# previous bug: n_init <= 0 threw non-informative TypeError (#3858)
assert_raises_regex(ValueError, "n_init", KMeans(n_init=0).fit, X)
assert_raises_regex(ValueError, "n_init", KMeans(n_init=-1).fit, X)
开发者ID:Lavanya-Basavaraju,项目名称:scikit-learn,代码行数:8,代码来源:test_k_means.py
示例10: test_bad_pyfunc_metric
def test_bad_pyfunc_metric():
def wrong_distance(x, y):
return "1"
X = np.ones((5, 2))
assert_raises_regex(TypeError,
"Custom distance function must accept two vectors",
BallTree, X, metric=wrong_distance)
开发者ID:amueller,项目名称:scikit-learn,代码行数:8,代码来源:test_dist_metrics.py
示例11: test_fit_predict_on_pipeline_without_fit_predict
def test_fit_predict_on_pipeline_without_fit_predict():
# tests that a pipeline does not have fit_predict method when final
# step of pipeline does not have fit_predict defined
scaler = StandardScaler()
pca = PCA()
pipe = Pipeline([('scaler', scaler), ('pca', pca)])
assert_raises_regex(AttributeError,
"'PCA' object has no attribute 'fit_predict'",
getattr, pipe, 'fit_predict')
开发者ID:Givonaldo,项目名称:scikit-learn,代码行数:9,代码来源:test_pipeline.py
示例12: test_gen_even_slices
def test_gen_even_slices():
# check that gen_even_slices contains all samples
some_range = range(10)
joined_range = list(chain(*[some_range[slice] for slice in gen_even_slices(10, 3)]))
assert_array_equal(some_range, joined_range)
# check that passing negative n_chunks raises an error
slices = gen_even_slices(10, -1)
assert_raises_regex(ValueError, "gen_even_slices got n_packs=-1, must be" " >=1", next, slices)
开发者ID:haadkhan,项目名称:cerebri,代码行数:9,代码来源:test_utils.py
示例13: test_precompute_invalid_argument
def test_precompute_invalid_argument():
X, y, _, _ = build_dataset()
for clf in [ElasticNetCV(precompute="invalid"), LassoCV(precompute="invalid")]:
assert_raises_regex(ValueError, ".*should be.*True.*False.*auto.*" "array-like.*Got 'invalid'", clf.fit, X, y)
# Precompute = 'auto' is not supported for ElasticNet
assert_raises_regex(
ValueError, ".*should be.*True.*False.*array-like.*" "Got 'auto'", ElasticNet(precompute="auto").fit, X, y
)
开发者ID:nelson-liu,项目名称:scikit-learn,代码行数:9,代码来源:test_coordinate_descent.py
示例14: test_check_estimators_unfitted
def test_check_estimators_unfitted():
# check that a ValueError/AttributeError is raised when calling predict
# on an unfitted estimator
msg = "AttributeError or ValueError not raised by predict"
assert_raises_regex(AssertionError, msg, check_estimators_unfitted, "estimator", NoSparseClassifier)
# check that CorrectNotFittedError inherit from either ValueError
# or AttributeError
check_estimators_unfitted("estimator", CorrectNotFittedErrorClassifier)
开发者ID:nelson-liu,项目名称:scikit-learn,代码行数:9,代码来源:test_estimator_checks.py
示例15: test_regression_metrics_at_limits
def test_regression_metrics_at_limits():
assert_almost_equal(mean_squared_error([0.], [0.]), 0.00, 2)
assert_almost_equal(mean_squared_log_error([0.], [0.]), 0.00, 2)
assert_almost_equal(mean_absolute_error([0.], [0.]), 0.00, 2)
assert_almost_equal(median_absolute_error([0.], [0.]), 0.00, 2)
assert_almost_equal(explained_variance_score([0.], [0.]), 1.00, 2)
assert_almost_equal(r2_score([0., 1], [0., 1]), 1.00, 2)
assert_raises_regex(ValueError, "Mean Squared Logarithmic Error cannot be "
"used when targets contain negative values.",
mean_squared_log_error, [-1.], [-1.])
开发者ID:IsaacHaze,项目名称:scikit-learn,代码行数:10,代码来源:test_regression.py
示例16: test__check_reg_targets_exception
def test__check_reg_targets_exception():
invalid_multioutput = 'this_value_is_not_valid'
expected_message = ("Allowed 'multioutput' string values are.+"
"You provided multioutput={!r}".format(
invalid_multioutput))
assert_raises_regex(ValueError, expected_message,
_check_reg_targets,
[1, 2, 3],
[[1], [2], [3]],
invalid_multioutput)
开发者ID:hmshan,项目名称:scikit-learn,代码行数:10,代码来源:test_regression.py
示例17: test_check_classification_targets
def test_check_classification_targets():
for y_type in EXAMPLES.keys():
if y_type in ["unknown", "continuous", 'continuous-multioutput']:
for example in EXAMPLES[y_type]:
msg = 'Unknown label type: '
assert_raises_regex(ValueError, msg,
check_classification_targets, example)
else:
for example in EXAMPLES[y_type]:
check_classification_targets(example)
开发者ID:hmshan,项目名称:scikit-learn,代码行数:10,代码来源:test_multiclass.py
示例18: test_ovr_partial_fit_exceptions
def test_ovr_partial_fit_exceptions():
ovr = OneVsRestClassifier(MultinomialNB())
X = np.abs(np.random.randn(14, 2))
y = [1, 1, 1, 1, 2, 3, 3, 0, 0, 2, 3, 1, 2, 3]
ovr.partial_fit(X[:7], y[:7], np.unique(y))
# A new class value which was not in the first call of partial_fit
# It should raise ValueError
y1 = [5] + y[7:-1]
assert_raises_regex(ValueError, "Mini-batch contains \[.+\] while classes"
" must be subset of \[.+\]",
ovr.partial_fit, X=X[7:], y=y1)
开发者ID:btabibian,项目名称:scikit-learn,代码行数:11,代码来源:test_multiclass.py
示例19: test_randomized_lasso_error_memory
def test_randomized_lasso_error_memory():
scaling = 0.3
selection_threshold = 0.5
tempdir = 5
clf = RandomizedLasso(verbose=False, alpha=[1, 0.8], random_state=42,
scaling=scaling,
selection_threshold=selection_threshold,
memory=tempdir)
assert_raises_regex(ValueError, "'memory' should either be a string or"
" a sklearn.utils.Memory instance",
clf.fit, X, y)
开发者ID:lebigot,项目名称:scikit-learn,代码行数:11,代码来源:test_randomized_l1.py
示例20: test_ordinal_encoder_inverse
def test_ordinal_encoder_inverse():
X = [['abc', 2, 55], ['def', 1, 55]]
enc = OrdinalEncoder()
X_tr = enc.fit_transform(X)
exp = np.array(X, dtype=object)
assert_array_equal(enc.inverse_transform(X_tr), exp)
# incorrect shape raises
X_tr = np.array([[0, 1, 1, 2], [1, 0, 1, 0]])
msg = re.escape('Shape of the passed X data is not correct')
assert_raises_regex(ValueError, msg, enc.inverse_transform, X_tr)
开发者ID:mikebotazzo,项目名称:scikit-learn,代码行数:11,代码来源:test_encoders.py
注:本文中的sklearn.utils.testing.assert_raises_regex函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论