diff --git a/sklearn/cluster/tests/test_k_means.py b/sklearn/cluster/tests/test_k_means.py index 820b4316be8abdac80e16721d55e92bd6650a241..fe9226c1ccd52e69672808dcaf5f3cccf6117c16 100644 --- a/sklearn/cluster/tests/test_k_means.py +++ b/sklearn/cluster/tests/test_k_means.py @@ -11,6 +11,8 @@ from nose.tools import assert_almost_equal from nose.tools import assert_raises from nose.tools import assert_true +from sklearn.utils.testing import assert_greater +from sklearn.utils.testing import assert_less from sklearn.metrics.cluster import v_measure_score from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans @@ -107,13 +109,13 @@ def test_minibatch_update_consistency(): old_inertia, incremental_diff = _mini_batch_step( X_mb, x_mb_squared_norms, new_centers, counts, buffer, 1) - assert_true(old_inertia > 0.0) + assert_greater(old_inertia, 0.0) # compute the new inertia on the same batch to check that it decreased labels, new_inertia = _labels_inertia( X_mb, x_mb_squared_norms, new_centers) - assert_true(new_inertia > 0.0) - assert_true(new_inertia < old_inertia) + assert_greater(new_inertia, 0.0) + assert_less(new_inertia, old_inertia) # check that the incremental difference computation is matching the # final observed value @@ -124,13 +126,13 @@ def test_minibatch_update_consistency(): old_inertia_csr, incremental_diff_csr = _mini_batch_step( X_mb_csr, x_mb_squared_norms_csr, new_centers_csr, counts_csr, buffer_csr, 1) - assert_true(old_inertia_csr > 0.0) + assert_greater(old_inertia_csr, 0.0) # compute the new inertia on the same batch to check that it decreased labels_csr, new_inertia_csr = _labels_inertia( X_mb_csr, x_mb_squared_norms_csr, new_centers_csr) - assert_true(new_inertia_csr > 0.0) - assert_true(new_inertia_csr < old_inertia_csr) + assert_greater(new_inertia_csr, 0.0) + assert_less(new_inertia_csr, old_inertia_csr) # check that the incremental difference computation is matching the # final observed value @@ -156,7 +158,7 @@ def _check_fitted_model(km): # check that the labels assignements are perfect (up to a permutation) assert_equal(v_measure_score(true_labels, labels), 1.0) - assert_true(km.inertia_ > 0.0) + assert_greater(km.inertia_, 0.0) # check error on dataset being too small assert_raises(ValueError, km.fit, [[0., 1.]]) @@ -367,7 +369,7 @@ def test_predict(): def test_score(): s1 = KMeans(k=n_clusters, max_iter=1, random_state=42).fit(X).score(X) s2 = KMeans(k=n_clusters, max_iter=10, random_state=42).fit(X).score(X) - assert_true(s2 > s1) + assert_greater(s2, s1) def test_predict_minibatch_dense_input(): @@ -449,7 +451,7 @@ def test_transform(): assert_equal(X_new[c, c], 0) for c2 in range(n_clusters): if c != c2: - assert_true(X_new[c, c2] > 0) + assert_greater(X_new[c, c2], 0) def test_n_init(): diff --git a/sklearn/cluster/tests/test_spectral.py b/sklearn/cluster/tests/test_spectral.py index 1d79795bef17cd0219a74427ebcc898543bdfc3b..c134dd96de3820ef92d789f3b4258032962a7316 100644 --- a/sklearn/cluster/tests/test_spectral.py +++ b/sklearn/cluster/tests/test_spectral.py @@ -2,12 +2,12 @@ from cPickle import dumps, loads import nose -from nose.tools import assert_true import numpy as np from numpy.testing import assert_equal from scipy import sparse +from sklearn.utils.testing import assert_greater from .. import SpectralClustering @@ -59,4 +59,4 @@ def test_spectral_clustering_sparse(): if labels[0] == 0: labels = 1 - labels - assert_true(np.mean(labels == [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]) > .9) + assert_greater(np.mean(labels == [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]), .9) diff --git a/sklearn/datasets/tests/test_samples_generator.py b/sklearn/datasets/tests/test_samples_generator.py index 18617966621c9eadb52ac7dea8063c18f97e2646..bda29d018122409dc5975895c42ad11e3e37c963 100644 --- a/sklearn/datasets/tests/test_samples_generator.py +++ b/sklearn/datasets/tests/test_samples_generator.py @@ -3,6 +3,8 @@ from numpy.testing import assert_equal, assert_approx_equal, \ assert_array_almost_equal from nose.tools import assert_true +from sklearn.utils.testing import assert_less + from .. import make_classification from .. import make_multilabel_classification from .. import make_hastie_10_2 @@ -119,7 +121,7 @@ def test_make_low_rank_matrix(): from numpy.linalg import svd u, s, v = svd(X) - assert_true(sum(s) - 5 < 0.1, "X rank is not approximately 5") + assert_less(sum(s) - 5, 0.1, "X rank is not approximately 5") def test_make_sparse_coded_signal(): diff --git a/sklearn/decomposition/tests/test_dict_learning.py b/sklearn/decomposition/tests/test_dict_learning.py index 09b54ef5ce6113fb571c2f2645bbaaa4b0808420..3c1c42aef611a1a8a6590714a4bb9aafe29ce7c0 100644 --- a/sklearn/decomposition/tests/test_dict_learning.py +++ b/sklearn/decomposition/tests/test_dict_learning.py @@ -4,6 +4,8 @@ from numpy.testing import assert_array_almost_equal, assert_array_equal, \ from nose import SkipTest from nose.tools import assert_true +from sklearn.utils.testing import assert_less + from .. import DictionaryLearning, MiniBatchDictionaryLearning, SparseCoder, \ dict_learning_online, sparse_encode @@ -129,7 +131,7 @@ def test_sparse_encode_error(): V /= np.sum(V ** 2, axis=1)[:, np.newaxis] code = sparse_encode(X, V, alpha=0.001) assert_true(not np.all(code == 0)) - assert_true(np.sqrt(np.sum((np.dot(code, V) - X) ** 2)) < 0.1) + assert_less(np.sqrt(np.sum((np.dot(code, V) - X) ** 2)), 0.1) def test_sparse_coder_estimator(): @@ -139,4 +141,4 @@ def test_sparse_coder_estimator(): code = SparseCoder(dictionary=V, transform_algorithm='lasso_lars', transform_alpha=0.001).transform(X) assert_true(not np.all(code == 0)) - assert_true(np.sqrt(np.sum((np.dot(code, V) - X) ** 2)) < 0.1) + assert_less(np.sqrt(np.sum((np.dot(code, V) - X) ** 2)), 0.1) diff --git a/sklearn/decomposition/tests/test_fastica.py b/sklearn/decomposition/tests/test_fastica.py index 364b990c3805125f6baac2cb12c54cd15f17c06d..5f8e6dc3c2a46e96a67fa404b0d25e61945feb06 100644 --- a/sklearn/decomposition/tests/test_fastica.py +++ b/sklearn/decomposition/tests/test_fastica.py @@ -9,6 +9,8 @@ from nose.tools import assert_true from scipy import stats import itertools +from sklearn.utils.testing import assert_less + from .. import FastICA, fastica, PCA from ..fastica_ import _gs_decorrelation @@ -38,11 +40,11 @@ def test_gs(): W, _, _ = np.linalg.svd(rng.randn(10, 10)) w = rng.randn(10) _gs_decorrelation(w, W, 10) - assert_true((w ** 2).sum() < 1.e-10) + assert_less((w ** 2).sum(), 1.e-10) w = rng.randn(10) u = _gs_decorrelation(w, W, 5) tmp = np.dot(u, W.T) - assert_true((tmp[:5] ** 2).sum() < 1.e-10) + assert_less((tmp[:5] ** 2).sum(), 1.e-10) def test_fastica(add_noise=False): diff --git a/sklearn/decomposition/tests/test_kernel_pca.py b/sklearn/decomposition/tests/test_kernel_pca.py index a84828dff8988d959ebd60883304a19470d8aee8..21a85d70fce9942a8057eec5cc2ebcda99960177 100644 --- a/sklearn/decomposition/tests/test_kernel_pca.py +++ b/sklearn/decomposition/tests/test_kernel_pca.py @@ -8,7 +8,7 @@ from nose.tools import assert_raises from sklearn.decomposition import PCA, KernelPCA from sklearn.datasets import make_circles from sklearn.linear_model import Perceptron -from sklearn.utils.testing import assert_lower +from sklearn.utils.testing import assert_less def test_kernel_pca(): @@ -124,7 +124,7 @@ def test_nested_circles(): # 2D nested circles are not linearly separable train_score = Perceptron().fit(X, y).score(X, y) - assert_lower(train_score, 0.8) + assert_less(train_score, 0.8) # Project the circles data into the first 2 components of a RBF Kernel # PCA model. diff --git a/sklearn/decomposition/tests/test_nmf.py b/sklearn/decomposition/tests/test_nmf.py index cb8bba009f3ba098df527a4ac95286487bad0a5b..27e177d6e0736af84ebe884e34c0723eaf21f36b 100644 --- a/sklearn/decomposition/tests/test_nmf.py +++ b/sklearn/decomposition/tests/test_nmf.py @@ -3,6 +3,8 @@ from .. import nmf from nose.tools import assert_true, assert_false, raises from numpy.testing import assert_array_almost_equal +from sklearn.utils.testing import assert_greater + random_state = np.random.mtrand.RandomState(0) @@ -119,7 +121,8 @@ def test_projgrad_nmf_sparseness(): sparseness='data').fit(A).data_sparseness_ comp_sp = nmf.ProjectedGradientNMF(n_components=5, sparseness='components').fit(A).comp_sparseness_ - assert_true(data_sp > m.data_sparseness_ and comp_sp > m.comp_sparseness_) + assert_greater(data_sp, m.data_sparseness_) + assert_greater(comp_sp, m.comp_sparseness_) def test_sparse_input(): diff --git a/sklearn/decomposition/tests/test_pca.py b/sklearn/decomposition/tests/test_pca.py index d9f6b97cd7fdb9cb1ea64a75ad700b8e05c612c7..60d95e1923cff71fda7f20b5c03528d6a1f6f83b 100644 --- a/sklearn/decomposition/tests/test_pca.py +++ b/sklearn/decomposition/tests/test_pca.py @@ -5,6 +5,8 @@ from nose.tools import assert_equal from scipy.sparse import csr_matrix from numpy.testing import assert_almost_equal, assert_array_almost_equal +from sklearn.utils.testing import assert_less, assert_greater + from ... import datasets from .. import PCA from .. import ProbabilisticPCA @@ -234,7 +236,7 @@ def test_infer_dim_1(): for k in range(p): ll.append(_assess_dimension_(spect, k, n, p)) ll = np.array(ll) - assert_true(ll[1] > ll.max() - .01 * n) + assert_greater(ll[1], ll.max() - .01 * n) def test_infer_dim_2(): @@ -250,7 +252,7 @@ def test_infer_dim_2(): pca = PCA(n_components=p) pca.fit(X) spect = pca.explained_variance_ - assert_true(_infer_dimension_(spect, n, p) > 1) + assert_greater(_infer_dimension_(spect, n, p), 1) def test_infer_dim_3(): @@ -265,7 +267,7 @@ def test_infer_dim_3(): pca = PCA(n_components=p) pca.fit(X) spect = pca.explained_variance_ - assert_true(_infer_dimension_(spect, n, p) > 2) + assert_greater(_infer_dimension_(spect, n, p), 2) def test_infer_dim_by_explained_variance(): @@ -306,7 +308,7 @@ def test_probabilistic_pca_2(): ppca.fit(X) ll1 = ppca.score(X) ll2 = ppca.score(rng.randn(n, p) * .2 + np.array([3, 4, 5])) - assert_true(ll1.mean() > ll2.mean()) + assert_greater(ll1.mean(), ll2.mean()) def test_probabilistic_pca_3(): @@ -321,7 +323,7 @@ def test_probabilistic_pca_3(): ll1 = ppca.score(X) ppca.fit(X, homoscedastic=False) ll2 = ppca.score(X) - assert_true(ll1.mean() < ll2.mean()) + assert_less(ll1.mean(), ll2.mean()) def test_probabilistic_pca_4(): diff --git a/sklearn/ensemble/tests/test_forest.py b/sklearn/ensemble/tests/test_forest.py index 5b958f21b2206bf34db6f89b40d02c1b2e2d7888..56f6f20986c8e93a66c39dab12c109ef31623faf 100644 --- a/sklearn/ensemble/tests/test_forest.py +++ b/sklearn/ensemble/tests/test_forest.py @@ -12,6 +12,8 @@ from numpy.testing import assert_equal from numpy.testing import assert_almost_equal from nose.tools import assert_true +from sklearn.utils.testing import assert_less, assert_greater + from sklearn.grid_search import GridSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import RandomForestRegressor @@ -175,7 +177,7 @@ def test_importances(): assert_equal(n_important, 3) X_new = clf.transform(X, threshold="mean") - assert_true(0 < X_new.shape[1] < X.shape[1]) + assert_less(0 < X_new.shape[1], X.shape[1]) clf = RandomForestClassifier(n_estimators=10) clf.fit(X, y) @@ -200,8 +202,8 @@ def test_oob_score_regression(): clf.fit(boston.data[:n_samples / 2, :], boston.target[:n_samples / 2]) test_score = clf.score(boston.data[n_samples / 2:, :], boston.target[n_samples / 2:]) - assert_true(test_score > clf.oob_score_) - assert_true(clf.oob_score_ > .8) + assert_greater(test_score, clf.oob_score_) + assert_greater(clf.oob_score_, .8) def test_gridsearch(): diff --git a/sklearn/feature_extraction/tests/test_text.py b/sklearn/feature_extraction/tests/test_text.py index 1424fe8eafe88c6d8fa217e9a95d3104007adc5c..738922ee56025ad0c015a6b1397754ebd9e7fc5e 100644 --- a/sklearn/feature_extraction/tests/test_text.py +++ b/sklearn/feature_extraction/tests/test_text.py @@ -7,6 +7,8 @@ from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.utils.testing import assert_less, assert_greater + from sklearn.grid_search import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC @@ -269,10 +271,10 @@ def test_sublinear_tf(): tr = TfidfTransformer(sublinear_tf=True, use_idf=False, norm=None) tfidf = tr.fit_transform(X).toarray() assert_equal(tfidf[0], 1) - assert_true(tfidf[1] > tfidf[0]) - assert_true(tfidf[2] > tfidf[1]) - assert_true(tfidf[1] < 2) - assert_true(tfidf[2] < 3) + assert_greater(tfidf[1], tfidf[0]) + assert_greater(tfidf[2], tfidf[1]) + assert_less(tfidf[1], 2) + assert_less(tfidf[2], 3) def test_vectorizer(): diff --git a/sklearn/feature_selection/tests/test_selector_mixin.py b/sklearn/feature_selection/tests/test_selector_mixin.py index 74a86d12191949b25c61239cb26ab2a02f34f2ce..1ffa3dc04def0beab2ac9e670dc69c6afa25c686 100644 --- a/sklearn/feature_selection/tests/test_selector_mixin.py +++ b/sklearn/feature_selection/tests/test_selector_mixin.py @@ -3,6 +3,8 @@ import scipy.sparse as sp from nose.tools import assert_true +from sklearn.utils.testing import assert_less + from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.linear_model import SGDClassifier @@ -23,7 +25,7 @@ def test_transform_linear_model(): if isinstance(clf, SGDClassifier): assert_true(X_new.shape[1] <= X.shape[1]) else: - assert_true(X_new.shape[1] < X.shape[1]) + assert_less(X_new.shape[1], X.shape[1]) clf.set_params(penalty="l2") clf.fit(X_new, iris.target) pred = clf.predict(X_new) diff --git a/sklearn/linear_model/sparse/tests/test_coordinate_descent.py b/sklearn/linear_model/sparse/tests/test_coordinate_descent.py index 6963c2fc4a3f240a52e2c40e631d2a33ab9e7cd8..103a87c2d1643f8c0687b0653c1eabc69fe1eae0 100644 --- a/sklearn/linear_model/sparse/tests/test_coordinate_descent.py +++ b/sklearn/linear_model/sparse/tests/test_coordinate_descent.py @@ -3,7 +3,8 @@ import scipy.sparse as sp from numpy.testing import assert_array_almost_equal from numpy.testing import assert_almost_equal from numpy.testing import assert_equal -from nose.tools import assert_true + +from sklearn.utils.testing import assert_less, assert_greater from sklearn.linear_model.sparse.coordinate_descent import Lasso as SparseLasso from sklearn.linear_model.sparse.coordinate_descent \ @@ -138,19 +139,19 @@ def test_sparse_enet_not_as_toy_dataset(): max_iter=max_iter, tol=1e-7) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) - assert_true(s_clf.score(X_test, y_test) > 0.85) + assert_greater(s_clf.score(X_test, y_test), 0.85) # check the convergence is the same as the dense version d_clf = DenseENet(alpha=0.1, rho=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-7) d_clf.fit(X_train, y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) - assert_true(d_clf.score(X_test, y_test) > 0.85) + assert_greater(d_clf.score(X_test, y_test), 0.85) assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) # check that the coefs are sparse - assert_true(np.sum(s_clf.coef_ != 0.0) < 2 * n_informative) + assert_less(np.sum(s_clf.coef_ != 0.0), 2 * n_informative) def test_sparse_lasso_not_as_toy_dataset(): @@ -166,14 +167,14 @@ def test_sparse_lasso_not_as_toy_dataset(): max_iter=max_iter, tol=1e-7) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) - assert_true(s_clf.score(X_test, y_test) > 0.85) + assert_greater(s_clf.score(X_test, y_test), 0.85) # check the convergence is the same as the dense version d_clf = DenseLasso(alpha=0.1, fit_intercept=False, max_iter=max_iter, tol=1e-7) d_clf.fit(X_train, y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) - assert_true(d_clf.score(X_test, y_test) > 0.85) + assert_greater(d_clf.score(X_test, y_test), 0.85) # check that the coefs are sparse assert_equal(np.sum(s_clf.coef_ != 0.0), n_informative) diff --git a/sklearn/linear_model/tests/test_coordinate_descent.py b/sklearn/linear_model/tests/test_coordinate_descent.py index 05b46ce47d5b2b03b35e60484c5d5b6f42185523..57c460889107e6586679e86c533ea8b9f7763d09 100644 --- a/sklearn/linear_model/tests/test_coordinate_descent.py +++ b/sklearn/linear_model/tests/test_coordinate_descent.py @@ -12,6 +12,8 @@ from numpy.testing import assert_array_almost_equal, assert_almost_equal, \ from nose import SkipTest from nose.tools import assert_true +from sklearn.utils.testing import assert_greater + from sklearn.linear_model.coordinate_descent import Lasso, \ LassoCV, ElasticNet, ElasticNetCV from sklearn.linear_model import LassoLarsCV @@ -168,7 +170,7 @@ def test_lasso_path(): significant=2) # test set - assert_true(clf.score(X_test, y_test) > 0.99) + assert_greater(clf.score(X_test, y_test), 0.99) def test_enet_path(): @@ -192,7 +194,7 @@ def test_enet_path(): assert_equal(clf.rho_, 0.95) # test set - assert_true(clf.score(X_test, y_test) > 0.99) + assert_greater(clf.score(X_test, y_test), 0.99) def test_path_parameters(): @@ -238,7 +240,7 @@ def test_lasso_alpha_warning(): clf = Lasso(alpha=0) clf.fit(X, Y) - assert_true(len(w) > 0) # warnings should be raised + assert_greater(len(w), 0) # warnings should be raised def test_lasso_positive_constraint(): diff --git a/sklearn/linear_model/tests/test_least_angle.py b/sklearn/linear_model/tests/test_least_angle.py index 1b800ade41105d4f4c862a9e36c0f4beca76b2c9..6056f64305715a66b5cccc5348d33e52ba82b18d 100644 --- a/sklearn/linear_model/tests/test_least_angle.py +++ b/sklearn/linear_model/tests/test_least_angle.py @@ -2,6 +2,7 @@ import numpy as np from numpy.testing import assert_array_almost_equal from nose.tools import assert_true +from sklearn.utils.testing import assert_less, assert_greater from sklearn import linear_model, datasets diabetes = datasets.load_diabetes() @@ -85,7 +86,7 @@ def test_collinearity(): _, _, coef_path_ = linear_model.lars_path(X, y, alpha_min=0.01) assert_true(not np.isnan(coef_path_).any()) residual = np.dot(X, coef_path_[:, -1]) - y - assert_true((residual ** 2).sum() < 1.) # just make sure it's bounded + assert_less((residual ** 2).sum(), 1.) # just make sure it's bounded def test_singular_matrix(): @@ -113,7 +114,7 @@ def test_lasso_lars_vs_lasso_cd(verbose=False): lasso_cd.alpha = a lasso_cd.fit(X, y) error = np.linalg.norm(c - lasso_cd.coef_) - assert_true(error < 0.01) + assert_less(error, 0.01) # similar test, with the classifiers for alpha in np.linspace(1e-2, 1 - 1e-2): @@ -121,7 +122,7 @@ def test_lasso_lars_vs_lasso_cd(verbose=False): clf2 = linear_model.Lasso(alpha=alpha, tol=1e-8, normalize=False).fit(X, y) err = np.linalg.norm(clf1.coef_ - clf2.coef_) - assert_true(err < 1e-3) + assert_less(err, 1e-3) # same test, with normalized data X = diabetes.data @@ -134,7 +135,7 @@ def test_lasso_lars_vs_lasso_cd(verbose=False): lasso_cd.alpha = a lasso_cd.fit(X, y) error = np.linalg.norm(c - lasso_cd.coef_) - assert_true(error < 0.01) + assert_less(error, 0.01) def test_lasso_lars_vs_lasso_cd_early_stopping(verbose=False): @@ -151,7 +152,7 @@ def test_lasso_lars_vs_lasso_cd_early_stopping(verbose=False): lasso_cd.alpha = alphas[-1] lasso_cd.fit(X, y) error = np.linalg.norm(lasso_path[:, -1] - lasso_cd.coef_) - assert_true(error < 0.01) + assert_less(error, 0.01) alphas_min = [10, 0.9, 1e-4] # same test, with normalization @@ -163,7 +164,7 @@ def test_lasso_lars_vs_lasso_cd_early_stopping(verbose=False): lasso_cd.alpha = alphas[-1] lasso_cd.fit(X, y) error = np.linalg.norm(lasso_path[:, -1] - lasso_cd.coef_) - assert_true(error < 0.01) + assert_less(error, 0.01) def test_lars_add_features(): @@ -219,9 +220,9 @@ def test_lasso_lars_ic(): lars_aic.fit(X, y) nonzero_bic = np.where(lars_bic.coef_)[0] nonzero_aic = np.where(lars_aic.coef_)[0] - assert_true(lars_bic.alpha_ > lars_aic.alpha_) - assert_true(len(nonzero_bic) < len(nonzero_aic)) - assert_true(np.max(nonzero_bic) < diabetes.data.shape[1]) + assert_greater(lars_bic.alpha_, lars_aic.alpha_) + assert_less(len(nonzero_bic), len(nonzero_aic)) + assert_less(np.max(nonzero_bic), diabetes.data.shape[1]) if __name__ == '__main__': diff --git a/sklearn/linear_model/tests/test_logistic.py b/sklearn/linear_model/tests/test_logistic.py index d165c525e11ed2d8e70af172786897e7bf49f4d4..6f517580be22355448e907298c5b29b51a6586f4 100644 --- a/sklearn/linear_model/tests/test_logistic.py +++ b/sklearn/linear_model/tests/test_logistic.py @@ -3,7 +3,9 @@ import scipy.sparse as sp from numpy.testing import assert_array_equal import nose -from nose.tools import assert_raises, raises, assert_true +from nose.tools import assert_raises, raises + +from sklearn.utils.testing import assert_greater from sklearn.linear_model import logistic from sklearn import datasets @@ -67,10 +69,10 @@ def test_predict_iris(): iris.target) pred = clf.predict(iris.data) - assert_true(np.mean(pred == iris.target) > .95) + assert_greater(np.mean(pred == iris.target), .95) pred = clf.predict_proba(iris.data).argmax(axis=1) - assert_true(np.mean(pred == iris.target) > .95) + assert_greater(np.mean(pred == iris.target), .95) def test_inconsistent_input(): diff --git a/sklearn/linear_model/tests/test_omp.py b/sklearn/linear_model/tests/test_omp.py index 0be9f7573ea512f101f6b8be4ca4f614bb3ed4fb..0c2cb16d1a755eb0d58ede48111b62392d685f99 100644 --- a/sklearn/linear_model/tests/test_omp.py +++ b/sklearn/linear_model/tests/test_omp.py @@ -8,6 +8,8 @@ import numpy as np from nose.tools import assert_raises, assert_true from numpy.testing import assert_equal, assert_array_almost_equal +from sklearn.utils.testing import assert_greater + from sklearn.linear_model import orthogonal_mp, orthogonal_mp_gram, \ OrthogonalMatchingPursuit from sklearn.utils.fixes import count_nonzero @@ -73,7 +75,7 @@ def test_unreachable_accuracy(): orthogonal_mp(X, y, tol=0, precompute_gram=True), orthogonal_mp(X, y, precompute_gram=True, n_nonzero_coefs=n_features)) - assert_true(len(w) > 0) # warnings should be raised + assert_greater(len(w), 0) # warnings should be raised def test_bad_input(): diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py index 8be9cd93fa85faf465d4dad9b0cf9229093e7927..e7ba5b33cdd47bfabc06ccc6e72ea3b9ce3cf32d 100644 --- a/sklearn/linear_model/tests/test_ridge.py +++ b/sklearn/linear_model/tests/test_ridge.py @@ -5,6 +5,7 @@ from numpy.testing import assert_almost_equal, assert_array_almost_equal, \ assert_equal, assert_array_equal from sklearn import datasets from sklearn.metrics import mean_squared_error +from sklearn.utils.testing import assert_greater from sklearn.linear_model.base import LinearRegression from sklearn.linear_model.ridge import Ridge @@ -51,10 +52,10 @@ def test_ridge(): ridge = Ridge(alpha=alpha) ridge.fit(X, y) assert_equal(ridge.coef_.shape, (X.shape[1], )) - assert_true(ridge.score(X, y) > 0.5) + assert_greater(ridge.score(X, y), 0.5) ridge.fit(X, y, sample_weight=np.ones(n_samples)) - assert_true(ridge.score(X, y) > 0.5) + assert_greater(ridge.score(X, y), 0.5) # With more features than samples n_samples, n_features = 5, 10 @@ -62,10 +63,10 @@ def test_ridge(): X = np.random.randn(n_samples, n_features) ridge = Ridge(alpha=alpha) ridge.fit(X, y) - assert_true(ridge.score(X, y) > .9) + assert_greater(ridge.score(X, y), .9) ridge.fit(X, y, sample_weight=np.ones(n_samples)) - assert_true(ridge.score(X, y) > 0.9) + assert_greater(ridge.score(X, y), 0.9) def test_ridge_shapes(): diff --git a/sklearn/linear_model/tests/test_sgd.py b/sklearn/linear_model/tests/test_sgd.py index 1572c43a782103a0f24614bea88514e7b4f8f21d..fbd26e4cdf78609a64c53dbd8f79db0e1a8e3faf 100644 --- a/sklearn/linear_model/tests/test_sgd.py +++ b/sklearn/linear_model/tests/test_sgd.py @@ -7,6 +7,7 @@ from numpy.testing import assert_almost_equal, assert_array_almost_equal from sklearn import linear_model, datasets, metrics from sklearn import preprocessing from sklearn.linear_model import SGDClassifier, SGDRegressor +from sklearn.utils.testing import assert_greater, assert_less import unittest from nose.tools import raises @@ -271,9 +272,9 @@ class DenseSGDClassifierTestCase(unittest.TestCase, CommonTest): # log loss implements the logistic regression prob estimate clf = self.factory(loss="log", alpha=0.01, n_iter=10).fit(X, Y) p = clf.predict_proba([3, 2]) - assert_true(p > 0.5) + assert_greater(p, 0.5) p = clf.predict_proba([-1, -1]) - assert_true(p < 0.5) + assert_less(p, 0.5) def test_sgd_l1(self): """Test L1 regularization""" @@ -377,19 +378,19 @@ class DenseSGDClassifierTestCase(unittest.TestCase, CommonTest): clf = self.factory(n_iter=1000, class_weight=None) clf.fit(X_imbalanced, y_imbalanced) y_pred = clf.predict(X) - assert_true(metrics.f1_score(y, y_pred) < 0.96) + assert_less(metrics.f1_score(y, y_pred), 0.96) # fit a model with auto class_weight enabled clf = self.factory(n_iter=1000, class_weight="auto") clf.fit(X_imbalanced, y_imbalanced) y_pred = clf.predict(X) - assert_true(metrics.f1_score(y, y_pred) > 0.96) + assert_greater(metrics.f1_score(y, y_pred), 0.96) # fit another using a fit parameter override clf = self.factory(n_iter=1000, class_weight="auto") clf.fit(X_imbalanced, y_imbalanced) y_pred = clf.predict(X) - assert_true(metrics.f1_score(y, y_pred) > 0.96) + assert_greater(metrics.f1_score(y, y_pred), 0.96) def test_sample_weights(self): """Test weights on individual samples""" @@ -536,7 +537,7 @@ class DenseSGDRegressorTestCase(unittest.TestCase): fit_intercept=False) clf.fit(X, y) score = clf.score(X, y) - assert_true(score > 0.99) + assert_greater(score, 0.99) # simple linear function with noise y = 0.5 * X.ravel() \ @@ -546,7 +547,7 @@ class DenseSGDRegressorTestCase(unittest.TestCase): fit_intercept=False) clf.fit(X, y) score = clf.score(X, y) - assert_true(score > 0.5) + assert_greater(score, 0.5) def test_sgd_huber_fit(self): xmin, xmax = -5, 5 @@ -560,7 +561,7 @@ class DenseSGDRegressorTestCase(unittest.TestCase): fit_intercept=False) clf.fit(X, y) score = clf.score(X, y) - assert_true(score > 0.99) + assert_greater(score, 0.99) # simple linear function with noise y = 0.5 * X.ravel() \ @@ -570,7 +571,7 @@ class DenseSGDRegressorTestCase(unittest.TestCase): fit_intercept=False) clf.fit(X, y) score = clf.score(X, y) - assert_true(score > 0.5) + assert_greater(score, 0.5) def test_elasticnet_convergence(self): """Check that the SGD ouput is consistent with coordinate descent""" diff --git a/sklearn/manifold/tests/test_isomap.py b/sklearn/manifold/tests/test_isomap.py index 5c35c7676ac6cc41ebf3c014d543767dedb5ea25..17155473294929fb50a85c951b67013129afd0f0 100644 --- a/sklearn/manifold/tests/test_isomap.py +++ b/sklearn/manifold/tests/test_isomap.py @@ -9,7 +9,7 @@ from sklearn import manifold from sklearn import neighbors from sklearn import pipeline from sklearn import preprocessing -from sklearn.utils.testing import assert_lower +from sklearn.utils.testing import assert_less eigen_solvers = ['auto', 'dense', 'arpack'] path_methods = ['auto', 'FW', 'D'] @@ -100,7 +100,7 @@ def test_transform(): X_iso2 = iso.transform(X + noise) # Make sure the rms error on re-embedding is comparable to noise_scale - assert_true(np.sqrt(np.mean((X_iso - X_iso2) ** 2)) < 2 * noise_scale) + assert_less(np.sqrt(np.mean((X_iso - X_iso2) ** 2)), 2 * noise_scale) def test_pipeline(): @@ -112,7 +112,7 @@ def test_pipeline(): [('isomap', manifold.Isomap()), ('clf', neighbors.KNeighborsClassifier())]) clf.fit(X, y) - assert_lower(.9, clf.score(X, y)) + assert_less(.9, clf.score(X, y)) if __name__ == '__main__': diff --git a/sklearn/manifold/tests/test_locally_linear.py b/sklearn/manifold/tests/test_locally_linear.py index c9ca2f0d795722bf71488e7faeed16a60244546b..a21ccbdd55538196b771c90549135cd297dc4817 100644 --- a/sklearn/manifold/tests/test_locally_linear.py +++ b/sklearn/manifold/tests/test_locally_linear.py @@ -5,7 +5,7 @@ from nose.tools import assert_true from numpy.testing import assert_almost_equal, assert_array_almost_equal from sklearn import neighbors, manifold from sklearn.manifold.locally_linear import barycenter_kneighbors_graph -from sklearn.utils.testing import assert_lower +from sklearn.utils.testing import assert_less eigen_solvers = ['dense', 'arpack'] @@ -26,7 +26,7 @@ def test_barycenter_kneighbors_graph(): # check that columns sum to one assert_array_almost_equal(np.sum(A.todense(), 1), np.ones((3, 1))) pred = np.dot(A.todense(), X) - assert_true(np.linalg.norm(pred - X) / X.shape[0] < 1) + assert_less(np.linalg.norm(pred - X) / X.shape[0], 1) #---------------------------------------------------------------------- @@ -43,7 +43,7 @@ def test_lle_simple_grid(): N = barycenter_kneighbors_graph(X, clf.n_neighbors).todense() reconstruction_error = np.linalg.norm(np.dot(N, X) - X, 'fro') - assert_lower(reconstruction_error, tol) + assert_less(reconstruction_error, tol) for solver in eigen_solvers: clf.set_params(eigen_solver=solver) @@ -53,14 +53,14 @@ def test_lle_simple_grid(): np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 # FIXME: ARPACK fails this test ... if solver != 'arpack': - assert_lower(reconstruction_error, tol) + assert_less(reconstruction_error, tol) assert_almost_equal(clf.reconstruction_error_, reconstruction_error, decimal=4) # re-embed a noisy version of X using the transform method noise = rng.randn(*X.shape) / 100 X_reembedded = clf.transform(X + noise) - assert_lower(np.linalg.norm(X_reembedded - clf.embedding_), tol) + assert_less(np.linalg.norm(X_reembedded - clf.embedding_), tol) def test_lle_manifold(): @@ -75,7 +75,7 @@ def test_lle_manifold(): N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() reconstruction_error = np.linalg.norm(np.dot(N, X) - X) - assert_lower(reconstruction_error, tol) + assert_less(reconstruction_error, tol) for solver in eigen_solvers: clf.set_params(eigen_solver=solver) @@ -84,9 +84,9 @@ def test_lle_manifold(): reconstruction_error = np.linalg.norm( np.dot(N, clf.embedding_) - clf.embedding_, 'fro') ** 2 details = "solver: " + solver - assert_lower(reconstruction_error, tol, details=details) - assert_lower(np.abs(clf.reconstruction_error_ - reconstruction_error), - tol * reconstruction_error, details=details) + assert_less(reconstruction_error, tol, msg=details) + assert_less(np.abs(clf.reconstruction_error_ - reconstruction_error), + tol * reconstruction_error, msg=details) def test_pipeline(): @@ -99,7 +99,7 @@ def test_pipeline(): [('filter', manifold.LocallyLinearEmbedding()), ('clf', neighbors.KNeighborsClassifier())]) clf.fit(X, y) - assert_lower(.9, clf.score(X, y)) + assert_less(.9, clf.score(X, y)) # Test the error raised when the weight matrix is singular diff --git a/sklearn/svm/tests/test_svm.py b/sklearn/svm/tests/test_svm.py index 8cc15fe621f4fd5b920dacb33f0c29eeb8f2891b..e8af5fc5f16dcdd005643a1a4fd14e63a8ca7608 100644 --- a/sklearn/svm/tests/test_svm.py +++ b/sklearn/svm/tests/test_svm.py @@ -12,6 +12,7 @@ from nose.tools import assert_raises, assert_true from sklearn import svm, linear_model, datasets, metrics, base from sklearn.datasets.samples_generator import make_classification from sklearn.utils import check_random_state +from sklearn.utils.testing import assert_greater, assert_less # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] @@ -47,23 +48,23 @@ def test_libsvm_iris(): # shuffle the dataset so that labels are not ordered for k in ('linear', 'rbf'): clf = svm.SVC(kernel=k).fit(iris.data, iris.target) - assert_true(np.mean(clf.predict(iris.data) == iris.target) > 0.9) + assert_greater(np.mean(clf.predict(iris.data) == iris.target), 0.9) assert_array_equal(clf.label_, np.sort(clf.label_)) # check also the low-level API model = svm.libsvm.fit(iris.data, iris.target.astype(np.float64)) pred = svm.libsvm.predict(iris.data, *model) - assert_true(np.mean(pred == iris.target) > .95) + assert_greater(np.mean(pred == iris.target), .95) model = svm.libsvm.fit(iris.data, iris.target.astype(np.float64), kernel='linear') pred = svm.libsvm.predict(iris.data, *model, kernel='linear') - assert_true(np.mean(pred == iris.target) > .95) + assert_greater(np.mean(pred == iris.target), .95) pred = svm.libsvm.cross_validation(iris.data, iris.target.astype(np.float64), 5, kernel='linear') - assert_true(np.mean(pred == iris.target) > .95) + assert_greater(np.mean(pred == iris.target), .95) def test_single_sample_1d(): @@ -156,7 +157,6 @@ def test_SVR(): """ diabetes = datasets.load_diabetes() - n_samples = len(diabetes.data) for clf in (svm.NuSVR(kernel='linear', nu=.4, C=1.0), svm.NuSVR(kernel='linear', nu=.4, C=10.), svm.SVR(kernel='linear', C=10.), @@ -164,7 +164,7 @@ def test_SVR(): svm.sparse.NuSVR(kernel='linear', nu=.4, C=10.), svm.sparse.SVR(kernel='linear', C=10.)): clf.fit(diabetes.data, diabetes.target) - assert_true(clf.score(diabetes.data, diabetes.target) > 0.02) + assert_greater(clf.score(diabetes.data, diabetes.target), 0.02) def test_oneclass(): @@ -206,9 +206,9 @@ def test_oneclass_decision_function(): # predict things y_pred_test = clf.predict(X_test) - assert_true(np.mean(y_pred_test == 1) > .9) + assert_greater(np.mean(y_pred_test == 1), .9) y_pred_outliers = clf.predict(X_outliers) - assert_true(np.mean(y_pred_outliers == -1) > .9) + assert_greater(np.mean(y_pred_outliers == -1), .9) dec_func_test = clf.decision_function(X_test) assert_array_equal((dec_func_test > 0).ravel(), y_pred_test == 1) dec_func_outliers = clf.decision_function(X_outliers) @@ -458,7 +458,7 @@ def test_linearsvc_iris(): Test that LinearSVC gives plausible predictions on the iris dataset """ clf = svm.LinearSVC().fit(iris.data, iris.target) - assert_true(np.mean(clf.predict(iris.data) == iris.target) > 0.8) + assert_greater(np.mean(clf.predict(iris.data) == iris.target), 0.8) dec = clf.decision_function(iris.data) pred = np.argmax(dec, 1) @@ -490,7 +490,7 @@ def test_dense_liblinear_intercept_handling(classifier=svm.LinearSVC): clf.intercept_scaling = 100 clf.fit(X, y) intercept1 = clf.intercept_ - assert_true(intercept1 < -1) + assert_less(intercept1, -1) # when intercept_scaling is sufficiently high, the intercept value # doesn't depend on intercept_scaling value diff --git a/sklearn/tests/test_cross_validation.py b/sklearn/tests/test_cross_validation.py index 2a40653f923507a2f7c6af6620609aae3907fedd..b20cc9f3faeb41364dacf38b6137418abca6f9e8 100644 --- a/sklearn/tests/test_cross_validation.py +++ b/sklearn/tests/test_cross_validation.py @@ -7,6 +7,7 @@ from scipy.sparse import coo_matrix from nose.tools import assert_true, assert_equal from nose.tools import assert_raises +from ..utils.testing import assert_greater, assert_less from ..base import BaseEstimator from ..datasets import make_regression from ..datasets import load_iris @@ -251,7 +252,7 @@ def test_permutation_score(): score, scores, pvalue = cval.permutation_test_score( svm, X, y, zero_one_score, cv) - assert_true(score > 0.9) + assert_greater(score, 0.9) np.testing.assert_almost_equal(pvalue, 0.0, 1) score_label, _, pvalue_label = cval.permutation_test_score( @@ -276,8 +277,8 @@ def test_permutation_score(): score, scores, pvalue = cval.permutation_test_score(svm, X, y, zero_one_score, cv) - assert_true(score < 0.5) - assert_true(pvalue > 0.4) + assert_less(score, 0.5) + assert_greater(pvalue, 0.4) def test_cross_val_generator_with_mask(): diff --git a/sklearn/tests/test_multiclass.py b/sklearn/tests/test_multiclass.py index c9882b33f4ef75224ea55a7b8c60569f8ed24f94..62f05ad5bd82ffd571c006b59bbae5615f80d35d 100644 --- a/sklearn/tests/test_multiclass.py +++ b/sklearn/tests/test_multiclass.py @@ -7,6 +7,7 @@ from nose.tools import assert_almost_equal from nose.tools import assert_true from nose.tools import assert_raises +from sklearn.utils.testing import assert_greater from sklearn.multiclass import OneVsRestClassifier from sklearn.multiclass import OneVsOneClassifier from sklearn.multiclass import OutputCodeClassifier @@ -15,7 +16,7 @@ from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LinearRegression, Lasso, ElasticNet, Ridge from sklearn.tree import DecisionTreeClassifier from sklearn.grid_search import GridSearchCV -from sklearn import svm +from sklearn import svm from sklearn import datasets iris = datasets.load_iris() @@ -99,7 +100,7 @@ def test_ovr_fit_predict_svc(): ovr = OneVsRestClassifier(svm.SVC()) ovr.fit(iris.data, iris.target) assert_equal(len(ovr.estimators_), 3) - assert_true(ovr.score(iris.data, iris.target) > .9) + assert_greater(ovr.score(iris.data, iris.target), .9) def test_ovr_multilabel_dataset(): diff --git a/sklearn/utils/testing.py b/sklearn/utils/testing.py index d9da8aa679ac2bc06c63ace247d19962c5ac38ee..e2d8b27c7060a042de18c39b655d032ae9796635 100644 --- a/sklearn/utils/testing.py +++ b/sklearn/utils/testing.py @@ -22,11 +22,23 @@ except ImportError: assert_false(x in container, msg="%r in %r" % (x, container)) -def assert_lower(a, b, details=None): - message = "%r is not lower than %r" % (a, b) - if details is not None: - message += ": " + details - assert a < b, message +try: + from nose.tools import assert_less +except ImportError: + def assert_less(a, b, msg=None): + message = "%r is not lower than %r" % (a, b) + if details is not None: + message += ": " + details + assert a < b, message + +try: + from nose.tools import assert_greater +except ImportError: + def assert_greater(a, b, msg=None): + message = "%r is not lower than %r" % (a, b) + if details is not None: + message += ": " + details + assert a < b, message def fake_mldata_cache(columns_dict, dataname, matfile, ordering=None): diff --git a/sklearn/utils/tests/test_svd.py b/sklearn/utils/tests/test_svd.py index 618fae0e30668dfa51ba1d011632aa666df734fb..6e5cf6d96303e8ae2f36c3f5185eacb52c740cae 100644 --- a/sklearn/utils/tests/test_svd.py +++ b/sklearn/utils/tests/test_svd.py @@ -7,7 +7,8 @@ from scipy import linalg from numpy.testing import assert_equal from numpy.testing import assert_almost_equal -from nose.tools import assert_true + +from sklearn.utils.testing import assert_greater from sklearn.utils.extmath import randomized_svd from sklearn.datasets.samples_generator import make_low_rank_matrix @@ -71,7 +72,7 @@ def test_randomized_svd_low_rank_with_noise(): _, sa, _ = randomized_svd(X, k, n_iterations=0) # the approximation does not tolerate the noise: - assert_true(np.abs(s[:k] - sa).max() > 0.05) + assert_greater(np.abs(s[:k] - sa).max(), 0.05) # compute the singular values of X using the fast approximate method with # iterated power method @@ -102,7 +103,7 @@ def test_randomized_svd_infinite_rank(): _, sa, _ = randomized_svd(X, k, n_iterations=0) # the approximation does not tolerate the noise: - assert_true(np.abs(s[:k] - sa).max() > 0.1) + assert_greater(np.abs(s[:k] - sa).max(), 0.1) # compute the singular values of X using the fast approximate method with # iterated power method