repo_name
stringlengths
6
96
path
stringlengths
4
180
copies
stringlengths
1
3
size
stringlengths
4
6
content
stringlengths
906
722k
license
stringclasses
15 values
linhvannguyen/PhDworks
codes/isotropic/regression/regressionUtils.py
2
10304
""" Created on Aug 02 2016 @author: Linh Van Nguyen ([email protected]) """ import numpy as np from netCDF4 import Dataset def data_preprocess(sspacing, tspacing): """ Load coupled input-output of LR and HR from file and normalize to zero-mean and one- standard deviation Parameters ---------- sspacing : 2D subsampling ratio in space (in one direction) tspacing : 1D subsampling ratio in time """ # Constants Nh = 96 Nt = 37 # Position of measurements in space-time HTLS_sknots = np.arange(0,Nh,sspacing) LTHS_tknots = np.arange(0,Nh,tspacing) Nl = len(HTLS_sknots) Ns = len(LTHS_tknots) # Dimension of HTLS and LTHS P = Nh*Nh Q = Nl*Nl M = Nt*Ns #Load all training data Xh_tr = np.zeros((M, P)) Xl_tr = np.zeros((M, Q)) ncfile1 = Dataset('/data/ISOTROPIC/data/data_downsampled4.nc','r') for t in range(Nt): count = 0 for i in LTHS_tknots: xh = np.array(ncfile1.variables['velocity_x'][t,0:Nh,0:Nh,i]) xl = xh[0:-1:sspacing,0:-1:sspacing] # xh[np.meshgrid(HTLS_sknots,HTLS_sknots)] Xh_tr[t*Ns + count,:] = np.reshape(xh,(1, P)) Xl_tr[t*Ns + count,:] = np.reshape(xl,(1, Q)) count = count + 1 ncfile1.close() # normalized: centered, variance 1 mea_l = np.zeros(Q) sig_l = np.zeros(Q) for k in range(Q): mea_l[k] = np.mean(Xl_tr[:,k]) sig_l[k] = np.std(Xl_tr[:,k]) Xl_tr[:,k] = (Xl_tr[:,k]-mea_l[k])/sig_l[k] mea_h = np.zeros(P) sig_h = np.zeros(P) for k in range(P): mea_h[k] = np.mean(Xh_tr[:,k]) sig_h[k] = np.std(Xh_tr[:,k]) Xh_tr[:,k] = (Xh_tr[:,k]-mea_h[k])/sig_h[k] return (Xl_tr, mea_l, sig_l, Xh_tr,mea_h,sig_h) ####################### RIDGE REGRESSION ###################################### def RR_cv_estimate_alpha(sspacing, tspacing, alphas): """ Estimate the optimal regularization parameter using grid search from a list and via k-fold cross validation Parameters ---------- sspacing : 2D subsampling ratio in space (in one direction) tspacing : 1D subsampling ratio in time alphas : list of regularization parameters to do grid search """ #Load all training data (Xl_tr, mea_l, sig_l, Xh_tr,mea_h,sig_h) = data_preprocess(sspacing, tspacing) # RidgeCV from sklearn.linear_model import RidgeCV ridge = RidgeCV(alphas = alphas, cv = 10, fit_intercept=False, normalize=False) ridge.fit(Xl_tr, Xh_tr) RR_alpha_opt = ridge.alpha_ print('\n Optimal lambda:', RR_alpha_opt) # save to .mat file import scipy.io as io filename = "".join(['/data/PhDworks/isotropic/regerssion/RR_cv_alpha_sspacing', str(sspacing),'_tspacing',str(tspacing),'.mat']) io.savemat(filename, dict(alphas=alphas, RR_alpha_opt=RR_alpha_opt)) # return return RR_alpha_opt def RR_allfields(sspacing, tspacing, RR_alpha_opt): """ Reconstruct all fields using RR and save to netcdf file Parameters ---------- sspacing : 2D subsampling ratio in space (in one direction) tspacing : 1D subsampling ratio in time RR_alpha_opt : optimal regularization parameter given from RR_cv_estimate_alpha(sspacing, tspacing, alphas) """ # Constants Nh = 96 Nt = 37 #Load all training data (Xl_tr, mea_l, sig_l, Xh_tr,mea_h,sig_h) = data_preprocess(sspacing, tspacing) # Ridge Regression from sklearn.linear_model import Ridge ridge = Ridge(alpha=RR_alpha_opt, fit_intercept=False, normalize=False) ridge.fit(Xl_tr, Xh_tr) print np.shape(ridge.coef_) # Prediction and save to file filename = "".join(['/data/PhDworks/isotropic/regerssion/RR_sspacing', str(sspacing),'_tspacing',str(tspacing),'.nc']) import os try: os.remove(filename) except OSError: pass ncfile2 = Dataset(filename, 'w') ncfile1 = Dataset('/data/PhDworks/isotropic/refdata_downsampled4.nc','r') # create the dimensions ncfile2.createDimension('Nt',Nt) ncfile2.createDimension('Nz',Nh) ncfile2.createDimension('Ny',Nh) ncfile2.createDimension('Nx',Nh) # create the var and its attribute var = ncfile2.createVariable('Urec', 'd',('Nt','Nz','Ny','Nx')) for t in range(Nt): print('3D snapshot:',t) for i in range(Nh): xl = np.array(ncfile1.variables['velocity_x'][t,0:Nh:sspacing,0:Nh:sspacing,i]) # load only LR xl = np.divide(np.reshape(xl,(1, xl.size)) - mea_l, sig_l) #pre-normalize xrec = np.multiply(ridge.predict(xl), sig_h) + mea_h # re-normalize the prediction var[t,:,:,i] = np.reshape(xrec, (Nh,Nh)) # put to netcdf file # Close file ncfile1.close() ncfile2.close() def RR_validationcurve(sspacing, tspacing, RR_lambda_opt, lambdas_range): """ Reconstruct all fields using RR and save to netcdf file Parameters ---------- sspacing : 2D subsampling ratio in space (in one direction) tspacing : 1D subsampling ratio in time RR_alpha_opt : optimal regularization parameter given from RR_cv_estimate_alpha(sspacing, tspacing, alphas) """ # lambdas_range= np.logspace(-2, 4, 28) #Load all training data (Xl_tr, mea_l, sig_l, Xh_tr,mea_h,sig_h) = data_preprocess(sspacing, tspacing) # validation curve from sklearn.linear_model import Ridge from sklearn.learning_curve import validation_curve train_MSE, test_MSE = validation_curve(Ridge(),Xl_tr, Xh_tr, param_name="alpha", param_range=lambdas_range, scoring = "mean_squared_error", cv=10) # API always tries to maximize a loss function, so MSE is actually in the flipped sign train_MSE = -train_MSE test_MSE = -test_MSE # save to .mat file import scipy.io as sio sio.savemat('/data/PhDworks/isotropic/regerssion/RR_crossvalidation.mat', dict(lambdas_range=lambdas_range, train_MSE = train_MSE, test_MSE = test_MSE)) return (train_MSE, test_MSE) def RR_learningcurve(sspacing, tspacing, RR_lambda_opt, train_sizes): # train_sizes=np.linspace(.1, 1.0, 20) #Load all training data (Xl_tr, mea_l, sig_l, Xh_tr,mea_h,sig_h) = data_preprocess(sspacing, tspacing) # Learning curve from sklearn.linear_model import Ridge from sklearn.learning_curve import learning_curve from sklearn import cross_validation estimator = Ridge(alpha=RR_lambda_opt, fit_intercept=False, normalize=False) cv = cross_validation.ShuffleSplit(np.shape(Xl_tr)[0], n_iter=50, test_size=0.1, random_state=0) train_sizes, train_MSE, test_MSE = learning_curve(estimator, Xl_tr, Xh_tr, cv=cv, n_jobs=4, train_sizes = train_sizes, scoring = "mean_squared_error") # save to .mat file import scipy.io as sio sio.savemat('/data/PhDworks/isotropic/regerssion/RR_learningcurve.mat', dict(train_sizes=train_sizes, train_MSE = -train_MSE, test_MSE = -test_MSE)) ####################### OTHER FUNCTIONS ####################################### def plot_learning_curve(estimator, plt, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): """ Generate a simple plot of the test and traning learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. plt : current matplotlib plot X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. ylim : tuple, shape (ymin, ymax), optional Defines minimum and maximum yvalues plotted. cv : integer, cross-validation generator, optional If an integer is passed, it is the number of folds (defaults to 3). Specific cross-validation objects can be passed, see sklearn.cross_validation module for the list of possible objects n_jobs : integer, optional Number of jobs to run in parallel (default 1). """ if ylim is not None: plt.ylim(*ylim) plt.xlabel("Number of training examples") plt.ylabel("Score") from sklearn.learning_curve import learning_curve train_sizes, train_scores, test_scores = learning_curve(estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") plt.grid() plt.legend(loc="best") return plt def interp2 (x, y, z, xnew, ynew, kind='cubic'): from scipy import interpolate f = interpolate.interp2d(x, y, z, kind=kind) return f(xnew, ynew) def NRMSE (xref, xrec): err = np.sqrt(np.sum(np.square(xref.ravel()-xrec.ravel())))/np.sqrt(np.sum(np.square(xref.ravel()))) return err
mit
bthirion/scikit-learn
sklearn/manifold/setup.py
43
1283
import os from os.path import join import numpy from numpy.distutils.misc_util import Configuration from sklearn._build_utils import get_blas_info def configuration(parent_package="", top_path=None): config = Configuration("manifold", parent_package, top_path) libraries = [] if os.name == 'posix': libraries.append('m') config.add_extension("_utils", sources=["_utils.pyx"], include_dirs=[numpy.get_include()], libraries=libraries, extra_compile_args=["-O3"]) cblas_libs, blas_info = get_blas_info() eca = blas_info.pop('extra_compile_args', []) eca.append("-O4") config.add_extension("_barnes_hut_tsne", libraries=cblas_libs, sources=["_barnes_hut_tsne.pyx"], include_dirs=[join('..', 'src', 'cblas'), numpy.get_include(), blas_info.pop('include_dirs', [])], extra_compile_args=eca, **blas_info) config.add_subpackage('tests') return config if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration().todict())
bsd-3-clause
rajat1994/scikit-learn
sklearn/datasets/__init__.py
176
3671
""" The :mod:`sklearn.datasets` module includes utilities to load datasets, including methods to load and fetch popular reference datasets. It also features some artificial data generators. """ from .base import load_diabetes from .base import load_digits from .base import load_files from .base import load_iris from .base import load_linnerud from .base import load_boston from .base import get_data_home from .base import clear_data_home from .base import load_sample_images from .base import load_sample_image from .covtype import fetch_covtype from .mlcomp import load_mlcomp from .lfw import load_lfw_pairs from .lfw import load_lfw_people from .lfw import fetch_lfw_pairs from .lfw import fetch_lfw_people from .twenty_newsgroups import fetch_20newsgroups from .twenty_newsgroups import fetch_20newsgroups_vectorized from .mldata import fetch_mldata, mldata_filename from .samples_generator import make_classification from .samples_generator import make_multilabel_classification from .samples_generator import make_hastie_10_2 from .samples_generator import make_regression from .samples_generator import make_blobs from .samples_generator import make_moons from .samples_generator import make_circles from .samples_generator import make_friedman1 from .samples_generator import make_friedman2 from .samples_generator import make_friedman3 from .samples_generator import make_low_rank_matrix from .samples_generator import make_sparse_coded_signal from .samples_generator import make_sparse_uncorrelated from .samples_generator import make_spd_matrix from .samples_generator import make_swiss_roll from .samples_generator import make_s_curve from .samples_generator import make_sparse_spd_matrix from .samples_generator import make_gaussian_quantiles from .samples_generator import make_biclusters from .samples_generator import make_checkerboard from .svmlight_format import load_svmlight_file from .svmlight_format import load_svmlight_files from .svmlight_format import dump_svmlight_file from .olivetti_faces import fetch_olivetti_faces from .species_distributions import fetch_species_distributions from .california_housing import fetch_california_housing from .rcv1 import fetch_rcv1 __all__ = ['clear_data_home', 'dump_svmlight_file', 'fetch_20newsgroups', 'fetch_20newsgroups_vectorized', 'fetch_lfw_pairs', 'fetch_lfw_people', 'fetch_mldata', 'fetch_olivetti_faces', 'fetch_species_distributions', 'fetch_california_housing', 'fetch_covtype', 'fetch_rcv1', 'get_data_home', 'load_boston', 'load_diabetes', 'load_digits', 'load_files', 'load_iris', 'load_lfw_pairs', 'load_lfw_people', 'load_linnerud', 'load_mlcomp', 'load_sample_image', 'load_sample_images', 'load_svmlight_file', 'load_svmlight_files', 'make_biclusters', 'make_blobs', 'make_circles', 'make_classification', 'make_checkerboard', 'make_friedman1', 'make_friedman2', 'make_friedman3', 'make_gaussian_quantiles', 'make_hastie_10_2', 'make_low_rank_matrix', 'make_moons', 'make_multilabel_classification', 'make_regression', 'make_s_curve', 'make_sparse_coded_signal', 'make_sparse_spd_matrix', 'make_sparse_uncorrelated', 'make_spd_matrix', 'make_swiss_roll', 'mldata_filename']
bsd-3-clause
heli522/scikit-learn
examples/linear_model/plot_robust_fit.py
238
2414
""" Robust linear estimator fitting =============================== Here a sine function is fit with a polynomial of order 3, for values close to zero. Robust fitting is demoed in different situations: - No measurement errors, only modelling errors (fitting a sine with a polynomial) - Measurement errors in X - Measurement errors in y The median absolute deviation to non corrupt new data is used to judge the quality of the prediction. What we can see that: - RANSAC is good for strong outliers in the y direction - TheilSen is good for small outliers, both in direction X and y, but has a break point above which it performs worst than OLS. """ from matplotlib import pyplot as plt import numpy as np from sklearn import linear_model, metrics from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline np.random.seed(42) X = np.random.normal(size=400) y = np.sin(X) # Make sure that it X is 2D X = X[:, np.newaxis] X_test = np.random.normal(size=200) y_test = np.sin(X_test) X_test = X_test[:, np.newaxis] y_errors = y.copy() y_errors[::3] = 3 X_errors = X.copy() X_errors[::3] = 3 y_errors_large = y.copy() y_errors_large[::3] = 10 X_errors_large = X.copy() X_errors_large[::3] = 10 estimators = [('OLS', linear_model.LinearRegression()), ('Theil-Sen', linear_model.TheilSenRegressor(random_state=42)), ('RANSAC', linear_model.RANSACRegressor(random_state=42)), ] x_plot = np.linspace(X.min(), X.max()) for title, this_X, this_y in [ ('Modeling errors only', X, y), ('Corrupt X, small deviants', X_errors, y), ('Corrupt y, small deviants', X, y_errors), ('Corrupt X, large deviants', X_errors_large, y), ('Corrupt y, large deviants', X, y_errors_large)]: plt.figure(figsize=(5, 4)) plt.plot(this_X[:, 0], this_y, 'k+') for name, estimator in estimators: model = make_pipeline(PolynomialFeatures(3), estimator) model.fit(this_X, this_y) mse = metrics.mean_squared_error(model.predict(X_test), y_test) y_plot = model.predict(x_plot[:, np.newaxis]) plt.plot(x_plot, y_plot, label='%s: error = %.3f' % (name, mse)) plt.legend(loc='best', frameon=False, title='Error: mean absolute deviation\n to non corrupt data') plt.xlim(-4, 10.2) plt.ylim(-2, 10.2) plt.title(title) plt.show()
bsd-3-clause
466152112/scikit-learn
sklearn/svm/tests/test_svm.py
116
31653
""" Testing for Support Vector Machine module (sklearn.svm) TODO: remove hard coded numerical results when possible """ import numpy as np import itertools from numpy.testing import assert_array_equal, assert_array_almost_equal from numpy.testing import assert_almost_equal from scipy import sparse from nose.tools import assert_raises, assert_true, assert_equal, assert_false from sklearn.base import ChangedBehaviorWarning from sklearn import svm, linear_model, datasets, metrics, base from sklearn.cross_validation import train_test_split from sklearn.datasets import make_classification, make_blobs from sklearn.metrics import f1_score from sklearn.metrics.pairwise import rbf_kernel from sklearn.utils import check_random_state from sklearn.utils import ConvergenceWarning from sklearn.utils.validation import NotFittedError from sklearn.utils.testing import assert_greater, assert_in, assert_less from sklearn.utils.testing import assert_raises_regexp, assert_warns from sklearn.utils.testing import assert_warns_message, assert_raise_message from sklearn.utils.testing import ignore_warnings # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] Y = [1, 1, 1, 2, 2, 2] T = [[-1, -1], [2, 2], [3, 2]] true_result = [1, 2, 2] # also load the iris dataset iris = datasets.load_iris() rng = check_random_state(42) perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] def test_libsvm_parameters(): # Test parameters on classes that make use of libsvm. clf = svm.SVC(kernel='linear').fit(X, Y) assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.support_, [1, 3]) assert_array_equal(clf.support_vectors_, (X[1], X[3])) assert_array_equal(clf.intercept_, [0.]) assert_array_equal(clf.predict(X), Y) def test_libsvm_iris(): # Check consistency on dataset 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_greater(np.mean(clf.predict(iris.data) == iris.target), 0.9) assert_array_equal(clf.classes_, np.sort(clf.classes_)) # 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_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_greater(np.mean(pred == iris.target), .95) pred = svm.libsvm.cross_validation(iris.data, iris.target.astype(np.float64), 5, kernel='linear', random_seed=0) assert_greater(np.mean(pred == iris.target), .95) # If random_seed >= 0, the libsvm rng is seeded (by calling `srand`), hence # we should get deteriministic results (assuming that there is no other # thread calling this wrapper calling `srand` concurrently). pred2 = svm.libsvm.cross_validation(iris.data, iris.target.astype(np.float64), 5, kernel='linear', random_seed=0) assert_array_equal(pred, pred2) def test_single_sample_1d(): # Test whether SVCs work on a single sample given as a 1-d array clf = svm.SVC().fit(X, Y) clf.predict(X[0]) clf = svm.LinearSVC(random_state=0).fit(X, Y) clf.predict(X[0]) def test_precomputed(): # SVC with a precomputed kernel. # We test it with a toy dataset and with iris. clf = svm.SVC(kernel='precomputed') # Gram matrix for train data (square matrix) # (we use just a linear kernel) K = np.dot(X, np.array(X).T) clf.fit(K, Y) # Gram matrix for test data (rectangular matrix) KT = np.dot(T, np.array(X).T) pred = clf.predict(KT) assert_raises(ValueError, clf.predict, KT.T) assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.support_, [1, 3]) assert_array_equal(clf.intercept_, [0]) assert_array_almost_equal(clf.support_, [1, 3]) assert_array_equal(pred, true_result) # Gram matrix for test data but compute KT[i,j] # for support vectors j only. KT = np.zeros_like(KT) for i in range(len(T)): for j in clf.support_: KT[i, j] = np.dot(T[i], X[j]) pred = clf.predict(KT) assert_array_equal(pred, true_result) # same as before, but using a callable function instead of the kernel # matrix. kernel is just a linear kernel kfunc = lambda x, y: np.dot(x, y.T) clf = svm.SVC(kernel=kfunc) clf.fit(X, Y) pred = clf.predict(T) assert_array_equal(clf.dual_coef_, [[-0.25, .25]]) assert_array_equal(clf.intercept_, [0]) assert_array_almost_equal(clf.support_, [1, 3]) assert_array_equal(pred, true_result) # test a precomputed kernel with the iris dataset # and check parameters against a linear SVC clf = svm.SVC(kernel='precomputed') clf2 = svm.SVC(kernel='linear') K = np.dot(iris.data, iris.data.T) clf.fit(K, iris.target) clf2.fit(iris.data, iris.target) pred = clf.predict(K) assert_array_almost_equal(clf.support_, clf2.support_) assert_array_almost_equal(clf.dual_coef_, clf2.dual_coef_) assert_array_almost_equal(clf.intercept_, clf2.intercept_) assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2) # Gram matrix for test data but compute KT[i,j] # for support vectors j only. K = np.zeros_like(K) for i in range(len(iris.data)): for j in clf.support_: K[i, j] = np.dot(iris.data[i], iris.data[j]) pred = clf.predict(K) assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2) clf = svm.SVC(kernel=kfunc) clf.fit(iris.data, iris.target) assert_almost_equal(np.mean(pred == iris.target), .99, decimal=2) def test_svr(): # Test Support Vector Regression diabetes = datasets.load_diabetes() 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.), svm.LinearSVR(C=10.), svm.LinearSVR(C=10.), ): clf.fit(diabetes.data, diabetes.target) assert_greater(clf.score(diabetes.data, diabetes.target), 0.02) # non-regression test; previously, BaseLibSVM would check that # len(np.unique(y)) < 2, which must only be done for SVC svm.SVR().fit(diabetes.data, np.ones(len(diabetes.data))) svm.LinearSVR().fit(diabetes.data, np.ones(len(diabetes.data))) def test_linearsvr(): # check that SVR(kernel='linear') and LinearSVC() give # comparable results diabetes = datasets.load_diabetes() lsvr = svm.LinearSVR(C=1e3).fit(diabetes.data, diabetes.target) score1 = lsvr.score(diabetes.data, diabetes.target) svr = svm.SVR(kernel='linear', C=1e3).fit(diabetes.data, diabetes.target) score2 = svr.score(diabetes.data, diabetes.target) assert np.linalg.norm(lsvr.coef_ - svr.coef_) / np.linalg.norm(svr.coef_) < .1 assert np.abs(score1 - score2) < 0.1 def test_svr_errors(): X = [[0.0], [1.0]] y = [0.0, 0.5] # Bad kernel clf = svm.SVR(kernel=lambda x, y: np.array([[1.0]])) clf.fit(X, y) assert_raises(ValueError, clf.predict, X) def test_oneclass(): # Test OneClassSVM clf = svm.OneClassSVM() clf.fit(X) pred = clf.predict(T) assert_array_almost_equal(pred, [-1, -1, -1]) assert_array_almost_equal(clf.intercept_, [-1.008], decimal=3) assert_array_almost_equal(clf.dual_coef_, [[0.632, 0.233, 0.633, 0.234, 0.632, 0.633]], decimal=3) assert_raises(ValueError, lambda: clf.coef_) def test_oneclass_decision_function(): # Test OneClassSVM decision function clf = svm.OneClassSVM() rnd = check_random_state(2) # Generate train data X = 0.3 * rnd.randn(100, 2) X_train = np.r_[X + 2, X - 2] # Generate some regular novel observations X = 0.3 * rnd.randn(20, 2) X_test = np.r_[X + 2, X - 2] # Generate some abnormal novel observations X_outliers = rnd.uniform(low=-4, high=4, size=(20, 2)) # fit the model clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1) clf.fit(X_train) # predict things y_pred_test = clf.predict(X_test) assert_greater(np.mean(y_pred_test == 1), .9) y_pred_outliers = clf.predict(X_outliers) 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) assert_array_equal((dec_func_outliers > 0).ravel(), y_pred_outliers == 1) def test_tweak_params(): # Make sure some tweaking of parameters works. # We change clf.dual_coef_ at run time and expect .predict() to change # accordingly. Notice that this is not trivial since it involves a lot # of C/Python copying in the libsvm bindings. # The success of this test ensures that the mapping between libsvm and # the python classifier is complete. clf = svm.SVC(kernel='linear', C=1.0) clf.fit(X, Y) assert_array_equal(clf.dual_coef_, [[-.25, .25]]) assert_array_equal(clf.predict([[-.1, -.1]]), [1]) clf._dual_coef_ = np.array([[.0, 1.]]) assert_array_equal(clf.predict([[-.1, -.1]]), [2]) def test_probability(): # Predict probabilities using SVC # This uses cross validation, so we use a slightly bigger testing set. for clf in (svm.SVC(probability=True, random_state=0, C=1.0), svm.NuSVC(probability=True, random_state=0)): clf.fit(iris.data, iris.target) prob_predict = clf.predict_proba(iris.data) assert_array_almost_equal( np.sum(prob_predict, 1), np.ones(iris.data.shape[0])) assert_true(np.mean(np.argmax(prob_predict, 1) == clf.predict(iris.data)) > 0.9) assert_almost_equal(clf.predict_proba(iris.data), np.exp(clf.predict_log_proba(iris.data)), 8) def test_decision_function(): # Test decision_function # Sanity check, test that decision_function implemented in python # returns the same as the one in libsvm # multi class: clf = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovo').fit(iris.data, iris.target) dec = np.dot(iris.data, clf.coef_.T) + clf.intercept_ assert_array_almost_equal(dec, clf.decision_function(iris.data)) # binary: clf.fit(X, Y) dec = np.dot(X, clf.coef_.T) + clf.intercept_ prediction = clf.predict(X) assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) assert_array_almost_equal( prediction, clf.classes_[(clf.decision_function(X) > 0).astype(np.int)]) expected = np.array([-1., -0.66, -1., 0.66, 1., 1.]) assert_array_almost_equal(clf.decision_function(X), expected, 2) # kernel binary: clf = svm.SVC(kernel='rbf', gamma=1, decision_function_shape='ovo') clf.fit(X, Y) rbfs = rbf_kernel(X, clf.support_vectors_, gamma=clf.gamma) dec = np.dot(rbfs, clf.dual_coef_.T) + clf.intercept_ assert_array_almost_equal(dec.ravel(), clf.decision_function(X)) def test_decision_function_shape(): # check that decision_function_shape='ovr' gives # correct shape and is consistent with predict clf = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovr').fit(iris.data, iris.target) dec = clf.decision_function(iris.data) assert_equal(dec.shape, (len(iris.data), 3)) assert_array_equal(clf.predict(iris.data), np.argmax(dec, axis=1)) # with five classes: X, y = make_blobs(n_samples=80, centers=5, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovr').fit(X_train, y_train) dec = clf.decision_function(X_test) assert_equal(dec.shape, (len(X_test), 5)) assert_array_equal(clf.predict(X_test), np.argmax(dec, axis=1)) # check shape of ovo_decition_function=True clf = svm.SVC(kernel='linear', C=0.1, decision_function_shape='ovo').fit(X_train, y_train) dec = clf.decision_function(X_train) assert_equal(dec.shape, (len(X_train), 10)) # check deprecation warning clf.decision_function_shape = None msg = "change the shape of the decision function" dec = assert_warns_message(ChangedBehaviorWarning, msg, clf.decision_function, X_train) assert_equal(dec.shape, (len(X_train), 10)) def test_svr_decision_function(): # Test SVR's decision_function # Sanity check, test that decision_function implemented in python # returns the same as the one in libsvm X = iris.data y = iris.target # linear kernel reg = svm.SVR(kernel='linear', C=0.1).fit(X, y) dec = np.dot(X, reg.coef_.T) + reg.intercept_ assert_array_almost_equal(dec.ravel(), reg.decision_function(X).ravel()) # rbf kernel reg = svm.SVR(kernel='rbf', gamma=1).fit(X, y) rbfs = rbf_kernel(X, reg.support_vectors_, gamma=reg.gamma) dec = np.dot(rbfs, reg.dual_coef_.T) + reg.intercept_ assert_array_almost_equal(dec.ravel(), reg.decision_function(X).ravel()) def test_weight(): # Test class weights clf = svm.SVC(class_weight={1: 0.1}) # we give a small weights to class 1 clf.fit(X, Y) # so all predicted values belong to class 2 assert_array_almost_equal(clf.predict(X), [2] * 6) X_, y_ = make_classification(n_samples=200, n_features=10, weights=[0.833, 0.167], random_state=2) for clf in (linear_model.LogisticRegression(), svm.LinearSVC(random_state=0), svm.SVC()): clf.set_params(class_weight={0: .1, 1: 10}) clf.fit(X_[:100], y_[:100]) y_pred = clf.predict(X_[100:]) assert_true(f1_score(y_[100:], y_pred) > .3) def test_sample_weights(): # Test weights on individual samples # TODO: check on NuSVR, OneClass, etc. clf = svm.SVC() clf.fit(X, Y) assert_array_equal(clf.predict(X[2]), [1.]) sample_weight = [.1] * 3 + [10] * 3 clf.fit(X, Y, sample_weight=sample_weight) assert_array_equal(clf.predict(X[2]), [2.]) # test that rescaling all samples is the same as changing C clf = svm.SVC() clf.fit(X, Y) dual_coef_no_weight = clf.dual_coef_ clf.set_params(C=100) clf.fit(X, Y, sample_weight=np.repeat(0.01, len(X))) assert_array_almost_equal(dual_coef_no_weight, clf.dual_coef_) def test_auto_weight(): # Test class weights for imbalanced data from sklearn.linear_model import LogisticRegression # We take as dataset the two-dimensional projection of iris so # that it is not separable and remove half of predictors from # class 1. # We add one to the targets as a non-regression test: class_weight="balanced" # used to work only when the labels where a range [0..K). from sklearn.utils import compute_class_weight X, y = iris.data[:, :2], iris.target + 1 unbalanced = np.delete(np.arange(y.size), np.where(y > 2)[0][::2]) classes = np.unique(y[unbalanced]) class_weights = compute_class_weight('balanced', classes, y[unbalanced]) assert_true(np.argmax(class_weights) == 2) for clf in (svm.SVC(kernel='linear'), svm.LinearSVC(random_state=0), LogisticRegression()): # check that score is better when class='balanced' is set. y_pred = clf.fit(X[unbalanced], y[unbalanced]).predict(X) clf.set_params(class_weight='balanced') y_pred_balanced = clf.fit(X[unbalanced], y[unbalanced],).predict(X) assert_true(metrics.f1_score(y, y_pred, average='weighted') <= metrics.f1_score(y, y_pred_balanced, average='weighted')) def test_bad_input(): # Test that it gives proper exception on deficient input # impossible value of C assert_raises(ValueError, svm.SVC(C=-1).fit, X, Y) # impossible value of nu clf = svm.NuSVC(nu=0.0) assert_raises(ValueError, clf.fit, X, Y) Y2 = Y[:-1] # wrong dimensions for labels assert_raises(ValueError, clf.fit, X, Y2) # Test with arrays that are non-contiguous. for clf in (svm.SVC(), svm.LinearSVC(random_state=0)): Xf = np.asfortranarray(X) assert_false(Xf.flags['C_CONTIGUOUS']) yf = np.ascontiguousarray(np.tile(Y, (2, 1)).T) yf = yf[:, -1] assert_false(yf.flags['F_CONTIGUOUS']) assert_false(yf.flags['C_CONTIGUOUS']) clf.fit(Xf, yf) assert_array_equal(clf.predict(T), true_result) # error for precomputed kernelsx clf = svm.SVC(kernel='precomputed') assert_raises(ValueError, clf.fit, X, Y) # sample_weight bad dimensions clf = svm.SVC() assert_raises(ValueError, clf.fit, X, Y, sample_weight=range(len(X) - 1)) # predict with sparse input when trained with dense clf = svm.SVC().fit(X, Y) assert_raises(ValueError, clf.predict, sparse.lil_matrix(X)) Xt = np.array(X).T clf.fit(np.dot(X, Xt), Y) assert_raises(ValueError, clf.predict, X) clf = svm.SVC() clf.fit(X, Y) assert_raises(ValueError, clf.predict, Xt) def test_sparse_precomputed(): clf = svm.SVC(kernel='precomputed') sparse_gram = sparse.csr_matrix([[1, 0], [0, 1]]) try: clf.fit(sparse_gram, [0, 1]) assert not "reached" except TypeError as e: assert_in("Sparse precomputed", str(e)) def test_linearsvc_parameters(): # Test possible parameter combinations in LinearSVC # Generate list of possible parameter combinations losses = ['hinge', 'squared_hinge', 'logistic_regression', 'foo'] penalties, duals = ['l1', 'l2', 'bar'], [True, False] X, y = make_classification(n_samples=5, n_features=5) for loss, penalty, dual in itertools.product(losses, penalties, duals): clf = svm.LinearSVC(penalty=penalty, loss=loss, dual=dual) if ((loss, penalty) == ('hinge', 'l1') or (loss, penalty, dual) == ('hinge', 'l2', False) or (penalty, dual) == ('l1', True) or loss == 'foo' or penalty == 'bar'): assert_raises_regexp(ValueError, "Unsupported set of arguments.*penalty='%s.*" "loss='%s.*dual=%s" % (penalty, loss, dual), clf.fit, X, y) else: clf.fit(X, y) # Incorrect loss value - test if explicit error message is raised assert_raises_regexp(ValueError, ".*loss='l3' is not supported.*", svm.LinearSVC(loss="l3").fit, X, y) # FIXME remove in 1.0 def test_linearsvx_loss_penalty_deprecations(): X, y = [[0.0], [1.0]], [0, 1] msg = ("loss='%s' has been deprecated in favor of " "loss='%s' as of 0.16. Backward compatibility" " for the %s will be removed in %s") # LinearSVC # loss l1/L1 --> hinge assert_warns_message(DeprecationWarning, msg % ("l1", "hinge", "loss='l1'", "1.0"), svm.LinearSVC(loss="l1").fit, X, y) # loss l2/L2 --> squared_hinge assert_warns_message(DeprecationWarning, msg % ("L2", "squared_hinge", "loss='L2'", "1.0"), svm.LinearSVC(loss="L2").fit, X, y) # LinearSVR # loss l1/L1 --> epsilon_insensitive assert_warns_message(DeprecationWarning, msg % ("L1", "epsilon_insensitive", "loss='L1'", "1.0"), svm.LinearSVR(loss="L1").fit, X, y) # loss l2/L2 --> squared_epsilon_insensitive assert_warns_message(DeprecationWarning, msg % ("l2", "squared_epsilon_insensitive", "loss='l2'", "1.0"), svm.LinearSVR(loss="l2").fit, X, y) # FIXME remove in 0.18 def test_linear_svx_uppercase_loss_penalty(): # Check if Upper case notation is supported by _fit_liblinear # which is called by fit X, y = [[0.0], [1.0]], [0, 1] msg = ("loss='%s' has been deprecated in favor of " "loss='%s' as of 0.16. Backward compatibility" " for the uppercase notation will be removed in %s") # loss SQUARED_hinge --> squared_hinge assert_warns_message(DeprecationWarning, msg % ("SQUARED_hinge", "squared_hinge", "0.18"), svm.LinearSVC(loss="SQUARED_hinge").fit, X, y) # penalty L2 --> l2 assert_warns_message(DeprecationWarning, msg.replace("loss", "penalty") % ("L2", "l2", "0.18"), svm.LinearSVC(penalty="L2").fit, X, y) # loss EPSILON_INSENSITIVE --> epsilon_insensitive assert_warns_message(DeprecationWarning, msg % ("EPSILON_INSENSITIVE", "epsilon_insensitive", "0.18"), svm.LinearSVR(loss="EPSILON_INSENSITIVE").fit, X, y) def test_linearsvc(): # Test basic routines using LinearSVC clf = svm.LinearSVC(random_state=0).fit(X, Y) # by default should have intercept assert_true(clf.fit_intercept) assert_array_equal(clf.predict(T), true_result) assert_array_almost_equal(clf.intercept_, [0], decimal=3) # the same with l1 penalty clf = svm.LinearSVC(penalty='l1', loss='squared_hinge', dual=False, random_state=0).fit(X, Y) assert_array_equal(clf.predict(T), true_result) # l2 penalty with dual formulation clf = svm.LinearSVC(penalty='l2', dual=True, random_state=0).fit(X, Y) assert_array_equal(clf.predict(T), true_result) # l2 penalty, l1 loss clf = svm.LinearSVC(penalty='l2', loss='hinge', dual=True, random_state=0) clf.fit(X, Y) assert_array_equal(clf.predict(T), true_result) # test also decision function dec = clf.decision_function(T) res = (dec > 0).astype(np.int) + 1 assert_array_equal(res, true_result) def test_linearsvc_crammer_singer(): # Test LinearSVC with crammer_singer multi-class svm ovr_clf = svm.LinearSVC(random_state=0).fit(iris.data, iris.target) cs_clf = svm.LinearSVC(multi_class='crammer_singer', random_state=0) cs_clf.fit(iris.data, iris.target) # similar prediction for ovr and crammer-singer: assert_true((ovr_clf.predict(iris.data) == cs_clf.predict(iris.data)).mean() > .9) # classifiers shouldn't be the same assert_true((ovr_clf.coef_ != cs_clf.coef_).all()) # test decision function assert_array_equal(cs_clf.predict(iris.data), np.argmax(cs_clf.decision_function(iris.data), axis=1)) dec_func = np.dot(iris.data, cs_clf.coef_.T) + cs_clf.intercept_ assert_array_almost_equal(dec_func, cs_clf.decision_function(iris.data)) def test_crammer_singer_binary(): # Test Crammer-Singer formulation in the binary case X, y = make_classification(n_classes=2, random_state=0) for fit_intercept in (True, False): acc = svm.LinearSVC(fit_intercept=fit_intercept, multi_class="crammer_singer", random_state=0).fit(X, y).score(X, y) assert_greater(acc, 0.9) def test_linearsvc_iris(): # Test that LinearSVC gives plausible predictions on the iris dataset # Also, test symbolic class names (classes_). target = iris.target_names[iris.target] clf = svm.LinearSVC(random_state=0).fit(iris.data, target) assert_equal(set(clf.classes_), set(iris.target_names)) assert_greater(np.mean(clf.predict(iris.data) == target), 0.8) dec = clf.decision_function(iris.data) pred = iris.target_names[np.argmax(dec, 1)] assert_array_equal(pred, clf.predict(iris.data)) def test_dense_liblinear_intercept_handling(classifier=svm.LinearSVC): # Test that dense liblinear honours intercept_scaling param X = [[2, 1], [3, 1], [1, 3], [2, 3]] y = [0, 0, 1, 1] clf = classifier(fit_intercept=True, penalty='l1', loss='squared_hinge', dual=False, C=4, tol=1e-7, random_state=0) assert_true(clf.intercept_scaling == 1, clf.intercept_scaling) assert_true(clf.fit_intercept) # when intercept_scaling is low the intercept value is highly "penalized" # by regularization clf.intercept_scaling = 1 clf.fit(X, y) assert_almost_equal(clf.intercept_, 0, decimal=5) # when intercept_scaling is sufficiently high, the intercept value # is not affected by regularization clf.intercept_scaling = 100 clf.fit(X, y) intercept1 = clf.intercept_ assert_less(intercept1, -1) # when intercept_scaling is sufficiently high, the intercept value # doesn't depend on intercept_scaling value clf.intercept_scaling = 1000 clf.fit(X, y) intercept2 = clf.intercept_ assert_array_almost_equal(intercept1, intercept2, decimal=2) def test_liblinear_set_coef(): # multi-class case clf = svm.LinearSVC().fit(iris.data, iris.target) values = clf.decision_function(iris.data) clf.coef_ = clf.coef_.copy() clf.intercept_ = clf.intercept_.copy() values2 = clf.decision_function(iris.data) assert_array_almost_equal(values, values2) # binary-class case X = [[2, 1], [3, 1], [1, 3], [2, 3]] y = [0, 0, 1, 1] clf = svm.LinearSVC().fit(X, y) values = clf.decision_function(X) clf.coef_ = clf.coef_.copy() clf.intercept_ = clf.intercept_.copy() values2 = clf.decision_function(X) assert_array_equal(values, values2) def test_immutable_coef_property(): # Check that primal coef modification are not silently ignored svms = [ svm.SVC(kernel='linear').fit(iris.data, iris.target), svm.NuSVC(kernel='linear').fit(iris.data, iris.target), svm.SVR(kernel='linear').fit(iris.data, iris.target), svm.NuSVR(kernel='linear').fit(iris.data, iris.target), svm.OneClassSVM(kernel='linear').fit(iris.data), ] for clf in svms: assert_raises(AttributeError, clf.__setattr__, 'coef_', np.arange(3)) assert_raises((RuntimeError, ValueError), clf.coef_.__setitem__, (0, 0), 0) def test_linearsvc_verbose(): # stdout: redirect import os stdout = os.dup(1) # save original stdout os.dup2(os.pipe()[1], 1) # replace it # actual call clf = svm.LinearSVC(verbose=1) clf.fit(X, Y) # stdout: restore os.dup2(stdout, 1) # restore original stdout def test_svc_clone_with_callable_kernel(): # create SVM with callable linear kernel, check that results are the same # as with built-in linear kernel svm_callable = svm.SVC(kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0, decision_function_shape='ovr') # clone for checking clonability with lambda functions.. svm_cloned = base.clone(svm_callable) svm_cloned.fit(iris.data, iris.target) svm_builtin = svm.SVC(kernel='linear', probability=True, random_state=0, decision_function_shape='ovr') svm_builtin.fit(iris.data, iris.target) assert_array_almost_equal(svm_cloned.dual_coef_, svm_builtin.dual_coef_) assert_array_almost_equal(svm_cloned.intercept_, svm_builtin.intercept_) assert_array_equal(svm_cloned.predict(iris.data), svm_builtin.predict(iris.data)) assert_array_almost_equal(svm_cloned.predict_proba(iris.data), svm_builtin.predict_proba(iris.data), decimal=4) assert_array_almost_equal(svm_cloned.decision_function(iris.data), svm_builtin.decision_function(iris.data)) def test_svc_bad_kernel(): svc = svm.SVC(kernel=lambda x, y: x) assert_raises(ValueError, svc.fit, X, Y) def test_timeout(): a = svm.SVC(kernel=lambda x, y: np.dot(x, y.T), probability=True, random_state=0, max_iter=1) assert_warns(ConvergenceWarning, a.fit, X, Y) def test_unfitted(): X = "foo!" # input validation not required when SVM not fitted clf = svm.SVC() assert_raises_regexp(Exception, r".*\bSVC\b.*\bnot\b.*\bfitted\b", clf.predict, X) clf = svm.NuSVR() assert_raises_regexp(Exception, r".*\bNuSVR\b.*\bnot\b.*\bfitted\b", clf.predict, X) # ignore convergence warnings from max_iter=1 @ignore_warnings def test_consistent_proba(): a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_1 = a.fit(X, Y).predict_proba(X) a = svm.SVC(probability=True, max_iter=1, random_state=0) proba_2 = a.fit(X, Y).predict_proba(X) assert_array_almost_equal(proba_1, proba_2) def test_linear_svc_convergence_warnings(): # Test that warnings are raised if model does not converge lsvc = svm.LinearSVC(max_iter=2, verbose=1) assert_warns(ConvergenceWarning, lsvc.fit, X, Y) assert_equal(lsvc.n_iter_, 2) def test_svr_coef_sign(): # Test that SVR(kernel="linear") has coef_ with the right sign. # Non-regression test for #2933. X = np.random.RandomState(21).randn(10, 3) y = np.random.RandomState(12).randn(10) for svr in [svm.SVR(kernel='linear'), svm.NuSVR(kernel='linear'), svm.LinearSVR()]: svr.fit(X, y) assert_array_almost_equal(svr.predict(X), np.dot(X, svr.coef_.ravel()) + svr.intercept_) def test_linear_svc_intercept_scaling(): # Test that the right error message is thrown when intercept_scaling <= 0 for i in [-1, 0]: lsvc = svm.LinearSVC(intercept_scaling=i) msg = ('Intercept scaling is %r but needs to be greater than 0.' ' To disable fitting an intercept,' ' set fit_intercept=False.' % lsvc.intercept_scaling) assert_raise_message(ValueError, msg, lsvc.fit, X, Y) def test_lsvc_intercept_scaling_zero(): # Test that intercept_scaling is ignored when fit_intercept is False lsvc = svm.LinearSVC(fit_intercept=False) lsvc.fit(X, Y) assert_equal(lsvc.intercept_, 0.) def test_hasattr_predict_proba(): # Method must be (un)available before or after fit, switched by # `probability` param G = svm.SVC(probability=True) assert_true(hasattr(G, 'predict_proba')) G.fit(iris.data, iris.target) assert_true(hasattr(G, 'predict_proba')) G = svm.SVC(probability=False) assert_false(hasattr(G, 'predict_proba')) G.fit(iris.data, iris.target) assert_false(hasattr(G, 'predict_proba')) # Switching to `probability=True` after fitting should make # predict_proba available, but calling it must not work: G.probability = True assert_true(hasattr(G, 'predict_proba')) msg = "predict_proba is not available when fitted with probability=False" assert_raise_message(NotFittedError, msg, G.predict_proba, iris.data)
bsd-3-clause
jramcast/ml_weather
example8/preprocessing.py
2
3314
""" Module for preprocessing data before feeding it into the classfier """ import string import re from nltk.stem import SnowballStemmer from nltk.corpus import stopwords from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import MinMaxScaler, Imputer from sklearn.feature_extraction import DictVectorizer from textblob import TextBlob class SentimentExtractor(BaseEstimator, TransformerMixin): """ Extracts sentiment features from tweets """ def __init__(self): pass def transform(self, tweets, y_train=None): samples = [] for tweet in tweets: textBlob = TextBlob(tweet) samples.append({ 'sent_polarity': textBlob.sentiment.polarity, 'sent_subjetivity': textBlob.sentiment.subjectivity }) vectorized = DictVectorizer().fit_transform(samples).toarray() vectorized = Imputer().fit_transform(vectorized) vectorized_scaled = MinMaxScaler().fit_transform(vectorized) return vectorized_scaled def fit(self, X, y=None): return self class TempExtractor(BaseEstimator, TransformerMixin): """ Extracts weather temp from tweet """ def transform(self, tweets, y_train=None): tempetures = [[self.get_temperature(tweet)] for tweet in tweets] vectorized = self.imputer.transform(tempetures) vectorized_scaled = MinMaxScaler().fit_transform(vectorized) return vectorized_scaled def fit(self, tweets, y=None): self.imputer = Imputer() tempetures = [[self.get_temperature(tweet)] for tweet in tweets] self.imputer.fit(tempetures) return self def get_temperature(self, tweet): match = re.search(r'(\d+(\.\d)?)\s*F', tweet, re.IGNORECASE) if match: value = float(match.group(1)) celsius = (value - 32) / 1.8 if - 100 < celsius < 100: return celsius return None class WindExtractor(BaseEstimator, TransformerMixin): """ Extracts wind from tweet """ def transform(self, tweets, y_train=None): winds = [[self.get_wind(tweet)] for tweet in tweets] vectorized = self.imputer.transform(winds) vectorized_scaled = MinMaxScaler().fit_transform(vectorized) return vectorized_scaled def fit(self, tweets, y=None): self.imputer = Imputer() winds = [[self.get_wind(tweet)] for tweet in tweets] self.imputer.fit(winds) return self def get_wind(self, tweet): match = re.search(r'(\d+(\.\d)?)\s*mph', tweet, re.IGNORECASE) if match: value = float(match.group(1)) kph = value * 1.60934 if 0 <= kph < 500: return kph return None stopwords_list = stopwords.words('english') def stem_tokens(tokens, stemmer): stemmer = SnowballStemmer('english') stemmed = [] for item in tokens: stemmed.append(stemmer.stem(item)) return stemmed def tokenize(text): non_words = list(string.punctuation) non_words.extend(['¿', '¡']) text = ''.join([c for c in text if c not in non_words]) sentence = TextBlob(text) tokens = [word.lemmatize() for word in sentence.words] return tokens
apache-2.0
potash/scikit-learn
sklearn/datasets/mlcomp.py
289
3855
# Copyright (c) 2010 Olivier Grisel <[email protected]> # License: BSD 3 clause """Glue code to load http://mlcomp.org data as a scikit.learn dataset""" import os import numbers from sklearn.datasets.base import load_files def _load_document_classification(dataset_path, metadata, set_=None, **kwargs): if set_ is not None: dataset_path = os.path.join(dataset_path, set_) return load_files(dataset_path, metadata.get('description'), **kwargs) LOADERS = { 'DocumentClassification': _load_document_classification, # TODO: implement the remaining domain formats } def load_mlcomp(name_or_id, set_="raw", mlcomp_root=None, **kwargs): """Load a datasets as downloaded from http://mlcomp.org Parameters ---------- name_or_id : the integer id or the string name metadata of the MLComp dataset to load set_ : select the portion to load: 'train', 'test' or 'raw' mlcomp_root : the filesystem path to the root folder where MLComp datasets are stored, if mlcomp_root is None, the MLCOMP_DATASETS_HOME environment variable is looked up instead. **kwargs : domain specific kwargs to be passed to the dataset loader. Read more in the :ref:`User Guide <datasets>`. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'filenames', the files holding the raw to learn, 'target', the classification labels (integer index), 'target_names', the meaning of the labels, and 'DESCR', the full description of the dataset. Note on the lookup process: depending on the type of name_or_id, will choose between integer id lookup or metadata name lookup by looking at the unzipped archives and metadata file. TODO: implement zip dataset loading too """ if mlcomp_root is None: try: mlcomp_root = os.environ['MLCOMP_DATASETS_HOME'] except KeyError: raise ValueError("MLCOMP_DATASETS_HOME env variable is undefined") mlcomp_root = os.path.expanduser(mlcomp_root) mlcomp_root = os.path.abspath(mlcomp_root) mlcomp_root = os.path.normpath(mlcomp_root) if not os.path.exists(mlcomp_root): raise ValueError("Could not find folder: " + mlcomp_root) # dataset lookup if isinstance(name_or_id, numbers.Integral): # id lookup dataset_path = os.path.join(mlcomp_root, str(name_or_id)) else: # assume name based lookup dataset_path = None expected_name_line = "name: " + name_or_id for dataset in os.listdir(mlcomp_root): metadata_file = os.path.join(mlcomp_root, dataset, 'metadata') if not os.path.exists(metadata_file): continue with open(metadata_file) as f: for line in f: if line.strip() == expected_name_line: dataset_path = os.path.join(mlcomp_root, dataset) break if dataset_path is None: raise ValueError("Could not find dataset with metadata line: " + expected_name_line) # loading the dataset metadata metadata = dict() metadata_file = os.path.join(dataset_path, 'metadata') if not os.path.exists(metadata_file): raise ValueError(dataset_path + ' is not a valid MLComp dataset') with open(metadata_file) as f: for line in f: if ":" in line: key, value = line.split(":", 1) metadata[key.strip()] = value.strip() format = metadata.get('format', 'unknow') loader = LOADERS.get(format) if loader is None: raise ValueError("No loader implemented for format: " + format) return loader(dataset_path, metadata, set_=set_, **kwargs)
bsd-3-clause
h2educ/scikit-learn
examples/mixture/plot_gmm_sin.py
248
2747
""" ================================= Gaussian Mixture Model Sine Curve ================================= This example highlights the advantages of the Dirichlet Process: complexity control and dealing with sparse data. The dataset is formed by 100 points loosely spaced following a noisy sine curve. The fit by the GMM class, using the expectation-maximization algorithm to fit a mixture of 10 Gaussian components, finds too-small components and very little structure. The fits by the Dirichlet process, however, show that the model can either learn a global structure for the data (small alpha) or easily interpolate to finding relevant local structure (large alpha), never falling into the problems shown by the GMM class. """ import itertools import numpy as np from scipy import linalg import matplotlib.pyplot as plt import matplotlib as mpl from sklearn import mixture from sklearn.externals.six.moves import xrange # Number of samples per component n_samples = 100 # Generate random sample following a sine curve np.random.seed(0) X = np.zeros((n_samples, 2)) step = 4 * np.pi / n_samples for i in xrange(X.shape[0]): x = i * step - 6 X[i, 0] = x + np.random.normal(0, 0.1) X[i, 1] = 3 * (np.sin(x) + np.random.normal(0, .2)) color_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm']) for i, (clf, title) in enumerate([ (mixture.GMM(n_components=10, covariance_type='full', n_iter=100), "Expectation-maximization"), (mixture.DPGMM(n_components=10, covariance_type='full', alpha=0.01, n_iter=100), "Dirichlet Process,alpha=0.01"), (mixture.DPGMM(n_components=10, covariance_type='diag', alpha=100., n_iter=100), "Dirichlet Process,alpha=100.")]): clf.fit(X) splot = plt.subplot(3, 1, 1 + i) Y_ = clf.predict(X) for i, (mean, covar, color) in enumerate(zip( clf.means_, clf._get_covars(), color_iter)): v, w = linalg.eigh(covar) u = w[0] / linalg.norm(w[0]) # as the DP will not use every component it has access to # unless it needs it, we shouldn't plot the redundant # components. if not np.any(Y_ == i): continue plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) # Plot an ellipse to show the Gaussian component angle = np.arctan(u[1] / u[0]) angle = 180 * angle / np.pi # convert to degrees ell = mpl.patches.Ellipse(mean, v[0], v[1], 180 + angle, color=color) ell.set_clip_box(splot.bbox) ell.set_alpha(0.5) splot.add_artist(ell) plt.xlim(-6, 4 * np.pi - 6) plt.ylim(-5, 5) plt.title(title) plt.xticks(()) plt.yticks(()) plt.show()
bsd-3-clause
nickdex/cosmos
code/artificial_intelligence/src/artificial_neural_network/ann.py
3
1384
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv("dataset.csv") X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) onehotencoder = OneHotEncoder(categorical_features=[1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) import keras from keras.models import Sequential from keras.layers import Dense classifier = Sequential() classifier.add( Dense(units=6, kernel_initializer="uniform", activation="relu", input_dim=11) ) classifier.add(Dense(units=6, kernel_initializer="uniform", activation="relu")) classifier.add(Dense(units=1, kernel_initializer="uniform", activation="sigmoid")) classifier.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"]) classifier.fit(X_train, y_train, batch_size=10, epochs=100) y_pred = classifier.predict(X_test) y_pred = y_pred > 0.5
gpl-3.0
hobson/totalgood
totalgood/pacs/predictor.py
1
4199
#!python manage.py shell_plus < import pandas as pd np = pd.np np.norm = np.linalg.norm import sklearn from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer from sklearn.linear_model import SGDClassifier from sklearn.grid_search import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.cross_validation import train_test_split from pacs.models import RawCommittees pipeline = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', SGDClassifier()), ]) def debug(): import ipdb ipdb.set_trace() class PACClassifier(SGDClassifier): def __init__(self, names=np.array(RawCommittees.objects.values_list('committee_name', flat=True)), labels=RawCommittees.objects.values_list('committee_type', 'committee_subtype'), alpha=1e-5, penalty='l1', verbosity=1, ): """Train a classifier that predicts a committee type, subtype (label) from its name Args: names (array of str): the committee names (space-delimitted words with a few words) labels (array of 2-tuple of str): the committee_type and subtype, Nones/NaNs/floats are stringified alpha (float): learning rate (sklearn TFIDF classifier examples use 1e-5 to 1e-6) default: 1e-5 penalty: 'none', 'l2', 'l1', or 'elasticnet' # regularization penalty on the feature weights Returns: SGDClassifier: Trained SVM classifier instance """ super(PACClassifier, self).__init__(alpha=alpha, penalty=penalty) if verbosity is not None: self.verbosity = verbosity # vectorizer = CountVectorizer(min_df=1) # word_bag = vectorizer.fit_transform(self.names) # print(word_bag) self.names = (names if isinstance(names, (list, np.ndarray)) else RawCommittees.objects.values_list('committee_name', flat=True)) self.pac_type_tuples = RawCommittees.objects.values_list('committee_type', 'committee_subtype') self.labels = np.array(list(labels or self.pac_type_tuples)) # self.labels = [', '.join(str(s) for s in pt) for pt in self.pac_type_tuples] self.labels = np.array([str(lbl) for lbl in self.labels]) self.label_set = sorted(np.unique(self.labels)) self.label_dict = dict(list(zip(self.label_set, range(len(self.label_set))))) self.label_ints = np.array([self.label_dict[label] for label in self.labels]) if self.verbosity > 1: print(pd.Series(self.labels)) if self.verbosity > 0: print(np.unique(self.labels)) self.tfidf = TfidfVectorizer(analyzer='word', ngram_range=(1, 1), stop_words='english') self.tfidf_matrix = self.tfidf.fit_transform(self.names) if verbosity > 1: print(self.tfidf.get_feature_names()) self.train_tfidf, self.test_tfidf, self.train_labels, self.test_labels = train_test_split( self.tfidf_matrix, self.label_ints, test_size=.25) # alpha: learning rate (default 1e-4, but other TFIDF classifier examples use 1e-5 to 1e-6) # penalty: 'none', 'l2', 'l1', or 'elasticnet' # regularization penalty on the feature weights self.svn_matrix = self.fit(self.train_tfidf, self.train_labels) if verbosity > 0: print(self.score(self.train_tfidf, self.train_labels)) # Typically > 98% recall (accuracy on training set) def predict_pac_type(self, name): name = str(name) vec = self.tfidf.transform(name) predicted_label = self.predict(vec) print(predicted_label) return predicted_label def similarity(self, name1, name2): # tfidf is already normalized, so no need to divide by the norm of each vector? vec1, vec2 = self.tfidf.transform(np.array([name1, name2])) # cosine distance between two tfidf vectors return vec1.dot(vec2.T)[0, 0] def similarity_matrix(self): return self.tfidf_matrix * self.tfidf_matrix.T
mit
dsullivan7/scikit-learn
examples/cluster/plot_lena_segmentation.py
271
2444
""" ========================================= Segmenting the picture of Lena in regions ========================================= This example uses :ref:`spectral_clustering` on a graph created from voxel-to-voxel difference on an image to break this image into multiple partly-homogeneous regions. This procedure (spectral clustering on an image) is an efficient approximate solution for finding normalized graph cuts. There are two options to assign labels: * with 'kmeans' spectral clustering will cluster samples in the embedding space using a kmeans algorithm * whereas 'discrete' will iteratively search for the closest partition space to the embedding space. """ print(__doc__) # Author: Gael Varoquaux <[email protected]>, Brian Cheung # License: BSD 3 clause import time import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering lena = sp.misc.lena() # Downsample the image by a factor of 4 lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2] lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2] # Convert the image into a graph with the value of the gradient on the # edges. graph = image.img_to_graph(lena) # Take a decreasing function of the gradient: an exponential # The smaller beta is, the more independent the segmentation is of the # actual image. For beta=1, the segmentation is close to a voronoi beta = 5 eps = 1e-6 graph.data = np.exp(-beta * graph.data / lena.std()) + eps # Apply spectral clustering (this step goes much faster if you have pyamg # installed) N_REGIONS = 11 ############################################################################### # Visualize the resulting regions for assign_labels in ('kmeans', 'discretize'): t0 = time.time() labels = spectral_clustering(graph, n_clusters=N_REGIONS, assign_labels=assign_labels, random_state=1) t1 = time.time() labels = labels.reshape(lena.shape) plt.figure(figsize=(5, 5)) plt.imshow(lena, cmap=plt.cm.gray) for l in range(N_REGIONS): plt.contour(labels == l, contours=1, colors=[plt.cm.spectral(l / float(N_REGIONS)), ]) plt.xticks(()) plt.yticks(()) plt.title('Spectral clustering: %s, %.2fs' % (assign_labels, (t1 - t0))) plt.show()
bsd-3-clause
jorge2703/scikit-learn
examples/text/document_clustering.py
230
8356
""" ======================================= Clustering text documents using k-means ======================================= This is an example showing how the scikit-learn can be used to cluster documents by topics using a bag-of-words approach. This example uses a scipy.sparse matrix to store the features instead of standard numpy arrays. Two feature extraction methods can be used in this example: - TfidfVectorizer uses a in-memory vocabulary (a python dict) to map the most frequent words to features indices and hence compute a word occurrence frequency (sparse) matrix. The word frequencies are then reweighted using the Inverse Document Frequency (IDF) vector collected feature-wise over the corpus. - HashingVectorizer hashes word occurrences to a fixed dimensional space, possibly with collisions. The word count vectors are then normalized to each have l2-norm equal to one (projected to the euclidean unit-ball) which seems to be important for k-means to work in high dimensional space. HashingVectorizer does not provide IDF weighting as this is a stateless model (the fit method does nothing). When IDF weighting is needed it can be added by pipelining its output to a TfidfTransformer instance. Two algorithms are demoed: ordinary k-means and its more scalable cousin minibatch k-means. Additionally, latent sematic analysis can also be used to reduce dimensionality and discover latent patterns in the data. It can be noted that k-means (and minibatch k-means) are very sensitive to feature scaling and that in this case the IDF weighting helps improve the quality of the clustering by quite a lot as measured against the "ground truth" provided by the class label assignments of the 20 newsgroups dataset. This improvement is not visible in the Silhouette Coefficient which is small for both as this measure seem to suffer from the phenomenon called "Concentration of Measure" or "Curse of Dimensionality" for high dimensional datasets such as text data. Other measures such as V-measure and Adjusted Rand Index are information theoretic based evaluation scores: as they are only based on cluster assignments rather than distances, hence not affected by the curse of dimensionality. Note: as k-means is optimizing a non-convex objective function, it will likely end up in a local optimum. Several runs with independent random init might be necessary to get a good convergence. """ # Author: Peter Prettenhofer <[email protected]> # Lars Buitinck <[email protected]> # License: BSD 3 clause from __future__ import print_function from sklearn.datasets import fetch_20newsgroups from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Normalizer from sklearn import metrics from sklearn.cluster import KMeans, MiniBatchKMeans import logging from optparse import OptionParser import sys from time import time import numpy as np # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') # parse commandline arguments op = OptionParser() op.add_option("--lsa", dest="n_components", type="int", help="Preprocess documents with latent semantic analysis.") op.add_option("--no-minibatch", action="store_false", dest="minibatch", default=True, help="Use ordinary k-means algorithm (in batch mode).") op.add_option("--no-idf", action="store_false", dest="use_idf", default=True, help="Disable Inverse Document Frequency feature weighting.") op.add_option("--use-hashing", action="store_true", default=False, help="Use a hashing feature vectorizer") op.add_option("--n-features", type=int, default=10000, help="Maximum number of features (dimensions)" " to extract from text.") op.add_option("--verbose", action="store_true", dest="verbose", default=False, help="Print progress reports inside k-means algorithm.") print(__doc__) op.print_help() (opts, args) = op.parse_args() if len(args) > 0: op.error("this script takes no arguments.") sys.exit(1) ############################################################################### # Load some categories from the training set categories = [ 'alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space', ] # Uncomment the following to do the analysis on all the categories #categories = None print("Loading 20 newsgroups dataset for categories:") print(categories) dataset = fetch_20newsgroups(subset='all', categories=categories, shuffle=True, random_state=42) print("%d documents" % len(dataset.data)) print("%d categories" % len(dataset.target_names)) print() labels = dataset.target true_k = np.unique(labels).shape[0] print("Extracting features from the training dataset using a sparse vectorizer") t0 = time() if opts.use_hashing: if opts.use_idf: # Perform an IDF normalization on the output of HashingVectorizer hasher = HashingVectorizer(n_features=opts.n_features, stop_words='english', non_negative=True, norm=None, binary=False) vectorizer = make_pipeline(hasher, TfidfTransformer()) else: vectorizer = HashingVectorizer(n_features=opts.n_features, stop_words='english', non_negative=False, norm='l2', binary=False) else: vectorizer = TfidfVectorizer(max_df=0.5, max_features=opts.n_features, min_df=2, stop_words='english', use_idf=opts.use_idf) X = vectorizer.fit_transform(dataset.data) print("done in %fs" % (time() - t0)) print("n_samples: %d, n_features: %d" % X.shape) print() if opts.n_components: print("Performing dimensionality reduction using LSA") t0 = time() # Vectorizer results are normalized, which makes KMeans behave as # spherical k-means for better results. Since LSA/SVD results are # not normalized, we have to redo the normalization. svd = TruncatedSVD(opts.n_components) normalizer = Normalizer(copy=False) lsa = make_pipeline(svd, normalizer) X = lsa.fit_transform(X) print("done in %fs" % (time() - t0)) explained_variance = svd.explained_variance_ratio_.sum() print("Explained variance of the SVD step: {}%".format( int(explained_variance * 100))) print() ############################################################################### # Do the actual clustering if opts.minibatch: km = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1, init_size=1000, batch_size=1000, verbose=opts.verbose) else: km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1, verbose=opts.verbose) print("Clustering sparse data with %s" % km) t0 = time() km.fit(X) print("done in %0.3fs" % (time() - t0)) print() print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels, km.labels_)) print("Completeness: %0.3f" % metrics.completeness_score(labels, km.labels_)) print("V-measure: %0.3f" % metrics.v_measure_score(labels, km.labels_)) print("Adjusted Rand-Index: %.3f" % metrics.adjusted_rand_score(labels, km.labels_)) print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X, km.labels_, sample_size=1000)) print() if not opts.use_hashing: print("Top terms per cluster:") if opts.n_components: original_space_centroids = svd.inverse_transform(km.cluster_centers_) order_centroids = original_space_centroids.argsort()[:, ::-1] else: order_centroids = km.cluster_centers_.argsort()[:, ::-1] terms = vectorizer.get_feature_names() for i in range(true_k): print("Cluster %d:" % i, end='') for ind in order_centroids[i, :10]: print(' %s' % terms[ind], end='') print()
bsd-3-clause
MartinThoma/algorithms
perceptron/perceptron.py
1
4057
#!/usr/bin/env python """Example implementation for a perceptron.""" import logging import math import sys import numpy as np from sklearn.metrics import accuracy_score logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG, stream=sys.stdout) class Activation: """Containing various activation functions.""" @staticmethod def sign(netOutput, threshold=0): return netOutput < threshold @staticmethod def sigmoid(netOutput): return 1 / (1 + math.e**(-1.0 * netOutput)) @staticmethod def tanh(netOutput): pass @staticmethod def rectified(netOutput): pass @staticmethod def softmax(netOutput): pass class Perceptron: """ A perceptron classifier. Parameters ---------- train : list valid : list test : list learningRate : float epochs : positive int Attributes ---------- learningRate : float epochs : int trainingSet : list validationSet : list testSet : list weight : list """ def __init__(self, train, valid, test, learningRate=0.01, epochs=10): self.learningRate = learningRate self.epochs = epochs self.trainingSet = train self.validationSet = valid self.testSet = test # Initialize the weight vector with small random values # around 0 and 0.1 self.weight = np.random.rand(self.trainingSet['x'].shape[1], 1) / 1000 self.weight = self.weight.astype(np.float32) def train(self, verbose=True): """ Train the perceptron with the perceptron learning algorithm. Parameters ---------- verbose : bool Print logging messages with validation accuracy if verbose is True. """ for i in range(1, self.epochs + 1): pred = self.evaluate(self.validationSet['x']) if verbose: val_acc = accuracy_score(self.validationSet['y'], pred) * 100 logging.info("Epoch: %i (Validation acc: %0.4f%%)", i, val_acc) for X, y in zip(self.trainingSet['x'], self.trainingSet['y']): pred = self.classify(X) X = np.array([X]).reshape(784, 1) self.weight += self.learningRate * (y - pred) * X * (-1) def classify(self, testInstance): """ Classify a single instance. Parameters ---------- testInstance : list of floats Returns ------- bool : True if the testInstance is recognized as a 7, False otherwise. """ return self.fire(testInstance) def evaluate(self, data=None): if data is None: data = self.testSet['x'] return list(map(self.classify, data)) def fire(self, input_): return Activation.sign(np.dot(np.array(input_, dtype=np.float32), self.weight)) def main(): """Run an example.""" # Get data from sklearn.datasets import fetch_mldata mnist = fetch_mldata('MNIST original', data_home='.') x = mnist.data y = mnist.target y = np.array([3 == el for el in y], dtype=np.float32) x = x / 255.0 * 2 - 1 # Scale data to [-1, 1] x = x.astype(np.float32) from sklearn.cross_validation import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.10, random_state=42) x_train, x_valid, y_train, y_valid = train_test_split(x_train, y_train, test_size=0.10, random_state=1337) p = Perceptron({'x': x_train, 'y': y_train}, {'x': x_valid, 'y': y_valid}, {'x': x_test, 'y': y_test}) p.train(verbose=True) if __name__ == '__main__': main()
mit
SnakeJenny/TensorFlow
tensorflow/contrib/learn/python/learn/estimators/estimator_test.py
8
42354
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Estimator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import itertools import json import os import tempfile import numpy as np import six from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib import learn from tensorflow.contrib import lookup from tensorflow.contrib.framework.python.ops import variables from tensorflow.contrib.layers.python.layers import feature_column as feature_column_lib from tensorflow.contrib.layers.python.layers import optimizers from tensorflow.contrib.learn.python.learn import experiment from tensorflow.contrib.learn.python.learn import models from tensorflow.contrib.learn.python.learn import monitors as monitors_lib from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.contrib.learn.python.learn.estimators import _sklearn from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn.estimators import linear from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.contrib.learn.python.learn.utils import input_fn_utils from tensorflow.contrib.metrics.python.ops import metric_ops from tensorflow.contrib.testing.python.framework import util_test from tensorflow.python.client import session as session_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.ops import variables as variables_lib from tensorflow.python.platform import gfile from tensorflow.python.platform import test from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import tag_constants from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import input as input_lib from tensorflow.python.training import monitored_session from tensorflow.python.training import queue_runner_impl from tensorflow.python.training import saver as saver_lib from tensorflow.python.training import session_run_hook from tensorflow.python.util import compat _BOSTON_INPUT_DIM = 13 _IRIS_INPUT_DIM = 4 def boston_input_fn(num_epochs=None): boston = base.load_boston() features = input_lib.limit_epochs( array_ops.reshape( constant_op.constant(boston.data), [-1, _BOSTON_INPUT_DIM]), num_epochs=num_epochs) labels = array_ops.reshape(constant_op.constant(boston.target), [-1, 1]) return features, labels def boston_input_fn_with_queue(num_epochs=None): features, labels = boston_input_fn(num_epochs=num_epochs) # Create a minimal queue runner. fake_queue = data_flow_ops.FIFOQueue(30, dtypes.int32) queue_runner = queue_runner_impl.QueueRunner(fake_queue, [constant_op.constant(0)]) queue_runner_impl.add_queue_runner(queue_runner) return features, labels def iris_input_fn(): iris = base.load_iris() features = array_ops.reshape( constant_op.constant(iris.data), [-1, _IRIS_INPUT_DIM]) labels = array_ops.reshape(constant_op.constant(iris.target), [-1]) return features, labels def iris_input_fn_labels_dict(): iris = base.load_iris() features = array_ops.reshape( constant_op.constant(iris.data), [-1, _IRIS_INPUT_DIM]) labels = { 'labels': array_ops.reshape(constant_op.constant(iris.target), [-1]) } return features, labels def boston_eval_fn(): boston = base.load_boston() n_examples = len(boston.target) features = array_ops.reshape( constant_op.constant(boston.data), [n_examples, _BOSTON_INPUT_DIM]) labels = array_ops.reshape( constant_op.constant(boston.target), [n_examples, 1]) return array_ops.concat([features, features], 0), array_ops.concat( [labels, labels], 0) def extract(data, key): if isinstance(data, dict): assert key in data return data[key] else: return data def linear_model_params_fn(features, labels, mode, params): features = extract(features, 'input') labels = extract(labels, 'labels') assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, variables.get_global_step(), optimizer='Adagrad', learning_rate=params['learning_rate']) return prediction, loss, train_op def linear_model_fn(features, labels, mode): features = extract(features, 'input') labels = extract(labels, 'labels') assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) if isinstance(features, dict): (_, features), = features.items() prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, variables.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return prediction, loss, train_op def linear_model_fn_with_model_fn_ops(features, labels, mode): """Same as linear_model_fn, but returns `ModelFnOps`.""" assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, variables.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return model_fn.ModelFnOps( mode=mode, predictions=prediction, loss=loss, train_op=train_op) def logistic_model_no_mode_fn(features, labels): features = extract(features, 'input') labels = extract(labels, 'labels') labels = array_ops.one_hot(labels, 3, 1, 0) prediction, loss = (models.logistic_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, variables.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return { 'class': math_ops.argmax(prediction, 1), 'prob': prediction }, loss, train_op VOCAB_FILE_CONTENT = 'emerson\nlake\npalmer\n' EXTRA_FILE_CONTENT = 'kermit\npiggy\nralph\n' def _build_estimator_for_export_tests(tmpdir): def _input_fn(): iris = base.load_iris() return { 'feature': constant_op.constant( iris.data, dtype=dtypes.float32) }, constant_op.constant( iris.target, shape=[150], dtype=dtypes.int32) feature_columns = [ feature_column_lib.real_valued_column( 'feature', dimension=4) ] est = linear.LinearRegressor(feature_columns) est.fit(input_fn=_input_fn, steps=20) feature_spec = feature_column_lib.create_feature_spec_for_parsing( feature_columns) serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) # hack in an op that uses an asset, in order to test asset export. # this is not actually valid, of course. def serving_input_fn_with_asset(): features, labels, inputs = serving_input_fn() vocab_file_name = os.path.join(tmpdir, 'my_vocab_file') vocab_file = gfile.GFile(vocab_file_name, mode='w') vocab_file.write(VOCAB_FILE_CONTENT) vocab_file.close() hashtable = lookup.HashTable( lookup.TextFileStringTableInitializer(vocab_file_name), 'x') features['bogus_lookup'] = hashtable.lookup( math_ops.to_int64(features['feature'])) return input_fn_utils.InputFnOps(features, labels, inputs) return est, serving_input_fn_with_asset def _build_estimator_for_resource_export_test(): def _input_fn(): iris = base.load_iris() return { 'feature': constant_op.constant(iris.data, dtype=dtypes.float32) }, constant_op.constant( iris.target, shape=[150], dtype=dtypes.int32) feature_columns = [ feature_column_lib.real_valued_column('feature', dimension=4) ] def resource_constant_model_fn(unused_features, unused_labels, mode): """A model_fn that loads a constant from a resource and serves it.""" assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) const = constant_op.constant(-1, dtype=dtypes.int64) table = lookup.MutableHashTable( dtypes.string, dtypes.int64, const, name='LookupTableModel') if mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL): key = constant_op.constant(['key']) value = constant_op.constant([42], dtype=dtypes.int64) train_op_1 = table.insert(key, value) training_state = lookup.MutableHashTable( dtypes.string, dtypes.int64, const, name='LookupTableTrainingState') training_op_2 = training_state.insert(key, value) return const, const, control_flow_ops.group(train_op_1, training_op_2) if mode == model_fn.ModeKeys.INFER: key = constant_op.constant(['key']) prediction = table.lookup(key) return prediction, const, control_flow_ops.no_op() est = estimator.Estimator(model_fn=resource_constant_model_fn) est.fit(input_fn=_input_fn, steps=1) feature_spec = feature_column_lib.create_feature_spec_for_parsing( feature_columns) serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) return est, serving_input_fn class CheckCallsMonitor(monitors_lib.BaseMonitor): def __init__(self, expect_calls): super(CheckCallsMonitor, self).__init__() self.begin_calls = None self.end_calls = None self.expect_calls = expect_calls def begin(self, max_steps): self.begin_calls = 0 self.end_calls = 0 def step_begin(self, step): self.begin_calls += 1 return {} def step_end(self, step, outputs): self.end_calls += 1 return False def end(self): assert (self.end_calls == self.expect_calls and self.begin_calls == self.expect_calls) class EstimatorTest(test.TestCase): def testExperimentIntegration(self): exp = experiment.Experiment( estimator=estimator.Estimator(model_fn=linear_model_fn), train_input_fn=boston_input_fn, eval_input_fn=boston_input_fn) exp.test() def testModelFnArgs(self): expected_param = {'some_param': 'some_value'} expected_config = run_config.RunConfig() expected_config.i_am_test = True def _argument_checker(features, labels, mode, params, config): _, _ = features, labels self.assertEqual(model_fn.ModeKeys.TRAIN, mode) self.assertEqual(expected_param, params) self.assertTrue(config.i_am_test) return constant_op.constant(0.), constant_op.constant( 0.), constant_op.constant(0.) est = estimator.Estimator( model_fn=_argument_checker, params=expected_param, config=expected_config) est.fit(input_fn=boston_input_fn, steps=1) def testModelFnWithModelDir(self): expected_param = {'some_param': 'some_value'} expected_model_dir = tempfile.mkdtemp() def _argument_checker(features, labels, mode, params, config=None, model_dir=None): _, _, _ = features, labels, config self.assertEqual(model_fn.ModeKeys.TRAIN, mode) self.assertEqual(expected_param, params) self.assertEqual(model_dir, expected_model_dir) return constant_op.constant(0.), constant_op.constant( 0.), constant_op.constant(0.) est = estimator.Estimator(model_fn=_argument_checker, params=expected_param, model_dir=expected_model_dir) est.fit(input_fn=boston_input_fn, steps=1) def testInvalidModelFn_no_train_op(self): def _invalid_model_fn(features, labels): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') loss = 100.0 - w return None, loss, None est = estimator.Estimator(model_fn=_invalid_model_fn) with self.assertRaisesRegexp(ValueError, 'Missing training_op'): est.fit(input_fn=boston_input_fn, steps=1) def testInvalidModelFn_no_loss(self): def _invalid_model_fn(features, labels, mode): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') loss = 100.0 - w train_op = w.assign_add(loss / 100.0) predictions = loss if mode == model_fn.ModeKeys.EVAL: loss = None return predictions, loss, train_op est = estimator.Estimator(model_fn=_invalid_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing loss'): est.evaluate(input_fn=boston_eval_fn, steps=1) def testInvalidModelFn_no_prediction(self): def _invalid_model_fn(features, labels): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') loss = 100.0 - w train_op = w.assign_add(loss / 100.0) return None, loss, train_op est = estimator.Estimator(model_fn=_invalid_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.evaluate(input_fn=boston_eval_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.predict(input_fn=boston_input_fn) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.predict( input_fn=functools.partial( boston_input_fn, num_epochs=1), as_iterable=True) def testModelFnScaffoldInTraining(self): self.is_init_fn_called = False def _init_fn(scaffold, session): _, _ = scaffold, session self.is_init_fn_called = True def _model_fn_scaffold(features, labels, mode): _, _ = features, labels return model_fn.ModelFnOps( mode=mode, predictions=constant_op.constant(0.), loss=constant_op.constant(0.), train_op=constant_op.constant(0.), scaffold=monitored_session.Scaffold(init_fn=_init_fn)) est = estimator.Estimator(model_fn=_model_fn_scaffold) est.fit(input_fn=boston_input_fn, steps=1) self.assertTrue(self.is_init_fn_called) def testModelFnScaffoldSaverUsage(self): def _model_fn_scaffold(features, labels, mode): _, _ = features, labels variables_lib.Variable(1., 'weight') real_saver = saver_lib.Saver() self.mock_saver = test.mock.Mock( wraps=real_saver, saver_def=real_saver.saver_def) return model_fn.ModelFnOps( mode=mode, predictions=constant_op.constant([[1.]]), loss=constant_op.constant(0.), train_op=constant_op.constant(0.), scaffold=monitored_session.Scaffold(saver=self.mock_saver)) def input_fn(): return { 'x': constant_op.constant([[1.]]), }, constant_op.constant([[1.]]) est = estimator.Estimator(model_fn=_model_fn_scaffold) est.fit(input_fn=input_fn, steps=1) self.assertTrue(self.mock_saver.save.called) est.evaluate(input_fn=input_fn, steps=1) self.assertTrue(self.mock_saver.restore.called) est.predict(input_fn=input_fn) self.assertTrue(self.mock_saver.restore.called) def serving_input_fn(): serialized_tf_example = array_ops.placeholder(dtype=dtypes.string, shape=[None], name='input_example_tensor') features, labels = input_fn() return input_fn_utils.InputFnOps( features, labels, {'examples': serialized_tf_example}) est.export_savedmodel(est.model_dir + '/export', serving_input_fn) self.assertTrue(self.mock_saver.restore.called) def testCheckpointSaverHookSuppressesTheDefaultOne(self): saver_hook = test.mock.Mock( spec=basic_session_run_hooks.CheckpointSaverHook) saver_hook.before_run.return_value = None est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1, monitors=[saver_hook]) # test nothing is saved, due to suppressing default saver with self.assertRaises(learn.NotFittedError): est.evaluate(input_fn=boston_input_fn, steps=1) def testCustomConfig(self): test_random_seed = 5783452 class TestInput(object): def __init__(self): self.random_seed = 0 def config_test_input_fn(self): self.random_seed = ops.get_default_graph().seed return constant_op.constant([[1.]]), constant_op.constant([1.]) config = run_config.RunConfig(tf_random_seed=test_random_seed) test_input = TestInput() est = estimator.Estimator(model_fn=linear_model_fn, config=config) est.fit(input_fn=test_input.config_test_input_fn, steps=1) # If input_fn ran, it will have given us the random seed set on the graph. self.assertEquals(test_random_seed, test_input.random_seed) def testRunConfigModelDir(self): config = run_config.RunConfig(model_dir='test_dir') est = estimator.Estimator(model_fn=linear_model_fn, config=config) self.assertEqual('test_dir', est.config.model_dir) self.assertEqual('test_dir', est.model_dir) def testModelDirAndRunConfigModelDir(self): config = run_config.RunConfig(model_dir='test_dir') est = estimator.Estimator(model_fn=linear_model_fn, config=config, model_dir='test_dir') self.assertEqual('test_dir', est.config.model_dir) with self.assertRaisesRegexp( ValueError, 'model_dir are set both in constructor and RunConfig, ' 'but with different'): estimator.Estimator(model_fn=linear_model_fn, config=config, model_dir='different_dir') def testModelDirIsCopiedToRunConfig(self): config = run_config.RunConfig() self.assertIsNone(config.model_dir) est = estimator.Estimator(model_fn=linear_model_fn, model_dir='test_dir', config=config) self.assertEqual('test_dir', est.config.model_dir) self.assertEqual('test_dir', est.model_dir) def testModelDirAsTempDir(self): with test.mock.patch.object(tempfile, 'mkdtemp', return_value='temp_dir'): est = estimator.Estimator(model_fn=linear_model_fn) self.assertEqual('temp_dir', est.config.model_dir) self.assertEqual('temp_dir', est.model_dir) def testCheckInputs(self): est = estimator.SKCompat(estimator.Estimator(model_fn=linear_model_fn)) # Lambdas so we have to different objects to compare right_features = lambda: np.ones(shape=[7, 8], dtype=np.float32) right_labels = lambda: np.ones(shape=[7, 10], dtype=np.int32) est.fit(right_features(), right_labels(), steps=1) # TODO(wicke): This does not fail for np.int32 because of data_feeder magic. wrong_type_features = np.ones(shape=[7, 8], dtype=np.int64) wrong_size_features = np.ones(shape=[7, 10]) wrong_type_labels = np.ones(shape=[7, 10], dtype=np.float32) wrong_size_labels = np.ones(shape=[7, 11]) est.fit(x=right_features(), y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=wrong_type_features, y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=wrong_size_features, y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=right_features(), y=wrong_type_labels, steps=1) with self.assertRaises(ValueError): est.fit(x=right_features(), y=wrong_size_labels, steps=1) def testBadInput(self): est = estimator.Estimator(model_fn=linear_model_fn) self.assertRaisesRegexp( ValueError, 'Either x or input_fn must be provided.', est.fit, x=None, input_fn=None, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and x or y', est.fit, x='X', input_fn=iris_input_fn, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and x or y', est.fit, y='Y', input_fn=iris_input_fn, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and batch_size', est.fit, input_fn=iris_input_fn, batch_size=100, steps=1) self.assertRaisesRegexp( ValueError, 'Inputs cannot be tensors. Please provide input_fn.', est.fit, x=constant_op.constant(1.), steps=1) def testUntrained(self): boston = base.load_boston() est = estimator.SKCompat(estimator.Estimator(model_fn=linear_model_fn)) with self.assertRaises(learn.NotFittedError): _ = est.score(x=boston.data, y=boston.target.astype(np.float64)) with self.assertRaises(learn.NotFittedError): est.predict(x=boston.data) def testContinueTraining(self): boston = base.load_boston() output_dir = tempfile.mkdtemp() est = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_fn, model_dir=output_dir)) float64_labels = boston.target.astype(np.float64) est.fit(x=boston.data, y=float64_labels, steps=50) scores = est.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) del est # Create another estimator object with the same output dir. est2 = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_fn, model_dir=output_dir)) # Check we can evaluate and predict. scores2 = est2.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) self.assertAllClose(scores['MSE'], scores2['MSE']) predictions = np.array(list(est2.predict(x=boston.data))) other_score = _sklearn.mean_squared_error(predictions, float64_labels) self.assertAllClose(scores['MSE'], other_score) # Check we can keep training. est2.fit(x=boston.data, y=float64_labels, steps=100) scores3 = est2.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) self.assertLess(scores3['MSE'], scores['MSE']) def testEstimatorParams(self): boston = base.load_boston() est = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_params_fn, params={'learning_rate': 0.01})) est.fit(x=boston.data, y=boston.target, steps=100) def testHooksNotChanged(self): est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) # We pass empty array and expect it to remain empty after calling # fit and evaluate. Requires inside to copy this array if any hooks were # added. my_array = [] est.fit(input_fn=iris_input_fn, steps=100, monitors=my_array) _ = est.evaluate(input_fn=iris_input_fn, steps=1, hooks=my_array) self.assertEqual(my_array, []) def testIrisIterator(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = itertools.islice(iris.target, 100) estimator.SKCompat(est).fit(x_iter, y_iter, steps=20) eval_result = est.evaluate(input_fn=iris_input_fn, steps=1) x_iter_eval = itertools.islice(iris.data, 100) y_iter_eval = itertools.islice(iris.target, 100) score_result = estimator.SKCompat(est).score(x_iter_eval, y_iter_eval) print(score_result) self.assertItemsEqual(eval_result.keys(), score_result.keys()) self.assertItemsEqual(['global_step', 'loss'], score_result.keys()) predictions = estimator.SKCompat(est).predict(x=iris.data)['class'] self.assertEqual(len(predictions), iris.target.shape[0]) def testIrisIteratorArray(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = (np.array(x) for x in iris.target) est.fit(x_iter, y_iter, steps=100) _ = est.evaluate(input_fn=iris_input_fn, steps=1) _ = six.next(est.predict(x=iris.data))['class'] def testIrisIteratorPlainInt(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = (v for v in iris.target) est.fit(x_iter, y_iter, steps=100) _ = est.evaluate(input_fn=iris_input_fn, steps=1) _ = six.next(est.predict(x=iris.data))['class'] def testIrisTruncatedIterator(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 50) y_iter = ([np.int32(v)] for v in iris.target) est.fit(x_iter, y_iter, steps=100) def testTrainStepsIsIncremental(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=10) self.assertEqual(10, est.get_variable_value('global_step')) est.fit(input_fn=boston_input_fn, steps=15) self.assertEqual(25, est.get_variable_value('global_step')) def testTrainMaxStepsIsNotIncremental(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, max_steps=10) self.assertEqual(10, est.get_variable_value('global_step')) est.fit(input_fn=boston_input_fn, max_steps=15) self.assertEqual(15, est.get_variable_value('global_step')) def testPredict(self): est = estimator.Estimator(model_fn=linear_model_fn) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) output = list(est.predict(x=boston.data, batch_size=10)) self.assertEqual(len(output), boston.target.shape[0]) def testWithModelFnOps(self): """Test for model_fn that returns `ModelFnOps`.""" est = estimator.Estimator(model_fn=linear_model_fn_with_model_fn_ops) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) input_fn = functools.partial(boston_input_fn, num_epochs=1) scores = est.evaluate(input_fn=input_fn, steps=1) self.assertIn('loss', scores.keys()) output = list(est.predict(input_fn=input_fn)) self.assertEqual(len(output), boston.target.shape[0]) def testWrongInput(self): def other_input_fn(): return { 'other': constant_op.constant([0, 0, 0]) }, constant_op.constant([0, 0, 0]) est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaises(ValueError): est.fit(input_fn=other_input_fn, steps=1) def testMonitorsForFit(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=21, monitors=[CheckCallsMonitor(expect_calls=21)]) def testHooksForEvaluate(self): class CheckCallHook(session_run_hook.SessionRunHook): def __init__(self): self.run_count = 0 def after_run(self, run_context, run_values): self.run_count += 1 est = learn.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1) hook = CheckCallHook() est.evaluate(input_fn=boston_eval_fn, steps=3, hooks=[hook]) self.assertEqual(3, hook.run_count) def testSummaryWriting(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=200) est.evaluate(input_fn=boston_input_fn, steps=200) loss_summary = util_test.simple_values_from_events( util_test.latest_events(est.model_dir), ['OptimizeLoss/loss']) self.assertEqual(1, len(loss_summary)) def testLossInGraphCollection(self): class _LossCheckerHook(session_run_hook.SessionRunHook): def begin(self): self.loss_collection = ops.get_collection(ops.GraphKeys.LOSSES) hook = _LossCheckerHook() est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=200, monitors=[hook]) self.assertTrue(hook.loss_collection) def test_export_returns_exported_dirname(self): expected = '/path/to/some_dir' with test.mock.patch.object(estimator, 'export') as mock_export_module: mock_export_module._export_estimator.return_value = expected est = estimator.Estimator(model_fn=linear_model_fn) actual = est.export('/path/to') self.assertEquals(expected, actual) def test_export_savedmodel(self): tmpdir = tempfile.mkdtemp() est, serving_input_fn = _build_estimator_for_export_tests(tmpdir) extra_file_name = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_extra_file')) extra_file = gfile.GFile(extra_file_name, mode='w') extra_file.write(EXTRA_FILE_CONTENT) extra_file.close() assets_extra = {'some/sub/directory/my_extra_file': extra_file_name} export_dir_base = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('export')) export_dir = est.export_savedmodel( export_dir_base, serving_input_fn, assets_extra=assets_extra) self.assertTrue(gfile.Exists(export_dir_base)) self.assertTrue(gfile.Exists(export_dir)) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes( 'saved_model.pb')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.index')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.data-00000-of-00001')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file')))) self.assertEqual( compat.as_bytes(VOCAB_FILE_CONTENT), compat.as_bytes( gfile.GFile( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file'))).read())) expected_extra_path = os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra/some/sub/directory/my_extra_file')) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra')))) self.assertTrue(gfile.Exists(expected_extra_path)) self.assertEqual( compat.as_bytes(EXTRA_FILE_CONTENT), compat.as_bytes(gfile.GFile(expected_extra_path).read())) expected_vocab_file = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_vocab_file')) # Restore, to validate that the export was well-formed. with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, [tag_constants.SERVING], export_dir) assets = [ x.eval() for x in graph.get_collection(ops.GraphKeys.ASSET_FILEPATHS) ] self.assertItemsEqual([expected_vocab_file], assets) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('linear/linear/feature/matmul' in graph_ops) # cleanup gfile.DeleteRecursively(tmpdir) def test_export_savedmodel_with_resource(self): tmpdir = tempfile.mkdtemp() est, serving_input_fn = _build_estimator_for_resource_export_test() export_dir_base = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('export')) export_dir = est.export_savedmodel(export_dir_base, serving_input_fn) self.assertTrue(gfile.Exists(export_dir_base)) self.assertTrue(gfile.Exists(export_dir)) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes( 'saved_model.pb')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.index')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.data-00000-of-00001')))) # Restore, to validate that the export was well-formed. with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, [tag_constants.SERVING], export_dir) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('LookupTableModel' in graph_ops) self.assertFalse('LookupTableTrainingState' in graph_ops) # cleanup gfile.DeleteRecursively(tmpdir) class InferRealValuedColumnsTest(test.TestCase): def testInvalidArgs(self): with self.assertRaisesRegexp(ValueError, 'x or input_fn must be provided'): estimator.infer_real_valued_columns_from_input(None) with self.assertRaisesRegexp(ValueError, 'cannot be tensors'): estimator.infer_real_valued_columns_from_input(constant_op.constant(1.0)) def _assert_single_feature_column(self, expected_shape, expected_dtype, feature_columns): self.assertEqual(1, len(feature_columns)) feature_column = feature_columns[0] self.assertEqual('', feature_column.name) self.assertEqual( { '': parsing_ops.FixedLenFeature( shape=expected_shape, dtype=expected_dtype) }, feature_column.config) def testInt32Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.int32)) self._assert_single_feature_column([8], dtypes.int32, feature_columns) def testInt32InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.int32), None)) self._assert_single_feature_column([8], dtypes.int32, feature_columns) def testInt64Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.int64)) self._assert_single_feature_column([8], dtypes.int64, feature_columns) def testInt64InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.int64), None)) self._assert_single_feature_column([8], dtypes.int64, feature_columns) def testFloat32Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.float32)) self._assert_single_feature_column([8], dtypes.float32, feature_columns) def testFloat32InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.float32), None)) self._assert_single_feature_column([8], dtypes.float32, feature_columns) def testFloat64Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.float64)) self._assert_single_feature_column([8], dtypes.float64, feature_columns) def testFloat64InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.float64), None)) self._assert_single_feature_column([8], dtypes.float64, feature_columns) def testBoolInput(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): estimator.infer_real_valued_columns_from_input( np.array([[False for _ in xrange(8)] for _ in xrange(7)])) def testBoolInputFn(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input_fn( lambda: (constant_op.constant(False, shape=[7, 8], dtype=dtypes.bool), None)) def testStringInput(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input( np.array([['%d.0' % i for i in xrange(8)] for _ in xrange(7)])) def testStringInputFn(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input_fn( lambda: ( constant_op.constant([['%d.0' % i for i in xrange(8)] for _ in xrange(7)]), None)) def testBostonInputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( boston_input_fn) self._assert_single_feature_column([_BOSTON_INPUT_DIM], dtypes.float64, feature_columns) def testIrisInputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( iris_input_fn) self._assert_single_feature_column([_IRIS_INPUT_DIM], dtypes.float64, feature_columns) class ReplicaDeviceSetterTest(test.TestCase): def testVariablesAreOnPs(self): tf_config = {'cluster': {run_config.TaskType.PS: ['fake_ps_0']}} with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('/job:ps/task:0', v.device) self.assertDeviceEqual('/job:ps/task:0', v.initializer.device) self.assertDeviceEqual('/job:ps/task:0', w.device) self.assertDeviceEqual('/job:ps/task:0', w.initializer.device) self.assertDeviceEqual('/job:worker', a.device) def testVariablesAreLocal(self): with ops.device( estimator._get_replica_device_setter(run_config.RunConfig())): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('', v.device) self.assertDeviceEqual('', v.initializer.device) self.assertDeviceEqual('', w.device) self.assertDeviceEqual('', w.initializer.device) self.assertDeviceEqual('', a.device) def testMutableHashTableIsOnPs(self): tf_config = {'cluster': {run_config.TaskType.PS: ['fake_ps_0']}} with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): default_val = constant_op.constant([-1, -1], dtypes.int64) table = lookup.MutableHashTable(dtypes.string, dtypes.int64, default_val) input_string = constant_op.constant(['brain', 'salad', 'tank']) output = table.lookup(input_string) self.assertDeviceEqual('/job:ps/task:0', table._table_ref.device) self.assertDeviceEqual('/job:ps/task:0', output.device) def testMutableHashTableIsLocal(self): with ops.device( estimator._get_replica_device_setter(run_config.RunConfig())): default_val = constant_op.constant([-1, -1], dtypes.int64) table = lookup.MutableHashTable(dtypes.string, dtypes.int64, default_val) input_string = constant_op.constant(['brain', 'salad', 'tank']) output = table.lookup(input_string) self.assertDeviceEqual('', table._table_ref.device) self.assertDeviceEqual('', output.device) def testTaskIsSetOnWorkerWhenJobNameIsSet(self): tf_config = { 'cluster': { run_config.TaskType.PS: ['fake_ps_0'] }, 'task': { 'type': run_config.TaskType.WORKER, 'index': 3 } } with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('/job:ps/task:0', v.device) self.assertDeviceEqual('/job:ps/task:0', v.initializer.device) self.assertDeviceEqual('/job:ps/task:0', w.device) self.assertDeviceEqual('/job:ps/task:0', w.initializer.device) self.assertDeviceEqual('/job:worker/task:3', a.device) if __name__ == '__main__': test.main()
apache-2.0
jvpoulos/cs289-hw5
hw5-code/census_clf.py
1
2480
import numpy as np import copy import cPickle as pickle import decision_tree as dt from sklearn.cross_validation import train_test_split # Load train data # train, load from csv without headers features_train = np.genfromtxt('../census-dataset/census-train-features-median.csv', delimiter=' ', skip_header=1) # remove index column features_train = features_train[:,1:] labels_train = np.genfromtxt('../census-dataset/census-train-labels.csv', delimiter=' ', skip_header=1) # remove index column labels_train = labels_train[:,1:][:,0] # split to obtain train and test set x_train, x_test, y_train, y_test = train_test_split(features_train, labels_train, test_size=0.33) # concatenate features and labels data_train = np.column_stack((x_train, y_train)) data_test = np.column_stack((x_test, y_test)) # build decision tree using entropy decision_tree = dt.buildtree(data_train, dt.entropy, 0.01) min_gain_error = {} # test minimal gain values for pruning for min_gain_value in np.arange(0,1, 0.01): dt_temp = copy.copy(decision_tree) dt.prune(dt_temp, min_gain_value) # classify test data y_hat = map(lambda obs : dt.classify(obs, dt_temp), x_test) y_hat = map(dt.convertToLabel, y_hat) y_hat = np.array(y_hat) error = (y_hat != y_test).sum() / float(y_test.shape[0]) min_gain_error[min_gain_value] = error # prune tree with optimal min_gain value min_gain_opt = min(dict.items(min_gain_error))[0] dt.prune(decision_tree, min_gain_opt) # print and draw decision tree # dt.drawtree(decision_tree,png='census_decision_tree.png') # dt.printtree(decision_tree) # classify validation set with pruned tree y_hat_val = map(lambda obs : dt.classify(obs, decision_tree), x_test) y_hat_val = map(dt.convertToLabel, y_hat_val) y_hat_val = np.array(y_hat_val) # report test set error error_val = (y_hat_val != y_test).sum() / float(y_test.shape[0]) print error_val # load test features features_test = np.genfromtxt('../census-dataset/census-test-features-median.csv', delimiter=' ', skip_header=1) features_test = features_test[:,1:] # classify test set with pruned tree y_hat_test = map(lambda obs : dt.classify(obs, decision_tree), features_test) y_hat_test = map(dt.convertToLabel, y_hat_test) y_hat_test = np.array(y_hat_test) # export labels for kaggle submission test_ids = np.arange(1,y_hat_test.shape[0]+1, 1) np.savetxt("census_decision_tree.csv", np.vstack((test_ids,y_hat_test)).T, delimiter=",", fmt='%1.0f',header='Id,Category')
mit
mugizico/scikit-learn
sklearn/decomposition/tests/test_sparse_pca.py
142
5990
# Author: Vlad Niculae # License: BSD 3 clause import sys import numpy as np from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import SkipTest from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import if_not_mac_os from sklearn.decomposition import SparsePCA, MiniBatchSparsePCA from sklearn.utils import check_random_state def generate_toy_data(n_components, n_samples, image_size, random_state=None): n_features = image_size[0] * image_size[1] rng = check_random_state(random_state) U = rng.randn(n_samples, n_components) V = rng.randn(n_components, n_features) centers = [(3, 3), (6, 7), (8, 1)] sz = [1, 2, 1] for k in range(n_components): img = np.zeros(image_size) xmin, xmax = centers[k][0] - sz[k], centers[k][0] + sz[k] ymin, ymax = centers[k][1] - sz[k], centers[k][1] + sz[k] img[xmin:xmax][:, ymin:ymax] = 1.0 V[k, :] = img.ravel() # Y is defined by : Y = UV + noise Y = np.dot(U, V) Y += 0.1 * rng.randn(Y.shape[0], Y.shape[1]) # Add noise return Y, U, V # SparsePCA can be a bit slow. To avoid having test times go up, we # test different aspects of the code in the same test def test_correct_shapes(): rng = np.random.RandomState(0) X = rng.randn(12, 10) spca = SparsePCA(n_components=8, random_state=rng) U = spca.fit_transform(X) assert_equal(spca.components_.shape, (8, 10)) assert_equal(U.shape, (12, 8)) # test overcomplete decomposition spca = SparsePCA(n_components=13, random_state=rng) U = spca.fit_transform(X) assert_equal(spca.components_.shape, (13, 10)) assert_equal(U.shape, (12, 13)) def test_fit_transform(): alpha = 1 rng = np.random.RandomState(0) Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array spca_lars = SparsePCA(n_components=3, method='lars', alpha=alpha, random_state=0) spca_lars.fit(Y) # Test that CD gives similar results spca_lasso = SparsePCA(n_components=3, method='cd', random_state=0, alpha=alpha) spca_lasso.fit(Y) assert_array_almost_equal(spca_lasso.components_, spca_lars.components_) @if_not_mac_os() def test_fit_transform_parallel(): alpha = 1 rng = np.random.RandomState(0) Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array spca_lars = SparsePCA(n_components=3, method='lars', alpha=alpha, random_state=0) spca_lars.fit(Y) U1 = spca_lars.transform(Y) # Test multiple CPUs spca = SparsePCA(n_components=3, n_jobs=2, method='lars', alpha=alpha, random_state=0).fit(Y) U2 = spca.transform(Y) assert_true(not np.all(spca_lars.components_ == 0)) assert_array_almost_equal(U1, U2) def test_transform_nan(): # Test that SparsePCA won't return NaN when there is 0 feature in all # samples. rng = np.random.RandomState(0) Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array Y[:, 0] = 0 estimator = SparsePCA(n_components=8) assert_false(np.any(np.isnan(estimator.fit_transform(Y)))) def test_fit_transform_tall(): rng = np.random.RandomState(0) Y, _, _ = generate_toy_data(3, 65, (8, 8), random_state=rng) # tall array spca_lars = SparsePCA(n_components=3, method='lars', random_state=rng) U1 = spca_lars.fit_transform(Y) spca_lasso = SparsePCA(n_components=3, method='cd', random_state=rng) U2 = spca_lasso.fit(Y).transform(Y) assert_array_almost_equal(U1, U2) def test_initialization(): rng = np.random.RandomState(0) U_init = rng.randn(5, 3) V_init = rng.randn(3, 4) model = SparsePCA(n_components=3, U_init=U_init, V_init=V_init, max_iter=0, random_state=rng) model.fit(rng.randn(5, 4)) assert_array_equal(model.components_, V_init) def test_mini_batch_correct_shapes(): rng = np.random.RandomState(0) X = rng.randn(12, 10) pca = MiniBatchSparsePCA(n_components=8, random_state=rng) U = pca.fit_transform(X) assert_equal(pca.components_.shape, (8, 10)) assert_equal(U.shape, (12, 8)) # test overcomplete decomposition pca = MiniBatchSparsePCA(n_components=13, random_state=rng) U = pca.fit_transform(X) assert_equal(pca.components_.shape, (13, 10)) assert_equal(U.shape, (12, 13)) def test_mini_batch_fit_transform(): raise SkipTest("skipping mini_batch_fit_transform.") alpha = 1 rng = np.random.RandomState(0) Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array spca_lars = MiniBatchSparsePCA(n_components=3, random_state=0, alpha=alpha).fit(Y) U1 = spca_lars.transform(Y) # Test multiple CPUs if sys.platform == 'win32': # fake parallelism for win32 import sklearn.externals.joblib.parallel as joblib_par _mp = joblib_par.multiprocessing joblib_par.multiprocessing = None try: U2 = MiniBatchSparsePCA(n_components=3, n_jobs=2, alpha=alpha, random_state=0).fit(Y).transform(Y) finally: joblib_par.multiprocessing = _mp else: # we can efficiently use parallelism U2 = MiniBatchSparsePCA(n_components=3, n_jobs=2, alpha=alpha, random_state=0).fit(Y).transform(Y) assert_true(not np.all(spca_lars.components_ == 0)) assert_array_almost_equal(U1, U2) # Test that CD gives similar results spca_lasso = MiniBatchSparsePCA(n_components=3, method='cd', alpha=alpha, random_state=0).fit(Y) assert_array_almost_equal(spca_lasso.components_, spca_lars.components_)
bsd-3-clause
mxjl620/scikit-learn
examples/mixture/plot_gmm_classifier.py
250
3918
""" ================== GMM classification ================== Demonstration of Gaussian mixture models for classification. See :ref:`gmm` for more information on the estimator. Plots predicted labels on both training and held out test data using a variety of GMM classifiers on the iris dataset. Compares GMMs with spherical, diagonal, full, and tied covariance matrices in increasing order of performance. Although one would expect full covariance to perform best in general, it is prone to overfitting on small datasets and does not generalize well to held out test data. On the plots, train data is shown as dots, while test data is shown as crosses. The iris dataset is four-dimensional. Only the first two dimensions are shown here, and thus some points are separated in other dimensions. """ print(__doc__) # Author: Ron Weiss <[email protected]>, Gael Varoquaux # License: BSD 3 clause # $Id$ import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from sklearn import datasets from sklearn.cross_validation import StratifiedKFold from sklearn.externals.six.moves import xrange from sklearn.mixture import GMM def make_ellipses(gmm, ax): for n, color in enumerate('rgb'): v, w = np.linalg.eigh(gmm._get_covars()[n][:2, :2]) u = w[0] / np.linalg.norm(w[0]) angle = np.arctan2(u[1], u[0]) angle = 180 * angle / np.pi # convert to degrees v *= 9 ell = mpl.patches.Ellipse(gmm.means_[n, :2], v[0], v[1], 180 + angle, color=color) ell.set_clip_box(ax.bbox) ell.set_alpha(0.5) ax.add_artist(ell) iris = datasets.load_iris() # Break up the dataset into non-overlapping training (75%) and testing # (25%) sets. skf = StratifiedKFold(iris.target, n_folds=4) # Only take the first fold. train_index, test_index = next(iter(skf)) X_train = iris.data[train_index] y_train = iris.target[train_index] X_test = iris.data[test_index] y_test = iris.target[test_index] n_classes = len(np.unique(y_train)) # Try GMMs using different types of covariances. classifiers = dict((covar_type, GMM(n_components=n_classes, covariance_type=covar_type, init_params='wc', n_iter=20)) for covar_type in ['spherical', 'diag', 'tied', 'full']) n_classifiers = len(classifiers) plt.figure(figsize=(3 * n_classifiers / 2, 6)) plt.subplots_adjust(bottom=.01, top=0.95, hspace=.15, wspace=.05, left=.01, right=.99) for index, (name, classifier) in enumerate(classifiers.items()): # Since we have class labels for the training data, we can # initialize the GMM parameters in a supervised manner. classifier.means_ = np.array([X_train[y_train == i].mean(axis=0) for i in xrange(n_classes)]) # Train the other parameters using the EM algorithm. classifier.fit(X_train) h = plt.subplot(2, n_classifiers / 2, index + 1) make_ellipses(classifier, h) for n, color in enumerate('rgb'): data = iris.data[iris.target == n] plt.scatter(data[:, 0], data[:, 1], 0.8, color=color, label=iris.target_names[n]) # Plot the test data with crosses for n, color in enumerate('rgb'): data = X_test[y_test == n] plt.plot(data[:, 0], data[:, 1], 'x', color=color) y_train_pred = classifier.predict(X_train) train_accuracy = np.mean(y_train_pred.ravel() == y_train.ravel()) * 100 plt.text(0.05, 0.9, 'Train accuracy: %.1f' % train_accuracy, transform=h.transAxes) y_test_pred = classifier.predict(X_test) test_accuracy = np.mean(y_test_pred.ravel() == y_test.ravel()) * 100 plt.text(0.05, 0.8, 'Test accuracy: %.1f' % test_accuracy, transform=h.transAxes) plt.xticks(()) plt.yticks(()) plt.title(name) plt.legend(loc='lower right', prop=dict(size=12)) plt.show()
bsd-3-clause
BonexGu/Blik2D-SDK
Blik2D/addon/tensorflow-1.2.1_for_blik/tensorflow/contrib/factorization/python/ops/gmm.py
47
5877
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of Gaussian mixture model (GMM) clustering using tf.Learn.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib import framework from tensorflow.contrib.factorization.python.ops import gmm_ops from tensorflow.contrib.framework.python.framework import checkpoint_utils from tensorflow.contrib.framework.python.ops import variables from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib from tensorflow.python.framework import constant_op from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops.control_flow_ops import with_dependencies def _streaming_sum(scalar_tensor): """Create a sum metric and update op.""" sum_metric = framework.local_variable(constant_op.constant(0.0)) sum_update = sum_metric.assign_add(scalar_tensor) return sum_metric, sum_update class GMM(estimator.Estimator): """An estimator for GMM clustering.""" SCORES = 'scores' ASSIGNMENTS = 'assignments' ALL_SCORES = 'all_scores' def __init__(self, num_clusters, model_dir=None, random_seed=0, params='wmc', initial_clusters='random', covariance_type='full', config=None): """Creates a model for running GMM training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. random_seed: Python integer. Seed for PRNG used to initialize centers. params: Controls which parameters are updated in the training process. Can contain any combination of "w" for weights, "m" for means, and "c" for covars. initial_clusters: specifies how to initialize the clusters for training. See gmm_ops.gmm for the possible values. covariance_type: one of "full", "diag". config: See Estimator """ self._num_clusters = num_clusters self._params = params self._training_initial_clusters = initial_clusters self._covariance_type = covariance_type self._training_graph = None self._random_seed = random_seed super(GMM, self).__init__( model_fn=self._model_builder(), model_dir=model_dir, config=config) def predict_assignments(self, input_fn=None, batch_size=None, outputs=None): """See BaseEstimator.predict.""" results = self.predict(input_fn=input_fn, batch_size=batch_size, outputs=outputs) for result in results: yield result[GMM.ASSIGNMENTS] def score(self, input_fn=None, batch_size=None, steps=None): """Predict total sum of distances to nearest clusters. Note that this function is different from the corresponding one in sklearn which returns the negative of the sum of distances. Args: input_fn: see predict. batch_size: see predict. steps: see predict. Returns: Total sum of distances to nearest clusters. """ results = self.evaluate(input_fn=input_fn, batch_size=batch_size, steps=steps) return np.sum(results[GMM.SCORES]) def weights(self): """Returns the cluster weights.""" return checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_WEIGHT) def clusters(self): """Returns cluster centers.""" clusters = checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_VARIABLE) return np.squeeze(clusters, 1) def covariances(self): """Returns the covariances.""" return checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE) def _parse_tensor_or_dict(self, features): if isinstance(features, dict): return array_ops.concat([features[k] for k in sorted(features.keys())], 1) return features def _model_builder(self): """Creates a model function.""" def _model_fn(features, labels, mode): """Model function.""" assert labels is None, labels (all_scores, model_predictions, losses, training_op) = gmm_ops.gmm( self._parse_tensor_or_dict(features), self._training_initial_clusters, self._num_clusters, self._random_seed, self._covariance_type, self._params) incr_step = state_ops.assign_add(variables.get_global_step(), 1) loss = math_ops.reduce_sum(losses) training_op = with_dependencies([training_op, incr_step], loss) predictions = { GMM.ALL_SCORES: all_scores[0], GMM.ASSIGNMENTS: model_predictions[0][0], } eval_metric_ops = { GMM.SCORES: _streaming_sum(loss), } return model_fn_lib.ModelFnOps(mode=mode, predictions=predictions, eval_metric_ops=eval_metric_ops, loss=loss, train_op=training_op) return _model_fn
mit
gautam1858/tensorflow
tensorflow/contrib/learn/python/learn/estimators/estimator.py
14
62926
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Base Estimator class (deprecated). This module and all its submodules are deprecated. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for migration instructions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import copy import os import tempfile import numpy as np import six from google.protobuf import message from tensorflow.contrib import layers from tensorflow.contrib.framework import deprecated from tensorflow.contrib.framework import deprecated_args from tensorflow.contrib.framework import list_variables from tensorflow.contrib.framework import load_variable from tensorflow.contrib.learn.python.learn import evaluable from tensorflow.contrib.learn.python.learn import metric_spec from tensorflow.contrib.learn.python.learn import monitors as monitor_lib from tensorflow.contrib.learn.python.learn import trainable from tensorflow.contrib.learn.python.learn.estimators import _sklearn as sklearn from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import metric_key from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.contrib.learn.python.learn.estimators import tensor_signature from tensorflow.contrib.learn.python.learn.estimators._sklearn import NotFittedError from tensorflow.contrib.learn.python.learn.learn_io import data_feeder from tensorflow.contrib.learn.python.learn.utils import export from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils from tensorflow.contrib.meta_graph_transform import meta_graph_transform from tensorflow.contrib.training.python.training import evaluation from tensorflow.core.framework import summary_pb2 from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session as tf_session from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_util from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import lookup_ops from tensorflow.python.ops import metrics as metrics_lib from tensorflow.python.ops import resources from tensorflow.python.ops import variables from tensorflow.python.platform import gfile from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model import tag_constants from tensorflow.python.summary import summary as core_summary from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import checkpoint_management from tensorflow.python.training import device_setter from tensorflow.python.training import monitored_session from tensorflow.python.training import saver from tensorflow.python.training import training_util from tensorflow.python.util import compat from tensorflow.python.util import tf_decorator from tensorflow.python.util import tf_inspect AS_ITERABLE_DATE = '2016-09-15' AS_ITERABLE_INSTRUCTIONS = ( 'The default behavior of predict() is changing. The default value for\n' 'as_iterable will change to True, and then the flag will be removed\n' 'altogether. The behavior of this flag is described below.') SCIKIT_DECOUPLE_DATE = '2016-12-01' SCIKIT_DECOUPLE_INSTRUCTIONS = ( 'Estimator is decoupled from Scikit Learn interface by moving into\n' 'separate class SKCompat. Arguments x, y and batch_size are only\n' 'available in the SKCompat class, Estimator will only accept input_fn.\n' 'Example conversion:\n' ' est = Estimator(...) -> est = SKCompat(Estimator(...))') def _verify_input_args(x, y, input_fn, feed_fn, batch_size): """Verifies validity of co-existence of input arguments.""" if input_fn is None: if x is None: raise ValueError('Either x or input_fn must be provided.') if tensor_util.is_tensor(x) or y is not None and tensor_util.is_tensor(y): raise ValueError('Inputs cannot be tensors. Please provide input_fn.') if feed_fn is not None: raise ValueError('Can not provide both feed_fn and x or y.') else: if (x is not None) or (y is not None): raise ValueError('Can not provide both input_fn and x or y.') if batch_size is not None: raise ValueError('Can not provide both input_fn and batch_size.') def _get_input_fn(x, y, input_fn, feed_fn, batch_size, shuffle=False, epochs=1): """Make inputs into input and feed functions. Args: x: Numpy, Pandas or Dask matrix or iterable. y: Numpy, Pandas or Dask matrix or iterable. input_fn: Pre-defined input function for training data. feed_fn: Pre-defined data feeder function. batch_size: Size to split data into parts. Must be >= 1. shuffle: Whether to shuffle the inputs. epochs: Number of epochs to run. Returns: Data input and feeder function based on training data. Raises: ValueError: Only one of `(x & y)` or `input_fn` must be provided. """ _verify_input_args(x, y, input_fn, feed_fn, batch_size) if input_fn is not None: return input_fn, feed_fn df = data_feeder.setup_train_data_feeder( x, y, n_classes=None, batch_size=batch_size, shuffle=shuffle, epochs=epochs) return df.input_builder, df.get_feed_dict_fn() @deprecated(None, 'Please specify feature columns explicitly.') def infer_real_valued_columns_from_input_fn(input_fn): """Creates `FeatureColumn` objects for inputs defined by `input_fn`. This interprets all inputs as dense, fixed-length float values. This creates a local graph in which it calls `input_fn` to build the tensors, then discards it. Args: input_fn: Input function returning a tuple of: features - Dictionary of string feature name to `Tensor` or `Tensor`. labels - `Tensor` of label values. Returns: List of `FeatureColumn` objects. """ with ops.Graph().as_default(): features, _ = input_fn() return layers.infer_real_valued_columns(features) @deprecated(None, 'Please specify feature columns explicitly.') def infer_real_valued_columns_from_input(x): """Creates `FeatureColumn` objects for inputs defined by input `x`. This interprets all inputs as dense, fixed-length float values. Args: x: Real-valued matrix of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. Returns: List of `FeatureColumn` objects. """ input_fn, _ = _get_input_fn( x=x, y=None, input_fn=None, feed_fn=None, batch_size=None) return infer_real_valued_columns_from_input_fn(input_fn) def _model_fn_args(fn): """Get argument names for function-like object. Args: fn: Function, or function-like object (e.g., result of `functools.partial`). Returns: `tuple` of string argument names. Raises: ValueError: if partial function has positionally bound arguments """ _, fn = tf_decorator.unwrap(fn) if hasattr(fn, 'func') and hasattr(fn, 'keywords') and hasattr(fn, 'args'): # Handle functools.partial and similar objects. return tuple([ arg for arg in tf_inspect.getargspec(fn.func).args[len(fn.args):] if arg not in set(fn.keywords.keys()) ]) # Handle function. return tuple(tf_inspect.getargspec(fn).args) def _get_replica_device_setter(config): """Creates a replica device setter if required. Args: config: A RunConfig instance. Returns: A replica device setter, or None. """ ps_ops = [ 'Variable', 'VariableV2', 'AutoReloadVariable', 'MutableHashTable', 'MutableHashTableV2', 'MutableHashTableOfTensors', 'MutableHashTableOfTensorsV2', 'MutableDenseHashTable', 'MutableDenseHashTableV2', 'VarHandleOp' ] if config.task_type: worker_device = '/job:%s/task:%d' % (config.task_type, config.task_id) else: worker_device = '/job:worker' if config.num_ps_replicas > 0: return device_setter.replica_device_setter( ps_tasks=config.num_ps_replicas, worker_device=worker_device, merge_devices=True, ps_ops=ps_ops, cluster=config.cluster_spec) else: return None def _make_metrics_ops(metrics, features, labels, predictions): """Add metrics based on `features`, `labels`, and `predictions`. `metrics` contains a specification for how to run metrics. It is a dict mapping friendly names to either `MetricSpec` objects, or directly to a metric function (assuming that `predictions` and `labels` are single tensors), or to `(pred_name, metric)` `tuple`, which passes `predictions[pred_name]` and `labels` to `metric` (assuming `labels` is a single tensor). Users are encouraged to use `MetricSpec` objects, which are more flexible and cleaner. They also lead to clearer errors. Args: metrics: A dict mapping names to metrics specification, for example `MetricSpec` objects. features: A dict of tensors returned from an input_fn as features/inputs. labels: A single tensor or a dict of tensors returned from an input_fn as labels. predictions: A single tensor or a dict of tensors output from a model as predictions. Returns: A dict mapping the friendly given in `metrics` to the result of calling the given metric function. Raises: ValueError: If metrics specifications do not work with the type of `features`, `labels`, or `predictions` provided. Mostly, a dict is given but no pred_name specified. """ metrics = metrics or {} # If labels is a dict with a single key, unpack into a single tensor. labels_tensor_or_dict = labels if isinstance(labels, dict) and len(labels) == 1: labels_tensor_or_dict = labels[list(labels.keys())[0]] result = {} # Iterate in lexicographic order, so the graph is identical among runs. for name, metric in sorted(six.iteritems(metrics)): if isinstance(metric, metric_spec.MetricSpec): result[name] = metric.create_metric_ops(features, labels, predictions) continue # TODO(b/31229024): Remove the rest of this loop logging.warning('Please specify metrics using MetricSpec. Using bare ' 'functions or (key, fn) tuples is deprecated and support ' 'for it will be removed on Oct 1, 2016.') if isinstance(name, tuple): # Multi-head metrics. if len(name) != 2: raise ValueError('Invalid metric for {}. It returned a tuple with ' 'len {}, expected 2.'.format(name, len(name))) if not isinstance(predictions, dict): raise ValueError('Metrics passed provide (name, prediction), ' 'but predictions are not dict. ' 'Metrics: %s, Predictions: %s.' % (metrics, predictions)) # Here are two options: labels are single Tensor or a dict. if isinstance(labels, dict) and name[1] in labels: # If labels are dict and the prediction name is in it, apply metric. result[name[0]] = metric(predictions[name[1]], labels[name[1]]) else: # Otherwise pass the labels to the metric. result[name[0]] = metric(predictions[name[1]], labels_tensor_or_dict) else: # Single head metrics. if isinstance(predictions, dict): raise ValueError('Metrics passed provide only name, no prediction, ' 'but predictions are dict. ' 'Metrics: %s, Labels: %s.' % (metrics, labels_tensor_or_dict)) result[name] = metric(predictions, labels_tensor_or_dict) return result def _dict_to_str(dictionary): """Get a `str` representation of a `dict`. Args: dictionary: The `dict` to be represented as `str`. Returns: A `str` representing the `dictionary`. """ results = [] for k, v in sorted(dictionary.items()): if isinstance(v, float) or isinstance(v, np.float32) or isinstance( v, int) or isinstance(v, np.int64) or isinstance(v, np.int32): results.append('%s = %s' % (k, v)) else: results.append('Type of %s = %s' % (k, type(v))) return ', '.join(results) def _write_dict_to_summary(output_dir, dictionary, current_global_step): """Writes a `dict` into summary file in given output directory. Args: output_dir: `str`, directory to write the summary file in. dictionary: the `dict` to be written to summary file. current_global_step: `int`, the current global step. """ logging.info('Saving dict for global step %d: %s', current_global_step, _dict_to_str(dictionary)) summary_writer = core_summary.FileWriterCache.get(output_dir) summary_proto = summary_pb2.Summary() for key in dictionary: if dictionary[key] is None: continue if key == 'global_step': continue if (isinstance(dictionary[key], np.float32) or isinstance(dictionary[key], float)): summary_proto.value.add(tag=key, simple_value=float(dictionary[key])) elif (isinstance(dictionary[key], np.int64) or isinstance(dictionary[key], np.int32) or isinstance(dictionary[key], int)): summary_proto.value.add(tag=key, simple_value=int(dictionary[key])) elif isinstance(dictionary[key], six.string_types): try: summ = summary_pb2.Summary.FromString(dictionary[key]) for i, _ in enumerate(summ.value): summ.value[i].tag = key summary_proto.value.extend(summ.value) except message.DecodeError: logging.warn('Skipping summary for %s, cannot parse string to Summary.', key) continue elif isinstance(dictionary[key], np.ndarray): value = summary_proto.value.add() value.tag = key value.node_name = key tensor_proto = tensor_util.make_tensor_proto(dictionary[key]) value.tensor.CopyFrom(tensor_proto) logging.info( 'Summary for np.ndarray is not visible in Tensorboard by default. ' 'Consider using a Tensorboard plugin for visualization (see ' 'https://github.com/tensorflow/tensorboard-plugin-example/blob/master/README.md' ' for more information).') else: logging.warn( 'Skipping summary for %s, must be a float, np.float32, np.int64, ' 'np.int32 or int or np.ndarray or a serialized string of Summary.', key) summary_writer.add_summary(summary_proto, current_global_step) summary_writer.flush() GraphRewriteSpec = collections.namedtuple('GraphRewriteSpec', ['tags', 'transforms']) class BaseEstimator(sklearn.BaseEstimator, evaluable.Evaluable, trainable.Trainable): """Abstract BaseEstimator class to train and evaluate TensorFlow models. THIS CLASS IS DEPRECATED. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for general migration instructions. Users should not instantiate or subclass this class. Instead, use an `Estimator`. """ # Note that for Google users, this is overridden with # learn_runner.EstimatorConfig. # TODO(wicke): Remove this once launcher takes over config functionality _Config = run_config.RunConfig # pylint: disable=invalid-name @deprecated(None, 'Please replace uses of any Estimator from tf.contrib.learn' ' with an Estimator from tf.estimator.*') def __init__(self, model_dir=None, config=None): """Initializes a BaseEstimator instance. Args: model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. If `None`, the model_dir in `config` will be used if set. If both are set, they must be same. config: A RunConfig instance. """ # Create a run configuration. if config is None: self._config = BaseEstimator._Config() logging.info('Using default config.') else: self._config = config if self._config.session_config is None: self._session_config = config_pb2.ConfigProto(allow_soft_placement=True) else: self._session_config = self._config.session_config # Model directory. if (model_dir is not None) and (self._config.model_dir is not None): if model_dir != self._config.model_dir: # TODO(b/9965722): remove this suppression after it is no longer # necessary. # pylint: disable=g-doc-exception raise ValueError( 'model_dir are set both in constructor and RunConfig, but with ' "different values. In constructor: '{}', in RunConfig: " "'{}' ".format(model_dir, self._config.model_dir)) # pylint: enable=g-doc-exception self._model_dir = model_dir or self._config.model_dir if self._model_dir is None: self._model_dir = tempfile.mkdtemp() logging.warning('Using temporary folder as model directory: %s', self._model_dir) if self._config.model_dir is None: self._config = self._config.replace(model_dir=self._model_dir) logging.info('Using config: %s', str(vars(self._config))) # Set device function depending if there are replicas or not. self._device_fn = _get_replica_device_setter(self._config) # Features and labels TensorSignature objects. # TODO(wicke): Rename these to something more descriptive self._features_info = None self._labels_info = None self._graph = None @property def config(self): # TODO(wicke): make RunConfig immutable, and then return it without a copy. return copy.deepcopy(self._config) @property def model_fn(self): """Returns the model_fn which is bound to self.params. Returns: The model_fn with the following signature: `def model_fn(features, labels, mode, metrics)` """ def public_model_fn(features, labels, mode, config): return self._call_model_fn(features, labels, mode, config=config) return public_model_fn @deprecated_args(SCIKIT_DECOUPLE_DATE, SCIKIT_DECOUPLE_INSTRUCTIONS, ('x', None), ('y', None), ('batch_size', None)) def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None, monitors=None, max_steps=None): # pylint: disable=g-doc-args,g-doc-return-or-yield """See `Trainable`. Raises: ValueError: If `x` or `y` are not `None` while `input_fn` is not `None`. ValueError: If both `steps` and `max_steps` are not `None`. """ if (steps is not None) and (max_steps is not None): raise ValueError('Can not provide both steps and max_steps.') _verify_input_args(x, y, input_fn, None, batch_size) if x is not None: SKCompat(self).fit(x, y, batch_size, steps, max_steps, monitors) return self if max_steps is not None: try: start_step = load_variable(self._model_dir, ops.GraphKeys.GLOBAL_STEP) if max_steps <= start_step: logging.info('Skipping training since max_steps has already saved.') return self except: # pylint: disable=bare-except pass hooks = monitor_lib.replace_monitors_with_hooks(monitors, self) if steps is not None or max_steps is not None: hooks.append(basic_session_run_hooks.StopAtStepHook(steps, max_steps)) loss = self._train_model(input_fn=input_fn, hooks=hooks) logging.info('Loss for final step: %s.', loss) return self @deprecated_args(SCIKIT_DECOUPLE_DATE, SCIKIT_DECOUPLE_INSTRUCTIONS, ('x', None), ('y', None), ('batch_size', None)) def partial_fit(self, x=None, y=None, input_fn=None, steps=1, batch_size=None, monitors=None): """Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different or the same chunks of the dataset. This either can implement iterative training or out-of-core/online training. This is especially useful when the whole dataset is too big to fit in memory at the same time. Or when model is taking long time to converge, and you want to split up training into subparts. Args: x: Matrix of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. If set, `input_fn` must be `None`. y: Vector or matrix [n_samples] or [n_samples, n_outputs]. Can be iterator that returns array of labels. The training label values (class labels in classification, real numbers in regression). If set, `input_fn` must be `None`. input_fn: Input function. If set, `x`, `y`, and `batch_size` must be `None`. steps: Number of steps for which to train model. If `None`, train forever. batch_size: minibatch size to use on the input, defaults to first dimension of `x`. Must be `None` if `input_fn` is provided. monitors: List of `BaseMonitor` subclass instances. Used for callbacks inside the training loop. Returns: `self`, for chaining. Raises: ValueError: If at least one of `x` and `y` is provided, and `input_fn` is provided. """ logging.warning('The current implementation of partial_fit is not optimized' ' for use in a loop. Consider using fit() instead.') return self.fit( x=x, y=y, input_fn=input_fn, steps=steps, batch_size=batch_size, monitors=monitors) @deprecated_args(SCIKIT_DECOUPLE_DATE, SCIKIT_DECOUPLE_INSTRUCTIONS, ('x', None), ('y', None), ('batch_size', None)) def evaluate(self, x=None, y=None, input_fn=None, feed_fn=None, batch_size=None, steps=None, metrics=None, name=None, checkpoint_path=None, hooks=None, log_progress=True): # pylint: disable=g-doc-args,g-doc-return-or-yield """See `Evaluable`. Raises: ValueError: If at least one of `x` or `y` is provided, and at least one of `input_fn` or `feed_fn` is provided. Or if `metrics` is not `None` or `dict`. """ _verify_input_args(x, y, input_fn, feed_fn, batch_size) if x is not None: return SKCompat(self).score(x, y, batch_size, steps, metrics, name) if metrics is not None and not isinstance(metrics, dict): raise ValueError('Metrics argument should be None or dict. ' 'Got %s.' % metrics) eval_results, global_step = self._evaluate_model( input_fn=input_fn, feed_fn=feed_fn, steps=steps, metrics=metrics, name=name, checkpoint_path=checkpoint_path, hooks=hooks, log_progress=log_progress) if eval_results is not None: eval_results.update({'global_step': global_step}) return eval_results @deprecated_args(SCIKIT_DECOUPLE_DATE, SCIKIT_DECOUPLE_INSTRUCTIONS, ('x', None), ('batch_size', None), ('as_iterable', True)) def predict(self, x=None, input_fn=None, batch_size=None, outputs=None, as_iterable=True, iterate_batches=False): """Returns predictions for given features. Args: x: Matrix of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. If set, `input_fn` must be `None`. input_fn: Input function. If set, `x` and 'batch_size' must be `None`. batch_size: Override default batch size. If set, 'input_fn' must be 'None'. outputs: list of `str`, name of the output to predict. If `None`, returns all. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). iterate_batches: If True, yield the whole batch at once instead of decomposing the batch into individual samples. Only relevant when as_iterable is True. Returns: A numpy array of predicted classes or regression values if the constructor's `model_fn` returns a `Tensor` for `predictions` or a `dict` of numpy arrays if `model_fn` returns a `dict`. Returns an iterable of predictions if as_iterable is True. Raises: ValueError: If x and input_fn are both provided or both `None`. """ _verify_input_args(x, None, input_fn, None, batch_size) if x is not None and not as_iterable: return SKCompat(self).predict(x, batch_size) input_fn, feed_fn = _get_input_fn(x, None, input_fn, None, batch_size) return self._infer_model( input_fn=input_fn, feed_fn=feed_fn, outputs=outputs, as_iterable=as_iterable, iterate_batches=iterate_batches) def get_variable_value(self, name): """Returns value of the variable given by name. Args: name: string, name of the tensor. Returns: Numpy array - value of the tensor. """ return load_variable(self.model_dir, name) def get_variable_names(self): """Returns list of all variable names in this model. Returns: List of names. """ return [name for name, _ in list_variables(self.model_dir)] @property def model_dir(self): return self._model_dir @deprecated('2017-03-25', 'Please use Estimator.export_savedmodel() instead.') def export( self, export_dir, input_fn=export._default_input_fn, # pylint: disable=protected-access input_feature_key=None, use_deprecated_input_fn=True, signature_fn=None, prediction_key=None, default_batch_size=1, exports_to_keep=None, checkpoint_path=None): """Exports inference graph into given dir. Args: export_dir: A string containing a directory to write the exported graph and checkpoints. input_fn: If `use_deprecated_input_fn` is true, then a function that given `Tensor` of `Example` strings, parses it into features that are then passed to the model. Otherwise, a function that takes no argument and returns a tuple of (features, labels), where features is a dict of string key to `Tensor` and labels is a `Tensor` that's currently not used (and so can be `None`). input_feature_key: Only used if `use_deprecated_input_fn` is false. String key into the features dict returned by `input_fn` that corresponds to a the raw `Example` strings `Tensor` that the exported model will take as input. Can only be `None` if you're using a custom `signature_fn` that does not use the first arg (examples). use_deprecated_input_fn: Determines the signature format of `input_fn`. signature_fn: Function that returns a default signature and a named signature map, given `Tensor` of `Example` strings, `dict` of `Tensor`s for features and `Tensor` or `dict` of `Tensor`s for predictions. prediction_key: The key for a tensor in the `predictions` dict (output from the `model_fn`) to use as the `predictions` input to the `signature_fn`. Optional. If `None`, predictions will pass to `signature_fn` without filtering. default_batch_size: Default batch size of the `Example` placeholder. exports_to_keep: Number of exports to keep. checkpoint_path: the checkpoint path of the model to be exported. If it is `None` (which is default), will use the latest checkpoint in export_dir. Returns: The string path to the exported directory. NB: this functionality was added ca. 2016/09/25; clients that depend on the return value may need to handle the case where this function returns None because subclasses are not returning a value. """ # pylint: disable=protected-access return export._export_estimator( estimator=self, export_dir=export_dir, signature_fn=signature_fn, prediction_key=prediction_key, input_fn=input_fn, input_feature_key=input_feature_key, use_deprecated_input_fn=use_deprecated_input_fn, default_batch_size=default_batch_size, exports_to_keep=exports_to_keep, checkpoint_path=checkpoint_path) @abc.abstractproperty def _get_train_ops(self, features, labels): """Method that builds model graph and returns trainer ops. Expected to be overridden by sub-classes that require custom support. Args: features: `Tensor` or `dict` of `Tensor` objects. labels: `Tensor` or `dict` of `Tensor` objects. Returns: A `ModelFnOps` object. """ pass @abc.abstractproperty def _get_predict_ops(self, features): """Method that builds model graph and returns prediction ops. Args: features: `Tensor` or `dict` of `Tensor` objects. Returns: A `ModelFnOps` object. """ pass def _get_eval_ops(self, features, labels, metrics): """Method that builds model graph and returns evaluation ops. Expected to be overridden by sub-classes that require custom support. Args: features: `Tensor` or `dict` of `Tensor` objects. labels: `Tensor` or `dict` of `Tensor` objects. metrics: Dict of metrics to run. If None, the default metric functions are used; if {}, no metrics are used. Otherwise, `metrics` should map friendly names for the metric to a `MetricSpec` object defining which model outputs to evaluate against which labels with which metric function. Metric ops should support streaming, e.g., returning update_op and value tensors. See more details in `../../../../metrics/python/metrics/ops/streaming_metrics.py` and `../metric_spec.py`. Returns: A `ModelFnOps` object. """ raise NotImplementedError('_get_eval_ops not implemented in BaseEstimator') @deprecated( '2016-09-23', 'The signature of the input_fn accepted by export is changing to be ' 'consistent with what\'s used by tf.Learn Estimator\'s train/evaluate, ' 'which makes this function useless. This will be removed after the ' 'deprecation date.') def _get_feature_ops_from_example(self, examples_batch): """Returns feature parser for given example batch using features info. This function requires `fit()` has been called. Args: examples_batch: batch of tf.Example Returns: features: `Tensor` or `dict` of `Tensor` objects. Raises: ValueError: If `_features_info` attribute is not available (usually because `fit()` has not been called). """ if self._features_info is None: raise ValueError('Features information missing, was fit() ever called?') return tensor_signature.create_example_parser_from_signatures( self._features_info, examples_batch) def _check_inputs(self, features, labels): if self._features_info is not None: logging.debug('Given features: %s, required signatures: %s.', str(features), str(self._features_info)) if not tensor_signature.tensors_compatible(features, self._features_info): raise ValueError('Features are incompatible with given information. ' 'Given features: %s, required signatures: %s.' % (str(features), str(self._features_info))) else: self._features_info = tensor_signature.create_signatures(features) logging.debug('Setting feature info to %s.', str(self._features_info)) if labels is not None: if self._labels_info is not None: logging.debug('Given labels: %s, required signatures: %s.', str(labels), str(self._labels_info)) if not tensor_signature.tensors_compatible(labels, self._labels_info): raise ValueError('Labels are incompatible with given information. ' 'Given labels: %s, required signatures: %s.' % (str(labels), str(self._labels_info))) else: self._labels_info = tensor_signature.create_signatures(labels) logging.debug('Setting labels info to %s', str(self._labels_info)) def _extract_metric_update_ops(self, eval_dict): """Separate update operations from metric value operations.""" update_ops = [] value_ops = {} for name, metric_ops in six.iteritems(eval_dict): if isinstance(metric_ops, (list, tuple)): if len(metric_ops) == 2: value_ops[name] = metric_ops[0] update_ops.append(metric_ops[1]) else: logging.warning( 'Ignoring metric {}. It returned a list|tuple with len {}, ' 'expected 2'.format(name, len(metric_ops))) value_ops[name] = metric_ops else: value_ops[name] = metric_ops if update_ops: update_ops = control_flow_ops.group(*update_ops) else: update_ops = None return update_ops, value_ops def _evaluate_model(self, input_fn, steps, feed_fn=None, metrics=None, name='', checkpoint_path=None, hooks=None, log_progress=True): # TODO(wicke): Remove this once Model and associated code are gone. if (hasattr(self._config, 'execution_mode') and self._config.execution_mode not in ('all', 'evaluate', 'eval_evalset')): return None, None # Check that model has been trained (if nothing has been set explicitly). if not checkpoint_path: latest_path = checkpoint_management.latest_checkpoint(self._model_dir) if not latest_path: raise NotFittedError( "Couldn't find trained model at %s." % self._model_dir) checkpoint_path = latest_path # Setup output directory. eval_dir = os.path.join(self._model_dir, 'eval' if not name else 'eval_' + name) with ops.Graph().as_default() as g: random_seed.set_random_seed(self._config.tf_random_seed) global_step = training_util.create_global_step(g) features, labels = input_fn() self._check_inputs(features, labels) model_fn_results = self._get_eval_ops(features, labels, metrics) eval_dict = model_fn_results.eval_metric_ops update_op, eval_dict = self._extract_metric_update_ops(eval_dict) # We need to copy the hook array as we modify it, thus [:]. hooks = hooks[:] if hooks else [] if feed_fn: hooks.append(basic_session_run_hooks.FeedFnHook(feed_fn)) if steps == 0: logging.warning('evaluation steps are 0. If `input_fn` does not raise ' '`OutOfRangeError`, the evaluation will never stop. ' 'Use steps=None if intended.') if steps: hooks.append( evaluation.StopAfterNEvalsHook(steps, log_progress=log_progress)) global_step_key = 'global_step' while global_step_key in eval_dict: global_step_key = '_' + global_step_key eval_dict[global_step_key] = global_step eval_results = evaluation.evaluate_once( checkpoint_path=checkpoint_path, master=self._config.evaluation_master, scaffold=model_fn_results.scaffold, eval_ops=update_op, final_ops=eval_dict, hooks=hooks, config=self._session_config) current_global_step = eval_results[global_step_key] _write_dict_to_summary(eval_dir, eval_results, current_global_step) return eval_results, current_global_step def _get_features_from_input_fn(self, input_fn): result = input_fn() if isinstance(result, (list, tuple)): return result[0] return result def _infer_model(self, input_fn, feed_fn=None, outputs=None, as_iterable=True, iterate_batches=False): # Check that model has been trained. checkpoint_path = checkpoint_management.latest_checkpoint(self._model_dir) if not checkpoint_path: raise NotFittedError( "Couldn't find trained model at %s." % self._model_dir) with ops.Graph().as_default() as g: random_seed.set_random_seed(self._config.tf_random_seed) training_util.create_global_step(g) features = self._get_features_from_input_fn(input_fn) infer_ops = self._get_predict_ops(features) predictions = self._filter_predictions(infer_ops.predictions, outputs) mon_sess = monitored_session.MonitoredSession( session_creator=monitored_session.ChiefSessionCreator( checkpoint_filename_with_path=checkpoint_path, scaffold=infer_ops.scaffold, config=self._session_config)) if not as_iterable: with mon_sess: if not mon_sess.should_stop(): return mon_sess.run(predictions, feed_fn() if feed_fn else None) else: return self._predict_generator(mon_sess, predictions, feed_fn, iterate_batches) def _predict_generator(self, mon_sess, predictions, feed_fn, iterate_batches): with mon_sess: while not mon_sess.should_stop(): preds = mon_sess.run(predictions, feed_fn() if feed_fn else None) if iterate_batches: yield preds elif not isinstance(predictions, dict): for pred in preds: yield pred else: first_tensor = list(preds.values())[0] if isinstance(first_tensor, sparse_tensor.SparseTensorValue): batch_length = first_tensor.dense_shape[0] else: batch_length = first_tensor.shape[0] for i in range(batch_length): yield {key: value[i] for key, value in six.iteritems(preds)} if self._is_input_constant(feed_fn, mon_sess.graph): return def _is_input_constant(self, feed_fn, graph): # If there are no queue_runners, the input `predictions` is a # constant, and we should stop after the first epoch. If, # instead, there are queue_runners, eventually they should throw # an `OutOfRangeError`. if graph.get_collection(ops.GraphKeys.QUEUE_RUNNERS): return False # data_feeder uses feed_fn to generate `OutOfRangeError`. if feed_fn is not None: return False return True def _filter_predictions(self, predictions, outputs): if not outputs: return predictions if not isinstance(predictions, dict): raise ValueError( 'outputs argument is not valid in case of non-dict predictions.') existing_keys = predictions.keys() predictions = { key: value for key, value in six.iteritems(predictions) if key in outputs } if not predictions: raise ValueError('Expected to run at least one output from %s, ' 'provided %s.' % (existing_keys, outputs)) return predictions def _train_model(self, input_fn, hooks): all_hooks = [] self._graph = ops.Graph() with self._graph.as_default() as g, g.device(self._device_fn): random_seed.set_random_seed(self._config.tf_random_seed) global_step = training_util.create_global_step(g) features, labels = input_fn() self._check_inputs(features, labels) training_util._get_or_create_global_step_read() # pylint: disable=protected-access model_fn_ops = self._get_train_ops(features, labels) ops.add_to_collection(ops.GraphKeys.LOSSES, model_fn_ops.loss) all_hooks.extend(hooks) all_hooks.extend([ basic_session_run_hooks.NanTensorHook(model_fn_ops.loss), basic_session_run_hooks.LoggingTensorHook( { 'loss': model_fn_ops.loss, 'step': global_step }, every_n_iter=100) ]) scaffold = model_fn_ops.scaffold or monitored_session.Scaffold() if not (scaffold.saver or ops.get_collection(ops.GraphKeys.SAVERS)): ops.add_to_collection( ops.GraphKeys.SAVERS, saver.Saver( sharded=True, max_to_keep=self._config.keep_checkpoint_max, keep_checkpoint_every_n_hours=( self._config.keep_checkpoint_every_n_hours), defer_build=True, save_relative_paths=True)) chief_hooks = [] if (self._config.save_checkpoints_secs or self._config.save_checkpoints_steps): saver_hook_exists = any( isinstance(h, basic_session_run_hooks.CheckpointSaverHook) for h in (all_hooks + model_fn_ops.training_hooks + chief_hooks + model_fn_ops.training_chief_hooks) ) if not saver_hook_exists: chief_hooks = [ basic_session_run_hooks.CheckpointSaverHook( self._model_dir, save_secs=self._config.save_checkpoints_secs, save_steps=self._config.save_checkpoints_steps, scaffold=scaffold) ] with monitored_session.MonitoredTrainingSession( master=self._config.master, is_chief=self._config.is_chief, checkpoint_dir=self._model_dir, scaffold=scaffold, hooks=all_hooks + model_fn_ops.training_hooks, chief_only_hooks=chief_hooks + model_fn_ops.training_chief_hooks, save_checkpoint_secs=0, # Saving is handled by a hook. save_summaries_steps=self._config.save_summary_steps, config=self._session_config) as mon_sess: loss = None while not mon_sess.should_stop(): _, loss = mon_sess.run([model_fn_ops.train_op, model_fn_ops.loss]) return loss def _identity_feature_engineering_fn(features, labels): return features, labels class Estimator(BaseEstimator): """Estimator class is the basic TensorFlow model trainer/evaluator. THIS CLASS IS DEPRECATED. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for general migration instructions. """ def __init__(self, model_fn=None, model_dir=None, config=None, params=None, feature_engineering_fn=None): """Constructs an `Estimator` instance. Args: model_fn: Model function. Follows the signature: * Args: * `features`: single `Tensor` or `dict` of `Tensor`s (depending on data passed to `fit`), * `labels`: `Tensor` or `dict` of `Tensor`s (for multi-head models). If mode is `ModeKeys.INFER`, `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`. * `mode`: Optional. Specifies if this training, evaluation or prediction. See `ModeKeys`. * `params`: Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning. * `config`: Optional configuration object. Will receive what is passed to Estimator in `config` parameter, or the default `config`. Allows updating things in your model_fn based on configuration such as `num_ps_replicas`. * `model_dir`: Optional directory where model parameters, graph etc are saved. Will receive what is passed to Estimator in `model_dir` parameter, or the default `model_dir`. Allows updating things in your model_fn that expect model_dir, such as training hooks. * Returns: `ModelFnOps` Also supports a legacy signature which returns tuple of: * predictions: `Tensor`, `SparseTensor` or dictionary of same. Can also be any type that is convertible to a `Tensor` or `SparseTensor`, or dictionary of same. * loss: Scalar loss `Tensor`. * train_op: Training update `Tensor` or `Operation`. Supports next three signatures for the function: * `(features, labels) -> (predictions, loss, train_op)` * `(features, labels, mode) -> (predictions, loss, train_op)` * `(features, labels, mode, params) -> (predictions, loss, train_op)` * `(features, labels, mode, params, config) -> (predictions, loss, train_op)` * `(features, labels, mode, params, config, model_dir) -> (predictions, loss, train_op)` model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. config: Configuration object. params: `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. feature_engineering_fn: Feature engineering function. Takes features and labels which are the output of `input_fn` and returns features and labels which will be fed into `model_fn`. Please check `model_fn` for a definition of features and labels. Raises: ValueError: parameters of `model_fn` don't match `params`. """ super(Estimator, self).__init__(model_dir=model_dir, config=config) if model_fn is not None: # Check number of arguments of the given function matches requirements. model_fn_args = _model_fn_args(model_fn) if params is not None and 'params' not in model_fn_args: raise ValueError('Estimator\'s model_fn (%s) does not have a params ' 'argument, but params (%s) were passed to the ' 'Estimator\'s constructor.' % (model_fn, params)) if params is None and 'params' in model_fn_args: logging.warning('Estimator\'s model_fn (%s) includes params ' 'argument, but params are not passed to Estimator.', model_fn) self._model_fn = model_fn self.params = params self._feature_engineering_fn = ( feature_engineering_fn or _identity_feature_engineering_fn) def _call_model_fn(self, features, labels, mode, metrics=None, config=None): """Calls model function with support of 2, 3 or 4 arguments. Args: features: features dict. labels: labels dict. mode: ModeKeys metrics: Dict of metrics. config: RunConfig. Returns: A `ModelFnOps` object. If model_fn returns a tuple, wraps them up in a `ModelFnOps` object. Raises: ValueError: if model_fn returns invalid objects. """ features, labels = self._feature_engineering_fn(features, labels) model_fn_args = _model_fn_args(self._model_fn) kwargs = {} if 'mode' in model_fn_args: kwargs['mode'] = mode if 'params' in model_fn_args: kwargs['params'] = self.params if 'config' in model_fn_args: if config: kwargs['config'] = config else: kwargs['config'] = self.config if 'model_dir' in model_fn_args: kwargs['model_dir'] = self.model_dir model_fn_results = self._model_fn(features, labels, **kwargs) if isinstance(model_fn_results, model_fn_lib.ModelFnOps): model_fn_ops = model_fn_results else: # Here model_fn_results should be a tuple with 3 elements. if len(model_fn_results) != 3: raise ValueError('Unrecognized value returned by model_fn, ' 'please return ModelFnOps.') model_fn_ops = model_fn_lib.ModelFnOps( mode=mode, predictions=model_fn_results[0], loss=model_fn_results[1], train_op=model_fn_results[2]) # Custom metrics should overwrite defaults. if metrics: model_fn_ops.eval_metric_ops.update( _make_metrics_ops(metrics, features, labels, model_fn_ops.predictions)) return model_fn_ops def _get_train_ops(self, features, labels): """Method that builds model graph and returns trainer ops. Expected to be overridden by sub-classes that require custom support. This implementation uses `model_fn` passed as parameter to constructor to build model. Args: features: `Tensor` or `dict` of `Tensor` objects. labels: `Tensor` or `dict` of `Tensor` objects. Returns: `ModelFnOps` object. """ return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN) def _get_eval_ops(self, features, labels, metrics): """Method that builds model graph and returns evaluation ops. Expected to be overridden by sub-classes that require custom support. This implementation uses `model_fn` passed as parameter to constructor to build model. Args: features: `Tensor` or `dict` of `Tensor` objects. labels: `Tensor` or `dict` of `Tensor` objects. metrics: Dict of metrics to run. If None, the default metric functions are used; if {}, no metrics are used. Otherwise, `metrics` should map friendly names for the metric to a `MetricSpec` object defining which model outputs to evaluate against which labels with which metric function. Metric ops should support streaming, e.g., returning update_op and value tensors. See more details in `../../../../metrics/python/metrics/ops/streaming_metrics.py` and `../metric_spec.py`. Returns: `ModelFnOps` object. Raises: ValueError: if `metrics` don't match `labels`. """ model_fn_ops = self._call_model_fn(features, labels, model_fn_lib.ModeKeys.EVAL, metrics) if metric_key.MetricKey.LOSS not in model_fn_ops.eval_metric_ops: model_fn_ops.eval_metric_ops[metric_key.MetricKey.LOSS] = ( metrics_lib.mean(model_fn_ops.loss)) return model_fn_ops def _get_predict_ops(self, features): """Method that builds model graph and returns prediction ops. Expected to be overridden by sub-classes that require custom support. This implementation uses `model_fn` passed as parameter to constructor to build model. Args: features: `Tensor` or `dict` of `Tensor` objects. Returns: `ModelFnOps` object. """ labels = tensor_signature.create_placeholders_from_signatures( self._labels_info) return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.INFER) def export_savedmodel(self, export_dir_base, serving_input_fn, default_output_alternative_key=None, assets_extra=None, as_text=False, checkpoint_path=None, graph_rewrite_specs=(GraphRewriteSpec( (tag_constants.SERVING,), ()),), strip_default_attrs=False): # pylint: disable=line-too-long """Exports inference graph as a SavedModel into given dir. Args: export_dir_base: A string containing a directory to write the exported graph and checkpoints. serving_input_fn: A function that takes no argument and returns an `InputFnOps`. default_output_alternative_key: the name of the head to serve when none is specified. Not needed for single-headed models. assets_extra: A dict specifying how to populate the assets.extra directory within the exported SavedModel. Each key should give the destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`. as_text: whether to write the SavedModel proto in text format. checkpoint_path: The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen. graph_rewrite_specs: an iterable of `GraphRewriteSpec`. Each element will produce a separate MetaGraphDef within the exported SavedModel, tagged and rewritten as specified. Defaults to a single entry using the default serving tag ("serve") and no rewriting. strip_default_attrs: Boolean. If `True`, default-valued attributes will be removed from the NodeDefs. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). Returns: The string path to the exported directory. Raises: ValueError: if an unrecognized export_type is requested. """ # pylint: enable=line-too-long if serving_input_fn is None: raise ValueError('serving_input_fn must be defined.') if not checkpoint_path: # Locate the latest checkpoint checkpoint_path = checkpoint_management.latest_checkpoint(self._model_dir) if not checkpoint_path: raise NotFittedError( "Couldn't find trained model at %s." % self._model_dir) export_dir = saved_model_export_utils.get_timestamped_export_dir( export_dir_base) # We'll write the SavedModel to a temporary directory and then atomically # rename it at the end. This helps to avoid corrupt / incomplete outputs, # which could otherwise occur if the job is preempted or otherwise fails # in the middle of SavedModel creation. temp_export_dir = saved_model_export_utils.get_temp_export_dir(export_dir) builder = saved_model_builder.SavedModelBuilder(temp_export_dir) # Build the base graph with ops.Graph().as_default() as g: training_util.create_global_step(g) # Call the serving_input_fn and collect the input alternatives. input_ops = serving_input_fn() input_alternatives, features = ( saved_model_export_utils.get_input_alternatives(input_ops)) # TODO(b/34388557) This is a stopgap, pending recording model provenance. # Record which features are expected at serving time. It is assumed that # these are the features that were used in training. for feature_key in input_ops.features.keys(): ops.add_to_collection( constants.COLLECTION_DEF_KEY_FOR_INPUT_FEATURE_KEYS, feature_key) # Call the model_fn and collect the output alternatives. model_fn_ops = self._call_model_fn(features, None, model_fn_lib.ModeKeys.INFER) output_alternatives, actual_default_output_alternative_key = ( saved_model_export_utils.get_output_alternatives( model_fn_ops, default_output_alternative_key)) init_op = control_flow_ops.group(variables.local_variables_initializer(), resources.initialize_resources( resources.shared_resources()), lookup_ops.tables_initializer()) # Build the SignatureDefs from all pairs of input and output alternatives signature_def_map = saved_model_export_utils.build_all_signature_defs( input_alternatives, output_alternatives, actual_default_output_alternative_key) # Export the first MetaGraphDef with variables, assets etc. with tf_session.Session('') as session: # pylint: disable=protected-access saveables = variables._all_saveable_objects() # pylint: enable=protected-access if (model_fn_ops.scaffold is not None and model_fn_ops.scaffold.saver is not None): saver_for_restore = model_fn_ops.scaffold.saver elif saveables: saver_for_restore = saver.Saver(saveables, sharded=True) saver_for_restore.restore(session, checkpoint_path) # Perform the export if not graph_rewrite_specs or graph_rewrite_specs[0].transforms: raise ValueError('The first element of graph_rewrite_specs ' 'must specify no transforms.') untransformed_tags = graph_rewrite_specs[0].tags builder.add_meta_graph_and_variables( session, untransformed_tags, signature_def_map=signature_def_map, assets_collection=ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS), main_op=init_op, strip_default_attrs=strip_default_attrs) # pylint: disable=protected-access base_meta_graph_def = builder._saved_model.meta_graphs[0] # pylint: enable=protected-access if graph_rewrite_specs[1:]: # Prepare the input_names and output_names needed for the # meta_graph_transform call below. input_names = [ tensor.name for input_dict in input_alternatives.values() for tensor in input_dict.values() ] output_names = [ tensor.name for output_alternative in output_alternatives.values() for tensor in output_alternative[1].values() ] # Write the additional MetaGraphDefs for graph_rewrite_spec in graph_rewrite_specs[1:]: # TODO(soergel) consider moving most of this to saved_model.builder_impl # as e.g. builder.add_rewritten_meta_graph(rewritten_graph_def, tags) transformed_meta_graph_def = meta_graph_transform.meta_graph_transform( base_meta_graph_def, input_names, output_names, graph_rewrite_spec.transforms, graph_rewrite_spec.tags) # pylint: disable=protected-access meta_graph_def = builder._saved_model.meta_graphs.add() # pylint: enable=protected-access meta_graph_def.CopyFrom(transformed_meta_graph_def) # Add the extra assets if assets_extra: assets_extra_path = os.path.join( compat.as_bytes(temp_export_dir), compat.as_bytes('assets.extra')) for dest_relative, source in assets_extra.items(): dest_absolute = os.path.join( compat.as_bytes(assets_extra_path), compat.as_bytes(dest_relative)) dest_path = os.path.dirname(dest_absolute) gfile.MakeDirs(dest_path) gfile.Copy(source, dest_absolute) builder.save(as_text) gfile.Rename(temp_export_dir, export_dir) return export_dir # For time of deprecation x,y from Estimator allow direct access. # pylint: disable=protected-access class SKCompat(sklearn.BaseEstimator): """Scikit learn wrapper for TensorFlow Learn Estimator. THIS CLASS IS DEPRECATED. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for general migration instructions. """ @deprecated(None, 'Please switch to the Estimator interface.') def __init__(self, estimator): self._estimator = estimator def fit(self, x, y, batch_size=128, steps=None, max_steps=None, monitors=None): input_fn, feed_fn = _get_input_fn( x, y, input_fn=None, feed_fn=None, batch_size=batch_size, shuffle=True, epochs=None) all_monitors = [] if feed_fn: all_monitors = [basic_session_run_hooks.FeedFnHook(feed_fn)] if monitors: all_monitors.extend(monitors) self._estimator.fit( input_fn=input_fn, steps=steps, max_steps=max_steps, monitors=all_monitors) return self def score(self, x, y, batch_size=128, steps=None, metrics=None, name=None): input_fn, feed_fn = _get_input_fn( x, y, input_fn=None, feed_fn=None, batch_size=batch_size, shuffle=False, epochs=1) if metrics is not None and not isinstance(metrics, dict): raise ValueError('Metrics argument should be None or dict. ' 'Got %s.' % metrics) eval_results, global_step = self._estimator._evaluate_model( input_fn=input_fn, feed_fn=feed_fn, steps=steps, metrics=metrics, name=name) if eval_results is not None: eval_results.update({'global_step': global_step}) return eval_results def predict(self, x, batch_size=128, outputs=None): input_fn, feed_fn = _get_input_fn( x, None, input_fn=None, feed_fn=None, batch_size=batch_size, shuffle=False, epochs=1) results = list( self._estimator._infer_model( input_fn=input_fn, feed_fn=feed_fn, outputs=outputs, as_iterable=True, iterate_batches=True)) if not isinstance(results[0], dict): return np.concatenate([output for output in results], axis=0) return { key: np.concatenate([output[key] for output in results], axis=0) for key in results[0] }
apache-2.0
horance-liu/tensorflow
tensorflow/contrib/learn/python/learn/estimators/estimator_test.py
21
53471
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Estimator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import itertools import json import os import tempfile import numpy as np import six from six.moves import xrange # pylint: disable=redefined-builtin from google.protobuf import text_format from tensorflow.contrib import learn from tensorflow.contrib import lookup from tensorflow.contrib.framework.python.ops import variables from tensorflow.contrib.layers.python.layers import feature_column as feature_column_lib from tensorflow.contrib.layers.python.layers import optimizers from tensorflow.contrib.learn.python.learn import experiment from tensorflow.contrib.learn.python.learn import models from tensorflow.contrib.learn.python.learn import monitors as monitors_lib from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.contrib.learn.python.learn.estimators import _sklearn from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn.estimators import linear from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.contrib.learn.python.learn.utils import input_fn_utils from tensorflow.contrib.metrics.python.ops import metric_ops from tensorflow.contrib.testing.python.framework import util_test from tensorflow.python.client import session as session_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.lib.io import file_io from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.ops import variables as variables_lib from tensorflow.python.platform import gfile from tensorflow.python.platform import test from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import tag_constants from tensorflow.python.summary import summary from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import checkpoint_state_pb2 from tensorflow.python.training import input as input_lib from tensorflow.python.training import monitored_session from tensorflow.python.training import saver as saver_lib from tensorflow.python.training import session_run_hook from tensorflow.python.util import compat _BOSTON_INPUT_DIM = 13 _IRIS_INPUT_DIM = 4 def boston_input_fn(num_epochs=None): boston = base.load_boston() features = input_lib.limit_epochs( array_ops.reshape( constant_op.constant(boston.data), [-1, _BOSTON_INPUT_DIM]), num_epochs=num_epochs) labels = array_ops.reshape(constant_op.constant(boston.target), [-1, 1]) return features, labels def iris_input_fn(): iris = base.load_iris() features = array_ops.reshape( constant_op.constant(iris.data), [-1, _IRIS_INPUT_DIM]) labels = array_ops.reshape(constant_op.constant(iris.target), [-1]) return features, labels def iris_input_fn_labels_dict(): iris = base.load_iris() features = array_ops.reshape( constant_op.constant(iris.data), [-1, _IRIS_INPUT_DIM]) labels = { 'labels': array_ops.reshape(constant_op.constant(iris.target), [-1]) } return features, labels def boston_eval_fn(): boston = base.load_boston() n_examples = len(boston.target) features = array_ops.reshape( constant_op.constant(boston.data), [n_examples, _BOSTON_INPUT_DIM]) labels = array_ops.reshape( constant_op.constant(boston.target), [n_examples, 1]) return array_ops.concat([features, features], 0), array_ops.concat( [labels, labels], 0) def extract(data, key): if isinstance(data, dict): assert key in data return data[key] else: return data def linear_model_params_fn(features, labels, mode, params): features = extract(features, 'input') labels = extract(labels, 'labels') assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, variables.get_global_step(), optimizer='Adagrad', learning_rate=params['learning_rate']) return prediction, loss, train_op def linear_model_fn(features, labels, mode): features = extract(features, 'input') labels = extract(labels, 'labels') assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) if isinstance(features, dict): (_, features), = features.items() prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, variables.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return prediction, loss, train_op def linear_model_fn_with_model_fn_ops(features, labels, mode): """Same as linear_model_fn, but returns `ModelFnOps`.""" assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) prediction, loss = (models.linear_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, variables.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return model_fn.ModelFnOps( mode=mode, predictions=prediction, loss=loss, train_op=train_op) def logistic_model_no_mode_fn(features, labels): features = extract(features, 'input') labels = extract(labels, 'labels') labels = array_ops.one_hot(labels, 3, 1, 0) prediction, loss = (models.logistic_regression_zero_init(features, labels)) train_op = optimizers.optimize_loss( loss, variables.get_global_step(), optimizer='Adagrad', learning_rate=0.1) return { 'class': math_ops.argmax(prediction, 1), 'prob': prediction }, loss, train_op VOCAB_FILE_CONTENT = 'emerson\nlake\npalmer\n' EXTRA_FILE_CONTENT = 'kermit\npiggy\nralph\n' def _build_estimator_for_export_tests(tmpdir): def _input_fn(): iris = base.load_iris() return { 'feature': constant_op.constant( iris.data, dtype=dtypes.float32) }, constant_op.constant( iris.target, shape=[150], dtype=dtypes.int32) feature_columns = [ feature_column_lib.real_valued_column( 'feature', dimension=4) ] est = linear.LinearRegressor(feature_columns) est.fit(input_fn=_input_fn, steps=20) feature_spec = feature_column_lib.create_feature_spec_for_parsing( feature_columns) serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) # hack in an op that uses an asset, in order to test asset export. # this is not actually valid, of course. def serving_input_fn_with_asset(): features, labels, inputs = serving_input_fn() vocab_file_name = os.path.join(tmpdir, 'my_vocab_file') vocab_file = gfile.GFile(vocab_file_name, mode='w') vocab_file.write(VOCAB_FILE_CONTENT) vocab_file.close() hashtable = lookup.HashTable( lookup.TextFileStringTableInitializer(vocab_file_name), 'x') features['bogus_lookup'] = hashtable.lookup( math_ops.to_int64(features['feature'])) return input_fn_utils.InputFnOps(features, labels, inputs) return est, serving_input_fn_with_asset def _build_estimator_for_resource_export_test(): def _input_fn(): iris = base.load_iris() return { 'feature': constant_op.constant(iris.data, dtype=dtypes.float32) }, constant_op.constant( iris.target, shape=[150], dtype=dtypes.int32) feature_columns = [ feature_column_lib.real_valued_column('feature', dimension=4) ] def resource_constant_model_fn(unused_features, unused_labels, mode): """A model_fn that loads a constant from a resource and serves it.""" assert mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL, model_fn.ModeKeys.INFER) const = constant_op.constant(-1, dtype=dtypes.int64) table = lookup.MutableHashTable( dtypes.string, dtypes.int64, const, name='LookupTableModel') update_global_step = variables.get_global_step().assign_add(1) if mode in (model_fn.ModeKeys.TRAIN, model_fn.ModeKeys.EVAL): key = constant_op.constant(['key']) value = constant_op.constant([42], dtype=dtypes.int64) train_op_1 = table.insert(key, value) training_state = lookup.MutableHashTable( dtypes.string, dtypes.int64, const, name='LookupTableTrainingState') training_op_2 = training_state.insert(key, value) return (const, const, control_flow_ops.group(train_op_1, training_op_2, update_global_step)) if mode == model_fn.ModeKeys.INFER: key = constant_op.constant(['key']) prediction = table.lookup(key) return prediction, const, update_global_step est = estimator.Estimator(model_fn=resource_constant_model_fn) est.fit(input_fn=_input_fn, steps=1) feature_spec = feature_column_lib.create_feature_spec_for_parsing( feature_columns) serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec) return est, serving_input_fn class CheckCallsMonitor(monitors_lib.BaseMonitor): def __init__(self, expect_calls): super(CheckCallsMonitor, self).__init__() self.begin_calls = None self.end_calls = None self.expect_calls = expect_calls def begin(self, max_steps): self.begin_calls = 0 self.end_calls = 0 def step_begin(self, step): self.begin_calls += 1 return {} def step_end(self, step, outputs): self.end_calls += 1 return False def end(self): assert (self.end_calls == self.expect_calls and self.begin_calls == self.expect_calls) def _model_fn_ops( expected_features, expected_labels, actual_features, actual_labels, mode): assert_ops = tuple([ check_ops.assert_equal( expected_features[k], actual_features[k], name='assert_%s' % k) for k in expected_features ] + [ check_ops.assert_equal( expected_labels, actual_labels, name='assert_labels') ]) with ops.control_dependencies(assert_ops): return model_fn.ModelFnOps( mode=mode, predictions=constant_op.constant(0.), loss=constant_op.constant(0.), train_op=variables.get_global_step().assign_add(1)) def _make_input_fn(features, labels): def _input_fn(): return { k: constant_op.constant(v) for k, v in six.iteritems(features) }, constant_op.constant(labels) return _input_fn class EstimatorModelFnTest(test.TestCase): def testModelFnArgs(self): features = {'x': 42., 'y': 43.} labels = 44. expected_params = {'some_param': 'some_value'} expected_config = run_config.RunConfig() expected_config.i_am_test = True # TODO(ptucker): We have to roll our own mock since Estimator._get_arguments # doesn't work with mock fns. model_fn_call_count = [0] # `features` and `labels` are passed by position, `arg0` and `arg1` here. def _model_fn(arg0, arg1, mode, params, config): model_fn_call_count[0] += 1 self.assertItemsEqual(features.keys(), arg0.keys()) self.assertEqual(model_fn.ModeKeys.TRAIN, mode) self.assertEqual(expected_params, params) self.assertTrue(config.i_am_test) return _model_fn_ops(features, labels, arg0, arg1, mode) est = estimator.Estimator( model_fn=_model_fn, params=expected_params, config=expected_config) self.assertEqual(0, model_fn_call_count[0]) est.fit(input_fn=_make_input_fn(features, labels), steps=1) self.assertEqual(1, model_fn_call_count[0]) def testPartialModelFnArgs(self): features = {'x': 42., 'y': 43.} labels = 44. expected_params = {'some_param': 'some_value'} expected_config = run_config.RunConfig() expected_config.i_am_test = True expected_foo = 45. expected_bar = 46. # TODO(ptucker): We have to roll our own mock since Estimator._get_arguments # doesn't work with mock fns. model_fn_call_count = [0] # `features` and `labels` are passed by position, `arg0` and `arg1` here. def _model_fn(arg0, arg1, foo, mode, params, config, bar): model_fn_call_count[0] += 1 self.assertEqual(expected_foo, foo) self.assertEqual(expected_bar, bar) self.assertItemsEqual(features.keys(), arg0.keys()) self.assertEqual(model_fn.ModeKeys.TRAIN, mode) self.assertEqual(expected_params, params) self.assertTrue(config.i_am_test) return _model_fn_ops(features, labels, arg0, arg1, mode) partial_model_fn = functools.partial( _model_fn, foo=expected_foo, bar=expected_bar) est = estimator.Estimator( model_fn=partial_model_fn, params=expected_params, config=expected_config) self.assertEqual(0, model_fn_call_count[0]) est.fit(input_fn=_make_input_fn(features, labels), steps=1) self.assertEqual(1, model_fn_call_count[0]) def testModelFnWithModelDir(self): expected_param = {'some_param': 'some_value'} expected_model_dir = tempfile.mkdtemp() def _argument_checker(features, labels, mode, params, config=None, model_dir=None): _, _, _ = features, labels, config self.assertEqual(model_fn.ModeKeys.TRAIN, mode) self.assertEqual(expected_param, params) self.assertEqual(model_dir, expected_model_dir) return (constant_op.constant(0.), constant_op.constant(0.), variables.get_global_step().assign_add(1)) est = estimator.Estimator(model_fn=_argument_checker, params=expected_param, model_dir=expected_model_dir) est.fit(input_fn=boston_input_fn, steps=1) def testInvalidModelFn_no_train_op(self): def _invalid_model_fn(features, labels): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') update_global_step = variables.get_global_step().assign_add(1) with ops.control_dependencies([update_global_step]): loss = 100.0 - w return None, loss, None est = estimator.Estimator(model_fn=_invalid_model_fn) with self.assertRaisesRegexp(ValueError, 'Missing train_op'): est.fit(input_fn=boston_input_fn, steps=1) def testInvalidModelFn_no_loss(self): def _invalid_model_fn(features, labels, mode): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') loss = 100.0 - w update_global_step = variables.get_global_step().assign_add(1) with ops.control_dependencies([update_global_step]): train_op = w.assign_add(loss / 100.0) predictions = loss if mode == model_fn.ModeKeys.EVAL: loss = None return predictions, loss, train_op est = estimator.Estimator(model_fn=_invalid_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing loss'): est.evaluate(input_fn=boston_eval_fn, steps=1) def testInvalidModelFn_no_prediction(self): def _invalid_model_fn(features, labels): # pylint: disable=unused-argument w = variables_lib.Variable(42.0, 'weight') loss = 100.0 - w update_global_step = variables.get_global_step().assign_add(1) with ops.control_dependencies([update_global_step]): train_op = w.assign_add(loss / 100.0) return None, loss, train_op est = estimator.Estimator(model_fn=_invalid_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.evaluate(input_fn=boston_eval_fn, steps=1) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.predict(input_fn=boston_input_fn) with self.assertRaisesRegexp(ValueError, 'Missing prediction'): est.predict( input_fn=functools.partial( boston_input_fn, num_epochs=1), as_iterable=True) def testModelFnScaffoldInTraining(self): self.is_init_fn_called = False def _init_fn(scaffold, session): _, _ = scaffold, session self.is_init_fn_called = True def _model_fn_scaffold(features, labels, mode): _, _ = features, labels return model_fn.ModelFnOps( mode=mode, predictions=constant_op.constant(0.), loss=constant_op.constant(0.), train_op=variables.get_global_step().assign_add(1), scaffold=monitored_session.Scaffold(init_fn=_init_fn)) est = estimator.Estimator(model_fn=_model_fn_scaffold) est.fit(input_fn=boston_input_fn, steps=1) self.assertTrue(self.is_init_fn_called) def testModelFnScaffoldSaverUsage(self): def _model_fn_scaffold(features, labels, mode): _, _ = features, labels variables_lib.Variable(1., 'weight') real_saver = saver_lib.Saver() self.mock_saver = test.mock.Mock( wraps=real_saver, saver_def=real_saver.saver_def) return model_fn.ModelFnOps( mode=mode, predictions=constant_op.constant([[1.]]), loss=constant_op.constant(0.), train_op=variables.get_global_step().assign_add(1), scaffold=monitored_session.Scaffold(saver=self.mock_saver)) def input_fn(): return { 'x': constant_op.constant([[1.]]), }, constant_op.constant([[1.]]) est = estimator.Estimator(model_fn=_model_fn_scaffold) est.fit(input_fn=input_fn, steps=1) self.assertTrue(self.mock_saver.save.called) est.evaluate(input_fn=input_fn, steps=1) self.assertTrue(self.mock_saver.restore.called) est.predict(input_fn=input_fn) self.assertTrue(self.mock_saver.restore.called) def serving_input_fn(): serialized_tf_example = array_ops.placeholder(dtype=dtypes.string, shape=[None], name='input_example_tensor') features, labels = input_fn() return input_fn_utils.InputFnOps( features, labels, {'examples': serialized_tf_example}) est.export_savedmodel(os.path.join(est.model_dir, 'export'), serving_input_fn) self.assertTrue(self.mock_saver.restore.called) class EstimatorTest(test.TestCase): def testExperimentIntegration(self): exp = experiment.Experiment( estimator=estimator.Estimator(model_fn=linear_model_fn), train_input_fn=boston_input_fn, eval_input_fn=boston_input_fn) exp.test() def testCheckpointSaverHookSuppressesTheDefaultOne(self): saver_hook = test.mock.Mock( spec=basic_session_run_hooks.CheckpointSaverHook) saver_hook.before_run.return_value = None est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1, monitors=[saver_hook]) # test nothing is saved, due to suppressing default saver with self.assertRaises(learn.NotFittedError): est.evaluate(input_fn=boston_input_fn, steps=1) def testCustomConfig(self): test_random_seed = 5783452 class TestInput(object): def __init__(self): self.random_seed = 0 def config_test_input_fn(self): self.random_seed = ops.get_default_graph().seed return constant_op.constant([[1.]]), constant_op.constant([1.]) config = run_config.RunConfig(tf_random_seed=test_random_seed) test_input = TestInput() est = estimator.Estimator(model_fn=linear_model_fn, config=config) est.fit(input_fn=test_input.config_test_input_fn, steps=1) # If input_fn ran, it will have given us the random seed set on the graph. self.assertEquals(test_random_seed, test_input.random_seed) def testRunConfigModelDir(self): config = run_config.RunConfig(model_dir='test_dir') est = estimator.Estimator(model_fn=linear_model_fn, config=config) self.assertEqual('test_dir', est.config.model_dir) self.assertEqual('test_dir', est.model_dir) def testModelDirAndRunConfigModelDir(self): config = run_config.RunConfig(model_dir='test_dir') est = estimator.Estimator(model_fn=linear_model_fn, config=config, model_dir='test_dir') self.assertEqual('test_dir', est.config.model_dir) with self.assertRaisesRegexp( ValueError, 'model_dir are set both in constructor and RunConfig, ' 'but with different'): estimator.Estimator(model_fn=linear_model_fn, config=config, model_dir='different_dir') def testModelDirIsCopiedToRunConfig(self): config = run_config.RunConfig() self.assertIsNone(config.model_dir) est = estimator.Estimator(model_fn=linear_model_fn, model_dir='test_dir', config=config) self.assertEqual('test_dir', est.config.model_dir) self.assertEqual('test_dir', est.model_dir) def testModelDirAsTempDir(self): with test.mock.patch.object(tempfile, 'mkdtemp', return_value='temp_dir'): est = estimator.Estimator(model_fn=linear_model_fn) self.assertEqual('temp_dir', est.config.model_dir) self.assertEqual('temp_dir', est.model_dir) def testCheckInputs(self): est = estimator.SKCompat(estimator.Estimator(model_fn=linear_model_fn)) # Lambdas so we have to different objects to compare right_features = lambda: np.ones(shape=[7, 8], dtype=np.float32) right_labels = lambda: np.ones(shape=[7, 10], dtype=np.int32) est.fit(right_features(), right_labels(), steps=1) # TODO(wicke): This does not fail for np.int32 because of data_feeder magic. wrong_type_features = np.ones(shape=[7, 8], dtype=np.int64) wrong_size_features = np.ones(shape=[7, 10]) wrong_type_labels = np.ones(shape=[7, 10], dtype=np.float32) wrong_size_labels = np.ones(shape=[7, 11]) est.fit(x=right_features(), y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=wrong_type_features, y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=wrong_size_features, y=right_labels(), steps=1) with self.assertRaises(ValueError): est.fit(x=right_features(), y=wrong_type_labels, steps=1) with self.assertRaises(ValueError): est.fit(x=right_features(), y=wrong_size_labels, steps=1) def testBadInput(self): est = estimator.Estimator(model_fn=linear_model_fn) self.assertRaisesRegexp( ValueError, 'Either x or input_fn must be provided.', est.fit, x=None, input_fn=None, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and x or y', est.fit, x='X', input_fn=iris_input_fn, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and x or y', est.fit, y='Y', input_fn=iris_input_fn, steps=1) self.assertRaisesRegexp( ValueError, 'Can not provide both input_fn and batch_size', est.fit, input_fn=iris_input_fn, batch_size=100, steps=1) self.assertRaisesRegexp( ValueError, 'Inputs cannot be tensors. Please provide input_fn.', est.fit, x=constant_op.constant(1.), steps=1) def testUntrained(self): boston = base.load_boston() est = estimator.SKCompat(estimator.Estimator(model_fn=linear_model_fn)) with self.assertRaises(learn.NotFittedError): _ = est.score(x=boston.data, y=boston.target.astype(np.float64)) with self.assertRaises(learn.NotFittedError): est.predict(x=boston.data) def testContinueTraining(self): boston = base.load_boston() output_dir = tempfile.mkdtemp() est = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_fn, model_dir=output_dir)) float64_labels = boston.target.astype(np.float64) est.fit(x=boston.data, y=float64_labels, steps=50) scores = est.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) del est # Create another estimator object with the same output dir. est2 = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_fn, model_dir=output_dir)) # Check we can evaluate and predict. scores2 = est2.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) self.assertAllClose(scores['MSE'], scores2['MSE']) predictions = np.array(list(est2.predict(x=boston.data))) other_score = _sklearn.mean_squared_error(predictions, float64_labels) self.assertAllClose(scores['MSE'], other_score) # Check we can keep training. est2.fit(x=boston.data, y=float64_labels, steps=100) scores3 = est2.score( x=boston.data, y=float64_labels, metrics={'MSE': metric_ops.streaming_mean_squared_error}) self.assertLess(scores3['MSE'], scores['MSE']) def test_checkpoint_contains_relative_paths(self): tmpdir = tempfile.mkdtemp() est = estimator.Estimator( model_dir=tmpdir, model_fn=linear_model_fn_with_model_fn_ops) est.fit(input_fn=boston_input_fn, steps=5) checkpoint_file_content = file_io.read_file_to_string( os.path.join(tmpdir, 'checkpoint')) ckpt = checkpoint_state_pb2.CheckpointState() text_format.Merge(checkpoint_file_content, ckpt) self.assertEqual(ckpt.model_checkpoint_path, 'model.ckpt-5') self.assertAllEqual( ['model.ckpt-1', 'model.ckpt-5'], ckpt.all_model_checkpoint_paths) def test_train_save_copy_reload(self): tmpdir = tempfile.mkdtemp() model_dir1 = os.path.join(tmpdir, 'model_dir1') est1 = estimator.Estimator( model_dir=model_dir1, model_fn=linear_model_fn_with_model_fn_ops) est1.fit(input_fn=boston_input_fn, steps=5) model_dir2 = os.path.join(tmpdir, 'model_dir2') os.renames(model_dir1, model_dir2) est2 = estimator.Estimator( model_dir=model_dir2, model_fn=linear_model_fn_with_model_fn_ops) self.assertEqual(5, est2.get_variable_value('global_step')) est2.fit(input_fn=boston_input_fn, steps=5) self.assertEqual(10, est2.get_variable_value('global_step')) def testEstimatorParams(self): boston = base.load_boston() est = estimator.SKCompat( estimator.Estimator( model_fn=linear_model_params_fn, params={'learning_rate': 0.01})) est.fit(x=boston.data, y=boston.target, steps=100) def testHooksNotChanged(self): est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) # We pass empty array and expect it to remain empty after calling # fit and evaluate. Requires inside to copy this array if any hooks were # added. my_array = [] est.fit(input_fn=iris_input_fn, steps=100, monitors=my_array) _ = est.evaluate(input_fn=iris_input_fn, steps=1, hooks=my_array) self.assertEqual(my_array, []) def testIrisIterator(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = itertools.islice(iris.target, 100) estimator.SKCompat(est).fit(x_iter, y_iter, steps=20) eval_result = est.evaluate(input_fn=iris_input_fn, steps=1) x_iter_eval = itertools.islice(iris.data, 100) y_iter_eval = itertools.islice(iris.target, 100) score_result = estimator.SKCompat(est).score(x_iter_eval, y_iter_eval) print(score_result) self.assertItemsEqual(eval_result.keys(), score_result.keys()) self.assertItemsEqual(['global_step', 'loss'], score_result.keys()) predictions = estimator.SKCompat(est).predict(x=iris.data)['class'] self.assertEqual(len(predictions), iris.target.shape[0]) def testIrisIteratorArray(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = (np.array(x) for x in iris.target) est.fit(x_iter, y_iter, steps=100) _ = est.evaluate(input_fn=iris_input_fn, steps=1) _ = six.next(est.predict(x=iris.data))['class'] def testIrisIteratorPlainInt(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 100) y_iter = (v for v in iris.target) est.fit(x_iter, y_iter, steps=100) _ = est.evaluate(input_fn=iris_input_fn, steps=1) _ = six.next(est.predict(x=iris.data))['class'] def testIrisTruncatedIterator(self): iris = base.load_iris() est = estimator.Estimator(model_fn=logistic_model_no_mode_fn) x_iter = itertools.islice(iris.data, 50) y_iter = ([np.int32(v)] for v in iris.target) est.fit(x_iter, y_iter, steps=100) def testTrainStepsIsIncremental(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=10) self.assertEqual(10, est.get_variable_value('global_step')) est.fit(input_fn=boston_input_fn, steps=15) self.assertEqual(25, est.get_variable_value('global_step')) def testTrainMaxStepsIsNotIncremental(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, max_steps=10) self.assertEqual(10, est.get_variable_value('global_step')) est.fit(input_fn=boston_input_fn, max_steps=15) self.assertEqual(15, est.get_variable_value('global_step')) def testPredict(self): est = estimator.Estimator(model_fn=linear_model_fn) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) output = list(est.predict(x=boston.data, batch_size=10)) self.assertEqual(len(output), boston.target.shape[0]) def testWithModelFnOps(self): """Test for model_fn that returns `ModelFnOps`.""" est = estimator.Estimator(model_fn=linear_model_fn_with_model_fn_ops) boston = base.load_boston() est.fit(input_fn=boston_input_fn, steps=1) input_fn = functools.partial(boston_input_fn, num_epochs=1) scores = est.evaluate(input_fn=input_fn, steps=1) self.assertIn('loss', scores.keys()) output = list(est.predict(input_fn=input_fn)) self.assertEqual(len(output), boston.target.shape[0]) def testWrongInput(self): def other_input_fn(): return { 'other': constant_op.constant([0, 0, 0]) }, constant_op.constant([0, 0, 0]) est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1) with self.assertRaises(ValueError): est.fit(input_fn=other_input_fn, steps=1) def testMonitorsForFit(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=21, monitors=[CheckCallsMonitor(expect_calls=21)]) def testHooksForEvaluate(self): class CheckCallHook(session_run_hook.SessionRunHook): def __init__(self): self.run_count = 0 def after_run(self, run_context, run_values): self.run_count += 1 est = learn.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=1) hook = CheckCallHook() est.evaluate(input_fn=boston_eval_fn, steps=3, hooks=[hook]) self.assertEqual(3, hook.run_count) def testSummaryWriting(self): est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=200) est.evaluate(input_fn=boston_input_fn, steps=200) loss_summary = util_test.simple_values_from_events( util_test.latest_events(est.model_dir), ['OptimizeLoss/loss']) self.assertEqual(1, len(loss_summary)) def testSummaryWritingWithSummaryProto(self): def _streaming_mean_squared_error_histogram(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): metrics, update_ops = metric_ops.streaming_mean_squared_error( predictions, labels, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_collections, name=name) return summary.histogram('histogram', metrics), update_ops est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=200) est.evaluate( input_fn=boston_input_fn, steps=200, metrics={'MSE': _streaming_mean_squared_error_histogram}) events = util_test.latest_events(est.model_dir + '/eval') output_values = {} for e in events: if e.HasField('summary'): for v in e.summary.value: output_values[v.tag] = v self.assertTrue('MSE' in output_values) self.assertTrue(output_values['MSE'].HasField('histo')) def testLossInGraphCollection(self): class _LossCheckerHook(session_run_hook.SessionRunHook): def begin(self): self.loss_collection = ops.get_collection(ops.GraphKeys.LOSSES) hook = _LossCheckerHook() est = estimator.Estimator(model_fn=linear_model_fn) est.fit(input_fn=boston_input_fn, steps=200, monitors=[hook]) self.assertTrue(hook.loss_collection) def test_export_returns_exported_dirname(self): expected = '/path/to/some_dir' with test.mock.patch.object(estimator, 'export') as mock_export_module: mock_export_module._export_estimator.return_value = expected est = estimator.Estimator(model_fn=linear_model_fn) actual = est.export('/path/to') self.assertEquals(expected, actual) def test_export_savedmodel(self): tmpdir = tempfile.mkdtemp() est, serving_input_fn = _build_estimator_for_export_tests(tmpdir) extra_file_name = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_extra_file')) extra_file = gfile.GFile(extra_file_name, mode='w') extra_file.write(EXTRA_FILE_CONTENT) extra_file.close() assets_extra = {'some/sub/directory/my_extra_file': extra_file_name} export_dir_base = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('export')) export_dir = est.export_savedmodel( export_dir_base, serving_input_fn, assets_extra=assets_extra) self.assertTrue(gfile.Exists(export_dir_base)) self.assertTrue(gfile.Exists(export_dir)) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes( 'saved_model.pb')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.index')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.data-00000-of-00001')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file')))) self.assertEqual( compat.as_bytes(VOCAB_FILE_CONTENT), compat.as_bytes( gfile.GFile( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file'))).read())) expected_extra_path = os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra/some/sub/directory/my_extra_file')) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra')))) self.assertTrue(gfile.Exists(expected_extra_path)) self.assertEqual( compat.as_bytes(EXTRA_FILE_CONTENT), compat.as_bytes(gfile.GFile(expected_extra_path).read())) expected_vocab_file = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_vocab_file')) # Restore, to validate that the export was well-formed. with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, [tag_constants.SERVING], export_dir) assets = [ x.eval() for x in graph.get_collection(ops.GraphKeys.ASSET_FILEPATHS) ] self.assertItemsEqual([expected_vocab_file], assets) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('linear/linear/feature/matmul' in graph_ops) self.assertItemsEqual( ['bogus_lookup', 'feature'], [compat.as_str_any(x) for x in graph.get_collection( constants.COLLECTION_DEF_KEY_FOR_INPUT_FEATURE_KEYS)]) # cleanup gfile.DeleteRecursively(tmpdir) def test_export_savedmodel_with_resource(self): tmpdir = tempfile.mkdtemp() est, serving_input_fn = _build_estimator_for_resource_export_test() export_dir_base = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('export')) export_dir = est.export_savedmodel(export_dir_base, serving_input_fn) self.assertTrue(gfile.Exists(export_dir_base)) self.assertTrue(gfile.Exists(export_dir)) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes( 'saved_model.pb')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.index')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.data-00000-of-00001')))) # Restore, to validate that the export was well-formed. with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, [tag_constants.SERVING], export_dir) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('LookupTableModel' in graph_ops) self.assertFalse('LookupTableTrainingState' in graph_ops) # cleanup gfile.DeleteRecursively(tmpdir) def test_export_savedmodel_with_graph_transforms(self): tmpdir = tempfile.mkdtemp() est, serving_input_fn = _build_estimator_for_export_tests(tmpdir) extra_file_name = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_extra_file')) extra_file = gfile.GFile(extra_file_name, mode='w') extra_file.write(EXTRA_FILE_CONTENT) extra_file.close() assets_extra = {'some/sub/directory/my_extra_file': extra_file_name} export_dir_base = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('export')) export_dir = est.export_savedmodel( export_dir_base, serving_input_fn, assets_extra=assets_extra, graph_rewrite_specs=[ estimator.GraphRewriteSpec(['tag_1'], []), estimator.GraphRewriteSpec(['tag_2', 'tag_3'], ['strip_unused_nodes'])]) self.assertTrue(gfile.Exists(export_dir_base)) self.assertTrue(gfile.Exists(export_dir)) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes( 'saved_model.pb')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.index')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('variables/variables.data-00000-of-00001')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets')))) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file')))) self.assertEqual( compat.as_bytes(VOCAB_FILE_CONTENT), compat.as_bytes( gfile.GFile( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets/my_vocab_file'))).read())) expected_extra_path = os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra/some/sub/directory/my_extra_file')) self.assertTrue( gfile.Exists( os.path.join( compat.as_bytes(export_dir), compat.as_bytes('assets.extra')))) self.assertTrue(gfile.Exists(expected_extra_path)) self.assertEqual( compat.as_bytes(EXTRA_FILE_CONTENT), compat.as_bytes(gfile.GFile(expected_extra_path).read())) expected_vocab_file = os.path.join( compat.as_bytes(tmpdir), compat.as_bytes('my_vocab_file')) # Restore, to validate that the export was well-formed. # tag_1 is untransformed. tags = ['tag_1'] with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, tags, export_dir) assets = [ x.eval() for x in graph.get_collection(ops.GraphKeys.ASSET_FILEPATHS) ] self.assertItemsEqual([expected_vocab_file], assets) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('linear/linear/feature/matmul' in graph_ops) # Since there were no transforms, both save ops are still present. self.assertTrue('save/SaveV2/tensor_names' in graph_ops) self.assertTrue('save_1/SaveV2/tensor_names' in graph_ops) # Since there were no transforms, the hash table lookup is still there. self.assertTrue('hash_table_Lookup' in graph_ops) # Restore, to validate that the export was well-formed. # tag_2, tag_3 was subjected to strip_unused_nodes. tags = ['tag_2', 'tag_3'] with ops.Graph().as_default() as graph: with session_lib.Session(graph=graph) as sess: loader.load(sess, tags, export_dir) assets = [ x.eval() for x in graph.get_collection(ops.GraphKeys.ASSET_FILEPATHS) ] self.assertItemsEqual([expected_vocab_file], assets) graph_ops = [x.name for x in graph.get_operations()] self.assertTrue('input_example_tensor' in graph_ops) self.assertTrue('ParseExample/ParseExample' in graph_ops) self.assertTrue('linear/linear/feature/matmul' in graph_ops) # The Saver used to restore the checkpoint into the export Session # was not added to the SAVERS collection, so strip_unused_nodes removes # it. The one explicitly created in export_savedmodel is tracked in # the MetaGraphDef saver_def field, so that one is retained. # TODO(soergel): Make Savers sane again. I understand this is all a bit # nuts but for now the test demonstrates what actually happens. self.assertFalse('save/SaveV2/tensor_names' in graph_ops) self.assertTrue('save_1/SaveV2/tensor_names' in graph_ops) # The fake hash table lookup wasn't connected to anything; stripped. self.assertFalse('hash_table_Lookup' in graph_ops) # cleanup gfile.DeleteRecursively(tmpdir) class InferRealValuedColumnsTest(test.TestCase): def testInvalidArgs(self): with self.assertRaisesRegexp(ValueError, 'x or input_fn must be provided'): estimator.infer_real_valued_columns_from_input(None) with self.assertRaisesRegexp(ValueError, 'cannot be tensors'): estimator.infer_real_valued_columns_from_input(constant_op.constant(1.0)) def _assert_single_feature_column(self, expected_shape, expected_dtype, feature_columns): self.assertEqual(1, len(feature_columns)) feature_column = feature_columns[0] self.assertEqual('', feature_column.name) self.assertEqual( { '': parsing_ops.FixedLenFeature( shape=expected_shape, dtype=expected_dtype) }, feature_column.config) def testInt32Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.int32)) self._assert_single_feature_column([8], dtypes.int32, feature_columns) def testInt32InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.int32), None)) self._assert_single_feature_column([8], dtypes.int32, feature_columns) def testInt64Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.int64)) self._assert_single_feature_column([8], dtypes.int64, feature_columns) def testInt64InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.int64), None)) self._assert_single_feature_column([8], dtypes.int64, feature_columns) def testFloat32Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.float32)) self._assert_single_feature_column([8], dtypes.float32, feature_columns) def testFloat32InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.float32), None)) self._assert_single_feature_column([8], dtypes.float32, feature_columns) def testFloat64Input(self): feature_columns = estimator.infer_real_valued_columns_from_input( np.ones( shape=[7, 8], dtype=np.float64)) self._assert_single_feature_column([8], dtypes.float64, feature_columns) def testFloat64InputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( lambda: (array_ops.ones(shape=[7, 8], dtype=dtypes.float64), None)) self._assert_single_feature_column([8], dtypes.float64, feature_columns) def testBoolInput(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): estimator.infer_real_valued_columns_from_input( np.array([[False for _ in xrange(8)] for _ in xrange(7)])) def testBoolInputFn(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input_fn( lambda: (constant_op.constant(False, shape=[7, 8], dtype=dtypes.bool), None)) def testStringInput(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input( np.array([['%d.0' % i for i in xrange(8)] for _ in xrange(7)])) def testStringInputFn(self): with self.assertRaisesRegexp( ValueError, 'on integer or non floating types are not supported'): # pylint: disable=g-long-lambda estimator.infer_real_valued_columns_from_input_fn( lambda: ( constant_op.constant([['%d.0' % i for i in xrange(8)] for _ in xrange(7)]), None)) def testBostonInputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( boston_input_fn) self._assert_single_feature_column([_BOSTON_INPUT_DIM], dtypes.float64, feature_columns) def testIrisInputFn(self): feature_columns = estimator.infer_real_valued_columns_from_input_fn( iris_input_fn) self._assert_single_feature_column([_IRIS_INPUT_DIM], dtypes.float64, feature_columns) class ReplicaDeviceSetterTest(test.TestCase): def testVariablesAreOnPs(self): tf_config = {'cluster': {run_config.TaskType.PS: ['fake_ps_0']}} with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('/job:ps/task:0', v.device) self.assertDeviceEqual('/job:ps/task:0', v.initializer.device) self.assertDeviceEqual('/job:ps/task:0', w.device) self.assertDeviceEqual('/job:ps/task:0', w.initializer.device) self.assertDeviceEqual('/job:worker', a.device) def testVariablesAreLocal(self): with ops.device( estimator._get_replica_device_setter(run_config.RunConfig())): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('', v.device) self.assertDeviceEqual('', v.initializer.device) self.assertDeviceEqual('', w.device) self.assertDeviceEqual('', w.initializer.device) self.assertDeviceEqual('', a.device) def testMutableHashTableIsOnPs(self): tf_config = {'cluster': {run_config.TaskType.PS: ['fake_ps_0']}} with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): default_val = constant_op.constant([-1, -1], dtypes.int64) table = lookup.MutableHashTable(dtypes.string, dtypes.int64, default_val) input_string = constant_op.constant(['brain', 'salad', 'tank']) output = table.lookup(input_string) self.assertDeviceEqual('/job:ps/task:0', table._table_ref.device) self.assertDeviceEqual('/job:ps/task:0', output.device) def testMutableHashTableIsLocal(self): with ops.device( estimator._get_replica_device_setter(run_config.RunConfig())): default_val = constant_op.constant([-1, -1], dtypes.int64) table = lookup.MutableHashTable(dtypes.string, dtypes.int64, default_val) input_string = constant_op.constant(['brain', 'salad', 'tank']) output = table.lookup(input_string) self.assertDeviceEqual('', table._table_ref.device) self.assertDeviceEqual('', output.device) def testTaskIsSetOnWorkerWhenJobNameIsSet(self): tf_config = { 'cluster': { run_config.TaskType.PS: ['fake_ps_0'] }, 'task': { 'type': run_config.TaskType.WORKER, 'index': 3 } } with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() with ops.device(estimator._get_replica_device_setter(config)): v = variables_lib.Variable([1, 2]) w = variables_lib.Variable([2, 1]) a = v + w self.assertDeviceEqual('/job:ps/task:0', v.device) self.assertDeviceEqual('/job:ps/task:0', v.initializer.device) self.assertDeviceEqual('/job:ps/task:0', w.device) self.assertDeviceEqual('/job:ps/task:0', w.initializer.device) self.assertDeviceEqual('/job:worker/task:3', a.device) if __name__ == '__main__': test.main()
apache-2.0
moutai/scikit-learn
sklearn/cluster/tests/test_k_means.py
10
29147
"""Testing for K-means""" import sys import numpy as np from scipy import sparse as sp from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import SkipTest from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regex from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_warns from sklearn.utils.testing import if_safe_multiprocessing_with_blas from sklearn.utils.testing import if_not_mac_os from sklearn.utils.testing import assert_raise_message from sklearn.utils.extmath import row_norms from sklearn.metrics.cluster import v_measure_score from sklearn.cluster import KMeans, k_means from sklearn.cluster import MiniBatchKMeans from sklearn.cluster.k_means_ import _labels_inertia from sklearn.cluster.k_means_ import _mini_batch_step from sklearn.datasets.samples_generator import make_blobs from sklearn.externals.six.moves import cStringIO as StringIO from sklearn.exceptions import DataConversionWarning from sklearn.metrics.cluster import homogeneity_score # non centered, sparse centers to check the centers = np.array([ [0.0, 5.0, 0.0, 0.0, 0.0], [1.0, 1.0, 4.0, 0.0, 0.0], [1.0, 0.0, 0.0, 5.0, 1.0], ]) n_samples = 100 n_clusters, n_features = centers.shape X, true_labels = make_blobs(n_samples=n_samples, centers=centers, cluster_std=1., random_state=42) X_csr = sp.csr_matrix(X) def test_kmeans_dtype(): rnd = np.random.RandomState(0) X = rnd.normal(size=(40, 2)) X = (X * 10).astype(np.uint8) km = KMeans(n_init=1).fit(X) pred_x = assert_warns(DataConversionWarning, km.predict, X) assert_array_equal(km.labels_, pred_x) def test_elkan_results(): rnd = np.random.RandomState(0) X_normal = rnd.normal(size=(50, 10)) X_blobs, _ = make_blobs(random_state=0) km_full = KMeans(algorithm='full', n_clusters=5, random_state=0, n_init=1) km_elkan = KMeans(algorithm='elkan', n_clusters=5, random_state=0, n_init=1) for X in [X_normal, X_blobs]: km_full.fit(X) km_elkan.fit(X) assert_array_almost_equal(km_elkan.cluster_centers_, km_full.cluster_centers_) assert_array_equal(km_elkan.labels_, km_full.labels_) def test_labels_assignment_and_inertia(): # pure numpy implementation as easily auditable reference gold # implementation rng = np.random.RandomState(42) noisy_centers = centers + rng.normal(size=centers.shape) labels_gold = - np.ones(n_samples, dtype=np.int) mindist = np.empty(n_samples) mindist.fill(np.infty) for center_id in range(n_clusters): dist = np.sum((X - noisy_centers[center_id]) ** 2, axis=1) labels_gold[dist < mindist] = center_id mindist = np.minimum(dist, mindist) inertia_gold = mindist.sum() assert_true((mindist >= 0.0).all()) assert_true((labels_gold != -1).all()) # perform label assignment using the dense array input x_squared_norms = (X ** 2).sum(axis=1) labels_array, inertia_array = _labels_inertia( X, x_squared_norms, noisy_centers) assert_array_almost_equal(inertia_array, inertia_gold) assert_array_equal(labels_array, labels_gold) # perform label assignment using the sparse CSR input x_squared_norms_from_csr = row_norms(X_csr, squared=True) labels_csr, inertia_csr = _labels_inertia( X_csr, x_squared_norms_from_csr, noisy_centers) assert_array_almost_equal(inertia_csr, inertia_gold) assert_array_equal(labels_csr, labels_gold) def test_minibatch_update_consistency(): # Check that dense and sparse minibatch update give the same results rng = np.random.RandomState(42) old_centers = centers + rng.normal(size=centers.shape) new_centers = old_centers.copy() new_centers_csr = old_centers.copy() counts = np.zeros(new_centers.shape[0], dtype=np.int32) counts_csr = np.zeros(new_centers.shape[0], dtype=np.int32) x_squared_norms = (X ** 2).sum(axis=1) x_squared_norms_csr = row_norms(X_csr, squared=True) buffer = np.zeros(centers.shape[1], dtype=np.double) buffer_csr = np.zeros(centers.shape[1], dtype=np.double) # extract a small minibatch X_mb = X[:10] X_mb_csr = X_csr[:10] x_mb_squared_norms = x_squared_norms[:10] x_mb_squared_norms_csr = x_squared_norms_csr[:10] # step 1: compute the dense minibatch update old_inertia, incremental_diff = _mini_batch_step( X_mb, x_mb_squared_norms, new_centers, counts, buffer, 1, None, random_reassign=False) 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_greater(new_inertia, 0.0) assert_less(new_inertia, old_inertia) # check that the incremental difference computation is matching the # final observed value effective_diff = np.sum((new_centers - old_centers) ** 2) assert_almost_equal(incremental_diff, effective_diff) # step 2: compute the sparse minibatch update 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, None, random_reassign=False) 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_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 effective_diff = np.sum((new_centers_csr - old_centers) ** 2) assert_almost_equal(incremental_diff_csr, effective_diff) # step 3: check that sparse and dense updates lead to the same results assert_array_equal(labels, labels_csr) assert_array_almost_equal(new_centers, new_centers_csr) assert_almost_equal(incremental_diff, incremental_diff_csr) assert_almost_equal(old_inertia, old_inertia_csr) assert_almost_equal(new_inertia, new_inertia_csr) def _check_fitted_model(km): # check that the number of clusters centers and distinct labels match # the expectation centers = km.cluster_centers_ assert_equal(centers.shape, (n_clusters, n_features)) labels = km.labels_ assert_equal(np.unique(labels).shape[0], n_clusters) # check that the labels assignment are perfect (up to a permutation) assert_equal(v_measure_score(true_labels, labels), 1.0) assert_greater(km.inertia_, 0.0) # check error on dataset being too small assert_raises(ValueError, km.fit, [[0., 1.]]) def test_k_means_plus_plus_init(): km = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42).fit(X) _check_fitted_model(km) def test_k_means_new_centers(): # Explore the part of the code where a new center is reassigned X = np.array([[0, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0]]) labels = [0, 1, 2, 1, 1, 2] bad_centers = np.array([[+0, 1, 0, 0], [.2, 0, .2, .2], [+0, 0, 0, 0]]) km = KMeans(n_clusters=3, init=bad_centers, n_init=1, max_iter=10, random_state=1) for this_X in (X, sp.coo_matrix(X)): km.fit(this_X) this_labels = km.labels_ # Reorder the labels so that the first instance is in cluster 0, # the second in cluster 1, ... this_labels = np.unique(this_labels, return_index=True)[1][this_labels] np.testing.assert_array_equal(this_labels, labels) @if_safe_multiprocessing_with_blas def test_k_means_plus_plus_init_2_jobs(): if sys.version_info[:2] < (3, 4): raise SkipTest( "Possible multi-process bug with some BLAS under Python < 3.4") km = KMeans(init="k-means++", n_clusters=n_clusters, n_jobs=2, random_state=42).fit(X) _check_fitted_model(km) def test_k_means_precompute_distances_flag(): # check that a warning is raised if the precompute_distances flag is not # supported km = KMeans(precompute_distances="wrong") assert_raises(ValueError, km.fit, X) def test_k_means_plus_plus_init_sparse(): km = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42) km.fit(X_csr) _check_fitted_model(km) def test_k_means_random_init(): km = KMeans(init="random", n_clusters=n_clusters, random_state=42) km.fit(X) _check_fitted_model(km) def test_k_means_random_init_sparse(): km = KMeans(init="random", n_clusters=n_clusters, random_state=42) km.fit(X_csr) _check_fitted_model(km) def test_k_means_plus_plus_init_not_precomputed(): km = KMeans(init="k-means++", n_clusters=n_clusters, random_state=42, precompute_distances=False).fit(X) _check_fitted_model(km) def test_k_means_random_init_not_precomputed(): km = KMeans(init="random", n_clusters=n_clusters, random_state=42, precompute_distances=False).fit(X) _check_fitted_model(km) def test_k_means_perfect_init(): km = KMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, n_init=1) km.fit(X) _check_fitted_model(km) 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) def test_k_means_explicit_init_shape(): # test for sensible errors when giving explicit init # with wrong number of features or clusters rnd = np.random.RandomState(0) X = rnd.normal(size=(40, 3)) for Class in [KMeans, MiniBatchKMeans]: # mismatch of number of features km = Class(n_init=1, init=X[:, :2], n_clusters=len(X)) msg = "does not match the number of features of the data" assert_raises_regex(ValueError, msg, km.fit, X) # for callable init km = Class(n_init=1, init=lambda X_, k, random_state: X_[:, :2], n_clusters=len(X)) assert_raises_regex(ValueError, msg, km.fit, X) # mismatch of number of clusters msg = "does not match the number of clusters" km = Class(n_init=1, init=X[:2, :], n_clusters=3) assert_raises_regex(ValueError, msg, km.fit, X) # for callable init km = Class(n_init=1, init=lambda X_, k, random_state: X_[:2, :], n_clusters=3) assert_raises_regex(ValueError, msg, km.fit, X) def test_k_means_fortran_aligned_data(): # Check the KMeans will work well, even if X is a fortran-aligned data. X = np.asfortranarray([[0, 0], [0, 1], [0, 1]]) centers = np.array([[0, 0], [0, 1]]) labels = np.array([0, 1, 1]) km = KMeans(n_init=1, init=centers, precompute_distances=False, random_state=42, n_clusters=2) km.fit(X) assert_array_equal(km.cluster_centers_, centers) assert_array_equal(km.labels_, labels) def test_mb_k_means_plus_plus_init_dense_array(): mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, random_state=42) mb_k_means.fit(X) _check_fitted_model(mb_k_means) def test_mb_kmeans_verbose(): mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, random_state=42, verbose=1) old_stdout = sys.stdout sys.stdout = StringIO() try: mb_k_means.fit(X) finally: sys.stdout = old_stdout def test_mb_k_means_plus_plus_init_sparse_matrix(): mb_k_means = MiniBatchKMeans(init="k-means++", n_clusters=n_clusters, random_state=42) mb_k_means.fit(X_csr) _check_fitted_model(mb_k_means) def test_minibatch_init_with_large_k(): mb_k_means = MiniBatchKMeans(init='k-means++', init_size=10, n_clusters=20) # Check that a warning is raised, as the number clusters is larger # than the init_size assert_warns(RuntimeWarning, mb_k_means.fit, X) def test_minibatch_k_means_random_init_dense_array(): # increase n_init to make random init stable enough mb_k_means = MiniBatchKMeans(init="random", n_clusters=n_clusters, random_state=42, n_init=10).fit(X) _check_fitted_model(mb_k_means) def test_minibatch_k_means_random_init_sparse_csr(): # increase n_init to make random init stable enough mb_k_means = MiniBatchKMeans(init="random", n_clusters=n_clusters, random_state=42, n_init=10).fit(X_csr) _check_fitted_model(mb_k_means) def test_minibatch_k_means_perfect_init_dense_array(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, n_init=1).fit(X) _check_fitted_model(mb_k_means) def test_minibatch_k_means_init_multiple_runs_with_explicit_centers(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, n_init=10) assert_warns(RuntimeWarning, mb_k_means.fit, X) def test_minibatch_k_means_perfect_init_sparse_csr(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, random_state=42, n_init=1).fit(X_csr) _check_fitted_model(mb_k_means) def test_minibatch_sensible_reassign_fit(): # check if identical initial clusters are reassigned # also a regression test for when there are more desired reassignments than # samples. zeroed_X, true_labels = make_blobs(n_samples=100, centers=5, cluster_std=1., random_state=42) zeroed_X[::2, :] = 0 mb_k_means = MiniBatchKMeans(n_clusters=20, batch_size=10, random_state=42, init="random") mb_k_means.fit(zeroed_X) # there should not be too many exact zero cluster centers assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) # do the same with batch-size > X.shape[0] (regression test) mb_k_means = MiniBatchKMeans(n_clusters=20, batch_size=201, random_state=42, init="random") mb_k_means.fit(zeroed_X) # there should not be too many exact zero cluster centers assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) def test_minibatch_sensible_reassign_partial_fit(): zeroed_X, true_labels = make_blobs(n_samples=n_samples, centers=5, cluster_std=1., random_state=42) zeroed_X[::2, :] = 0 mb_k_means = MiniBatchKMeans(n_clusters=20, random_state=42, init="random") for i in range(100): mb_k_means.partial_fit(zeroed_X) # there should not be too many exact zero cluster centers assert_greater(mb_k_means.cluster_centers_.any(axis=1).sum(), 10) def test_minibatch_reassign(): # Give a perfect initialization, but a large reassignment_ratio, # as a result all the centers should be reassigned and the model # should not longer be good for this_X in (X, X_csr): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=100, random_state=42) mb_k_means.fit(this_X) score_before = mb_k_means.score(this_X) try: old_stdout = sys.stdout sys.stdout = StringIO() # Turn on verbosity to smoke test the display code _mini_batch_step(this_X, (X ** 2).sum(axis=1), mb_k_means.cluster_centers_, mb_k_means.counts_, np.zeros(X.shape[1], np.double), False, distances=np.zeros(X.shape[0]), random_reassign=True, random_state=42, reassignment_ratio=1, verbose=True) finally: sys.stdout = old_stdout assert_greater(score_before, mb_k_means.score(this_X)) # Give a perfect initialization, with a small reassignment_ratio, # no center should be reassigned for this_X in (X, X_csr): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=100, init=centers.copy(), random_state=42, n_init=1) mb_k_means.fit(this_X) clusters_before = mb_k_means.cluster_centers_ # Turn on verbosity to smoke test the display code _mini_batch_step(this_X, (X ** 2).sum(axis=1), mb_k_means.cluster_centers_, mb_k_means.counts_, np.zeros(X.shape[1], np.double), False, distances=np.zeros(X.shape[0]), random_reassign=True, random_state=42, reassignment_ratio=1e-15) assert_array_almost_equal(clusters_before, mb_k_means.cluster_centers_) def test_minibatch_with_many_reassignments(): # Test for the case that the number of clusters to reassign is bigger # than the batch_size n_samples = 550 rnd = np.random.RandomState(42) X = rnd.uniform(size=(n_samples, 10)) # Check that the fit works if n_clusters is bigger than the batch_size. # Run the test with 550 clusters and 550 samples, because it turned out # that this values ensure that the number of clusters to reassign # is always bigger than the batch_size n_clusters = 550 MiniBatchKMeans(n_clusters=n_clusters, batch_size=100, init_size=n_samples, random_state=42).fit(X) def test_sparse_mb_k_means_callable_init(): def test_init(X, k, random_state): return centers # Small test to check that giving the wrong number of centers # raises a meaningful error msg = "does not match the number of clusters" assert_raises_regex(ValueError, msg, MiniBatchKMeans(init=test_init, random_state=42).fit, X_csr) # Now check that the fit actually works mb_k_means = MiniBatchKMeans(n_clusters=3, init=test_init, random_state=42).fit(X_csr) _check_fitted_model(mb_k_means) def test_mini_batch_k_means_random_init_partial_fit(): km = MiniBatchKMeans(n_clusters=n_clusters, init="random", random_state=42) # use the partial_fit API for online learning for X_minibatch in np.array_split(X, 10): km.partial_fit(X_minibatch) # compute the labeling on the complete dataset labels = km.predict(X) assert_equal(v_measure_score(true_labels, labels), 1.0) def test_minibatch_default_init_size(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, batch_size=10, random_state=42, n_init=1).fit(X) assert_equal(mb_k_means.init_size_, 3 * mb_k_means.batch_size) _check_fitted_model(mb_k_means) def test_minibatch_tol(): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, batch_size=10, random_state=42, tol=.01).fit(X) _check_fitted_model(mb_k_means) def test_minibatch_set_init_size(): mb_k_means = MiniBatchKMeans(init=centers.copy(), n_clusters=n_clusters, init_size=666, random_state=42, n_init=1).fit(X) assert_equal(mb_k_means.init_size, 666) assert_equal(mb_k_means.init_size_, n_samples) _check_fitted_model(mb_k_means) def test_k_means_invalid_init(): km = KMeans(init="invalid", n_init=1, n_clusters=n_clusters) assert_raises(ValueError, km.fit, X) def test_mini_match_k_means_invalid_init(): km = MiniBatchKMeans(init="invalid", n_init=1, n_clusters=n_clusters) assert_raises(ValueError, km.fit, X) def test_k_means_copyx(): # Check if copy_x=False returns nearly equal X after de-centering. my_X = X.copy() km = KMeans(copy_x=False, n_clusters=n_clusters, random_state=42) km.fit(my_X) _check_fitted_model(km) # check if my_X is centered assert_array_almost_equal(my_X, X) def test_k_means_non_collapsed(): # Check k_means with a bad initialization does not yield a singleton # Starting with bad centers that are quickly ignored should not # result in a repositioning of the centers to the center of mass that # would lead to collapsed centers which in turns make the clustering # dependent of the numerical unstabilities. my_X = np.array([[1.1, 1.1], [0.9, 1.1], [1.1, 0.9], [0.9, 1.1]]) array_init = np.array([[1.0, 1.0], [5.0, 5.0], [-5.0, -5.0]]) km = KMeans(init=array_init, n_clusters=3, random_state=42, n_init=1) km.fit(my_X) # centers must not been collapsed assert_equal(len(np.unique(km.labels_)), 3) centers = km.cluster_centers_ assert_true(np.linalg.norm(centers[0] - centers[1]) >= 0.1) assert_true(np.linalg.norm(centers[0] - centers[2]) >= 0.1) assert_true(np.linalg.norm(centers[1] - centers[2]) >= 0.1) def test_predict(): km = KMeans(n_clusters=n_clusters, random_state=42) km.fit(X) # sanity check: predict centroid labels pred = km.predict(km.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # sanity check: re-predict labeling for training set samples pred = km.predict(X) assert_array_equal(pred, km.labels_) # re-predict labels for training set using fit_predict pred = km.fit_predict(X) assert_array_equal(pred, km.labels_) def test_score(): km1 = KMeans(n_clusters=n_clusters, max_iter=1, random_state=42, n_init=1) s1 = km1.fit(X).score(X) km2 = KMeans(n_clusters=n_clusters, max_iter=10, random_state=42, n_init=1) s2 = km2.fit(X).score(X) assert_greater(s2, s1) km1 = KMeans(n_clusters=n_clusters, max_iter=1, random_state=42, n_init=1, algorithm='elkan') s1 = km1.fit(X).score(X) km2 = KMeans(n_clusters=n_clusters, max_iter=10, random_state=42, n_init=1, algorithm='elkan') s2 = km2.fit(X).score(X) assert_greater(s2, s1) def test_predict_minibatch_dense_input(): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, random_state=40).fit(X) # sanity check: predict centroid labels pred = mb_k_means.predict(mb_k_means.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # sanity check: re-predict labeling for training set samples pred = mb_k_means.predict(X) assert_array_equal(mb_k_means.predict(X), mb_k_means.labels_) def test_predict_minibatch_kmeanspp_init_sparse_input(): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, init='k-means++', n_init=10).fit(X_csr) # sanity check: re-predict labeling for training set samples assert_array_equal(mb_k_means.predict(X_csr), mb_k_means.labels_) # sanity check: predict centroid labels pred = mb_k_means.predict(mb_k_means.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # check that models trained on sparse input also works for dense input at # predict time assert_array_equal(mb_k_means.predict(X), mb_k_means.labels_) def test_predict_minibatch_random_init_sparse_input(): mb_k_means = MiniBatchKMeans(n_clusters=n_clusters, init='random', n_init=10).fit(X_csr) # sanity check: re-predict labeling for training set samples assert_array_equal(mb_k_means.predict(X_csr), mb_k_means.labels_) # sanity check: predict centroid labels pred = mb_k_means.predict(mb_k_means.cluster_centers_) assert_array_equal(pred, np.arange(n_clusters)) # check that models trained on sparse input also works for dense input at # predict time assert_array_equal(mb_k_means.predict(X), mb_k_means.labels_) def test_input_dtypes(): X_list = [[0, 0], [10, 10], [12, 9], [-1, 1], [2, 0], [8, 10]] X_int = np.array(X_list, dtype=np.int32) X_int_csr = sp.csr_matrix(X_int) init_int = X_int[:2] fitted_models = [ KMeans(n_clusters=2).fit(X_list), KMeans(n_clusters=2).fit(X_int), KMeans(n_clusters=2, init=init_int, n_init=1).fit(X_list), KMeans(n_clusters=2, init=init_int, n_init=1).fit(X_int), # mini batch kmeans is very unstable on such a small dataset hence # we use many inits MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_list), MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_int), MiniBatchKMeans(n_clusters=2, n_init=10, batch_size=2).fit(X_int_csr), MiniBatchKMeans(n_clusters=2, batch_size=2, init=init_int, n_init=1).fit(X_list), MiniBatchKMeans(n_clusters=2, batch_size=2, init=init_int, n_init=1).fit(X_int), MiniBatchKMeans(n_clusters=2, batch_size=2, init=init_int, n_init=1).fit(X_int_csr), ] expected_labels = [0, 1, 1, 0, 0, 1] scores = np.array([v_measure_score(expected_labels, km.labels_) for km in fitted_models]) assert_array_equal(scores, np.ones(scores.shape[0])) def test_transform(): km = KMeans(n_clusters=n_clusters) km.fit(X) X_new = km.transform(km.cluster_centers_) for c in range(n_clusters): assert_equal(X_new[c, c], 0) for c2 in range(n_clusters): if c != c2: assert_greater(X_new[c, c2], 0) def test_fit_transform(): X1 = KMeans(n_clusters=3, random_state=51).fit(X).transform(X) X2 = KMeans(n_clusters=3, random_state=51).fit_transform(X) assert_array_equal(X1, X2) def test_predict_equal_labels(): km = KMeans(random_state=13, n_jobs=1, n_init=1, max_iter=1, algorithm='full') km.fit(X) assert_array_equal(km.predict(X), km.labels_) km = KMeans(random_state=13, n_jobs=1, n_init=1, max_iter=1, algorithm='elkan') km.fit(X) assert_array_equal(km.predict(X), km.labels_) def test_full_vs_elkan(): km1 = KMeans(algorithm='full', random_state=13) km2 = KMeans(algorithm='elkan', random_state=13) km1.fit(X) km2.fit(X) homogeneity_score(km1.predict(X), km2.predict(X)) == 1.0 def test_n_init(): # Check that increasing the number of init increases the quality n_runs = 5 n_init_range = [1, 5, 10] inertia = np.zeros((len(n_init_range), n_runs)) for i, n_init in enumerate(n_init_range): for j in range(n_runs): km = KMeans(n_clusters=n_clusters, init="random", n_init=n_init, random_state=j).fit(X) inertia[i, j] = km.inertia_ inertia = inertia.mean(axis=1) failure_msg = ("Inertia %r should be decreasing" " when n_init is increasing.") % list(inertia) for i in range(len(n_init_range) - 1): assert_true(inertia[i] >= inertia[i + 1], failure_msg) def test_k_means_function(): # test calling the k_means function directly # catch output old_stdout = sys.stdout sys.stdout = StringIO() try: cluster_centers, labels, inertia = k_means(X, n_clusters=n_clusters, verbose=True) finally: sys.stdout = old_stdout centers = cluster_centers assert_equal(centers.shape, (n_clusters, n_features)) labels = labels assert_equal(np.unique(labels).shape[0], n_clusters) # check that the labels assignment are perfect (up to a permutation) assert_equal(v_measure_score(true_labels, labels), 1.0) assert_greater(inertia, 0.0) # check warning when centers are passed assert_warns(RuntimeWarning, k_means, X, n_clusters=n_clusters, init=centers) # to many clusters desired assert_raises(ValueError, k_means, X, n_clusters=X.shape[0] + 1) def test_x_squared_norms_init_centroids(): """Test that x_squared_norms can be None in _init_centroids""" from sklearn.cluster.k_means_ import _init_centroids X_norms = np.sum(X**2, axis=1) precompute = _init_centroids( X, 3, "k-means++", random_state=0, x_squared_norms=X_norms) assert_array_equal( precompute, _init_centroids(X, 3, "k-means++", random_state=0)) def test_max_iter_error(): km = KMeans(max_iter=-1) assert_raise_message(ValueError, 'Number of iterations should be', km.fit, X)
bsd-3-clause
vortex-ape/scikit-learn
benchmarks/bench_covertype.py
4
7382
""" =========================== Covertype dataset benchmark =========================== Benchmark stochastic gradient descent (SGD), Liblinear, and Naive Bayes, CART (decision tree), RandomForest and Extra-Trees on the forest covertype dataset of Blackard, Jock, and Dean [1]. The dataset comprises 581,012 samples. It is low dimensional with 54 features and a sparsity of approx. 23%. Here, we consider the task of predicting class 1 (spruce/fir). The classification performance of SGD is competitive with Liblinear while being two orders of magnitude faster to train:: [..] Classification performance: =========================== Classifier train-time test-time error-rate -------------------------------------------- liblinear 15.9744s 0.0705s 0.2305 GaussianNB 3.0666s 0.3884s 0.4841 SGD 1.0558s 0.1152s 0.2300 CART 79.4296s 0.0523s 0.0469 RandomForest 1190.1620s 0.5881s 0.0243 ExtraTrees 640.3194s 0.6495s 0.0198 The same task has been used in a number of papers including: * `"SVM Optimization: Inverse Dependence on Training Set Size" <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.139.2112>`_ S. Shalev-Shwartz, N. Srebro - In Proceedings of ICML '08. * `"Pegasos: Primal estimated sub-gradient solver for svm" <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.74.8513>`_ S. Shalev-Shwartz, Y. Singer, N. Srebro - In Proceedings of ICML '07. * `"Training Linear SVMs in Linear Time" <www.cs.cornell.edu/People/tj/publications/joachims_06a.pdf>`_ T. Joachims - In SIGKDD '06 [1] http://archive.ics.uci.edu/ml/datasets/Covertype """ from __future__ import division, print_function # Author: Peter Prettenhofer <[email protected]> # Arnaud Joly <[email protected]> # License: BSD 3 clause import os from time import time import argparse import numpy as np from sklearn.datasets import fetch_covtype, get_data_home from sklearn.svm import LinearSVC from sklearn.linear_model import SGDClassifier, LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import zero_one_loss from sklearn.utils import Memory from sklearn.utils import check_array # Memoize the data extraction and memory map the resulting # train / test splits in readonly mode memory = Memory(os.path.join(get_data_home(), 'covertype_benchmark_data'), mmap_mode='r') @memory.cache def load_data(dtype=np.float32, order='C', random_state=13): """Load the data, then cache and memmap the train/test split""" ###################################################################### # Load dataset print("Loading dataset...") data = fetch_covtype(download_if_missing=True, shuffle=True, random_state=random_state) X = check_array(data['data'], dtype=dtype, order=order) y = (data['target'] != 1).astype(np.int) # Create train-test split (as [Joachims, 2006]) print("Creating train-test split...") n_train = 522911 X_train = X[:n_train] y_train = y[:n_train] X_test = X[n_train:] y_test = y[n_train:] # Standardize first 10 features (the numerical ones) mean = X_train.mean(axis=0) std = X_train.std(axis=0) mean[10:] = 0.0 std[10:] = 1.0 X_train = (X_train - mean) / std X_test = (X_test - mean) / std return X_train, X_test, y_train, y_test ESTIMATORS = { 'GBRT': GradientBoostingClassifier(n_estimators=250), 'ExtraTrees': ExtraTreesClassifier(n_estimators=20), 'RandomForest': RandomForestClassifier(n_estimators=20), 'CART': DecisionTreeClassifier(min_samples_split=5), 'SGD': SGDClassifier(alpha=0.001, max_iter=1000, tol=1e-3), 'GaussianNB': GaussianNB(), 'liblinear': LinearSVC(loss="l2", penalty="l2", C=1000, dual=False, tol=1e-3), 'SAG': LogisticRegression(solver='sag', max_iter=2, C=1000) } if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--classifiers', nargs="+", choices=ESTIMATORS, type=str, default=['liblinear', 'GaussianNB', 'SGD', 'CART'], help="list of classifiers to benchmark.") parser.add_argument('--n-jobs', nargs="?", default=1, type=int, help="Number of concurrently running workers for " "models that support parallelism.") parser.add_argument('--order', nargs="?", default="C", type=str, choices=["F", "C"], help="Allow to choose between fortran and C ordered " "data") parser.add_argument('--random-seed', nargs="?", default=13, type=int, help="Common seed used by random number generator.") args = vars(parser.parse_args()) print(__doc__) X_train, X_test, y_train, y_test = load_data( order=args["order"], random_state=args["random_seed"]) print("") print("Dataset statistics:") print("===================") print("%s %d" % ("number of features:".ljust(25), X_train.shape[1])) print("%s %d" % ("number of classes:".ljust(25), np.unique(y_train).size)) print("%s %s" % ("data type:".ljust(25), X_train.dtype)) print("%s %d (pos=%d, neg=%d, size=%dMB)" % ("number of train samples:".ljust(25), X_train.shape[0], np.sum(y_train == 1), np.sum(y_train == 0), int(X_train.nbytes / 1e6))) print("%s %d (pos=%d, neg=%d, size=%dMB)" % ("number of test samples:".ljust(25), X_test.shape[0], np.sum(y_test == 1), np.sum(y_test == 0), int(X_test.nbytes / 1e6))) print() print("Training Classifiers") print("====================") error, train_time, test_time = {}, {}, {} for name in sorted(args["classifiers"]): print("Training %s ... " % name, end="") estimator = ESTIMATORS[name] estimator_params = estimator.get_params() estimator.set_params(**{p: args["random_seed"] for p in estimator_params if p.endswith("random_state")}) if "n_jobs" in estimator_params: estimator.set_params(n_jobs=args["n_jobs"]) time_start = time() estimator.fit(X_train, y_train) train_time[name] = time() - time_start time_start = time() y_pred = estimator.predict(X_test) test_time[name] = time() - time_start error[name] = zero_one_loss(y_test, y_pred) print("done") print() print("Classification performance:") print("===========================") print("%s %s %s %s" % ("Classifier ", "train-time", "test-time", "error-rate")) print("-" * 44) for name in sorted(args["classifiers"], key=error.get): print("%s %s %s %s" % (name.ljust(12), ("%.4fs" % train_time[name]).center(10), ("%.4fs" % test_time[name]).center(10), ("%.4f" % error[name]).center(10))) print()
bsd-3-clause
mattgiguere/scikit-learn
sklearn/linear_model/tests/test_passive_aggressive.py
121
6117
import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_less from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_array_almost_equal, assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.base import ClassifierMixin from sklearn.utils import check_random_state from sklearn.datasets import load_iris from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.linear_model import PassiveAggressiveRegressor iris = load_iris() random_state = check_random_state(12) indices = np.arange(iris.data.shape[0]) random_state.shuffle(indices) X = iris.data[indices] y = iris.target[indices] X_csr = sp.csr_matrix(X) class MyPassiveAggressive(ClassifierMixin): def __init__(self, C=1.0, epsilon=0.01, loss="hinge", fit_intercept=True, n_iter=1, random_state=None): self.C = C self.epsilon = epsilon self.loss = loss self.fit_intercept = fit_intercept self.n_iter = n_iter def fit(self, X, y): n_samples, n_features = X.shape self.w = np.zeros(n_features, dtype=np.float64) self.b = 0.0 for t in range(self.n_iter): for i in range(n_samples): p = self.project(X[i]) if self.loss in ("hinge", "squared_hinge"): loss = max(1 - y[i] * p, 0) else: loss = max(np.abs(p - y[i]) - self.epsilon, 0) sqnorm = np.dot(X[i], X[i]) if self.loss in ("hinge", "epsilon_insensitive"): step = min(self.C, loss / sqnorm) elif self.loss in ("squared_hinge", "squared_epsilon_insensitive"): step = loss / (sqnorm + 1.0 / (2 * self.C)) if self.loss in ("hinge", "squared_hinge"): step *= y[i] else: step *= np.sign(y[i] - p) self.w += step * X[i] if self.fit_intercept: self.b += step def project(self, X): return np.dot(X, self.w) + self.b def test_classifier_accuracy(): for data in (X, X_csr): for fit_intercept in (True, False): clf = PassiveAggressiveClassifier(C=1.0, n_iter=30, fit_intercept=fit_intercept, random_state=0) clf.fit(data, y) score = clf.score(data, y) assert_greater(score, 0.79) def test_classifier_partial_fit(): classes = np.unique(y) for data in (X, X_csr): clf = PassiveAggressiveClassifier(C=1.0, fit_intercept=True, random_state=0) for t in range(30): clf.partial_fit(data, y, classes) score = clf.score(data, y) assert_greater(score, 0.79) def test_classifier_refit(): # Classifier can be retrained on different labels and features. clf = PassiveAggressiveClassifier().fit(X, y) assert_array_equal(clf.classes_, np.unique(y)) clf.fit(X[:, :-1], iris.target_names[y]) assert_array_equal(clf.classes_, iris.target_names) def test_classifier_correctness(): y_bin = y.copy() y_bin[y != 1] = -1 for loss in ("hinge", "squared_hinge"): clf1 = MyPassiveAggressive(C=1.0, loss=loss, fit_intercept=True, n_iter=2) clf1.fit(X, y_bin) for data in (X, X_csr): clf2 = PassiveAggressiveClassifier(C=1.0, loss=loss, fit_intercept=True, n_iter=2, shuffle=False) clf2.fit(data, y_bin) assert_array_almost_equal(clf1.w, clf2.coef_.ravel(), decimal=2) def test_classifier_undefined_methods(): clf = PassiveAggressiveClassifier() for meth in ("predict_proba", "predict_log_proba", "transform"): assert_raises(AttributeError, lambda x: getattr(clf, x), meth) def test_regressor_mse(): y_bin = y.copy() y_bin[y != 1] = -1 for data in (X, X_csr): for fit_intercept in (True, False): reg = PassiveAggressiveRegressor(C=1.0, n_iter=50, fit_intercept=fit_intercept, random_state=0) reg.fit(data, y_bin) pred = reg.predict(data) assert_less(np.mean((pred - y_bin) ** 2), 1.7) def test_regressor_partial_fit(): y_bin = y.copy() y_bin[y != 1] = -1 for data in (X, X_csr): reg = PassiveAggressiveRegressor(C=1.0, fit_intercept=True, random_state=0) for t in range(50): reg.partial_fit(data, y_bin) pred = reg.predict(data) assert_less(np.mean((pred - y_bin) ** 2), 1.7) def test_regressor_correctness(): y_bin = y.copy() y_bin[y != 1] = -1 for loss in ("epsilon_insensitive", "squared_epsilon_insensitive"): reg1 = MyPassiveAggressive(C=1.0, loss=loss, fit_intercept=True, n_iter=2) reg1.fit(X, y_bin) for data in (X, X_csr): reg2 = PassiveAggressiveRegressor(C=1.0, loss=loss, fit_intercept=True, n_iter=2, shuffle=False) reg2.fit(data, y_bin) assert_array_almost_equal(reg1.w, reg2.coef_.ravel(), decimal=2) def test_regressor_undefined_methods(): reg = PassiveAggressiveRegressor() for meth in ("transform",): assert_raises(AttributeError, lambda x: getattr(reg, x), meth)
bsd-3-clause
qifeigit/scikit-learn
sklearn/tests/test_isotonic.py
230
11087
import numpy as np import pickle from sklearn.isotonic import (check_increasing, isotonic_regression, IsotonicRegression) from sklearn.utils.testing import (assert_raises, assert_array_equal, assert_true, assert_false, assert_equal, assert_array_almost_equal, assert_warns_message, assert_no_warnings) from sklearn.utils import shuffle def test_permutation_invariance(): # check that fit is permuation invariant. # regression test of missing sorting of sample-weights ir = IsotonicRegression() x = [1, 2, 3, 4, 5, 6, 7] y = [1, 41, 51, 1, 2, 5, 24] sample_weight = [1, 2, 3, 4, 5, 6, 7] x_s, y_s, sample_weight_s = shuffle(x, y, sample_weight, random_state=0) y_transformed = ir.fit_transform(x, y, sample_weight=sample_weight) y_transformed_s = ir.fit(x_s, y_s, sample_weight=sample_weight_s).transform(x) assert_array_equal(y_transformed, y_transformed_s) def test_check_increasing_up(): x = [0, 1, 2, 3, 4, 5] y = [0, 1.5, 2.77, 8.99, 8.99, 50] # Check that we got increasing=True and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_true(is_increasing) def test_check_increasing_up_extreme(): x = [0, 1, 2, 3, 4, 5] y = [0, 1, 2, 3, 4, 5] # Check that we got increasing=True and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_true(is_increasing) def test_check_increasing_down(): x = [0, 1, 2, 3, 4, 5] y = [0, -1.5, -2.77, -8.99, -8.99, -50] # Check that we got increasing=False and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_false(is_increasing) def test_check_increasing_down_extreme(): x = [0, 1, 2, 3, 4, 5] y = [0, -1, -2, -3, -4, -5] # Check that we got increasing=False and no warnings is_increasing = assert_no_warnings(check_increasing, x, y) assert_false(is_increasing) def test_check_ci_warn(): x = [0, 1, 2, 3, 4, 5] y = [0, -1, 2, -3, 4, -5] # Check that we got increasing=False and CI interval warning is_increasing = assert_warns_message(UserWarning, "interval", check_increasing, x, y) assert_false(is_increasing) def test_isotonic_regression(): y = np.array([3, 7, 5, 9, 8, 7, 10]) y_ = np.array([3, 6, 6, 8, 8, 8, 10]) assert_array_equal(y_, isotonic_regression(y)) x = np.arange(len(y)) ir = IsotonicRegression(y_min=0., y_max=1.) ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(ir.transform(x), ir.predict(x)) # check that it is immune to permutation perm = np.random.permutation(len(y)) ir = IsotonicRegression(y_min=0., y_max=1.) assert_array_equal(ir.fit_transform(x[perm], y[perm]), ir.fit_transform(x, y)[perm]) assert_array_equal(ir.transform(x[perm]), ir.transform(x)[perm]) # check we don't crash when all x are equal: ir = IsotonicRegression() assert_array_equal(ir.fit_transform(np.ones(len(x)), y), np.mean(y)) def test_isotonic_regression_ties_min(): # Setup examples with ties on minimum x = [0, 1, 1, 2, 3, 4, 5] y = [0, 1, 2, 3, 4, 5, 6] y_true = [0, 1.5, 1.5, 3, 4, 5, 6] # Check that we get identical results for fit/transform and fit_transform ir = IsotonicRegression() ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(y_true, ir.fit_transform(x, y)) def test_isotonic_regression_ties_max(): # Setup examples with ties on maximum x = [1, 2, 3, 4, 5, 5] y = [1, 2, 3, 4, 5, 6] y_true = [1, 2, 3, 4, 5.5, 5.5] # Check that we get identical results for fit/transform and fit_transform ir = IsotonicRegression() ir.fit(x, y) assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y)) assert_array_equal(y_true, ir.fit_transform(x, y)) def test_isotonic_regression_ties_secondary_(): """ Test isotonic regression fit, transform and fit_transform against the "secondary" ties method and "pituitary" data from R "isotone" package, as detailed in: J. d. Leeuw, K. Hornik, P. Mair, Isotone Optimization in R: Pool-Adjacent-Violators Algorithm (PAVA) and Active Set Methods Set values based on pituitary example and the following R command detailed in the paper above: > library("isotone") > data("pituitary") > res1 <- gpava(pituitary$age, pituitary$size, ties="secondary") > res1$x `isotone` version: 1.0-2, 2014-09-07 R version: R version 3.1.1 (2014-07-10) """ x = [8, 8, 8, 10, 10, 10, 12, 12, 12, 14, 14] y = [21, 23.5, 23, 24, 21, 25, 21.5, 22, 19, 23.5, 25] y_true = [22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 22.22222, 24.25, 24.25] # Check fit, transform and fit_transform ir = IsotonicRegression() ir.fit(x, y) assert_array_almost_equal(ir.transform(x), y_true, 4) assert_array_almost_equal(ir.fit_transform(x, y), y_true, 4) def test_isotonic_regression_reversed(): y = np.array([10, 9, 10, 7, 6, 6.1, 5]) y_ = IsotonicRegression(increasing=False).fit_transform( np.arange(len(y)), y) assert_array_equal(np.ones(y_[:-1].shape), ((y_[:-1] - y_[1:]) >= 0)) def test_isotonic_regression_auto_decreasing(): # Set y and x for decreasing y = np.array([10, 9, 10, 7, 6, 6.1, 5]) x = np.arange(len(y)) # Create model and fit_transform ir = IsotonicRegression(increasing='auto') y_ = assert_no_warnings(ir.fit_transform, x, y) # Check that relationship decreases is_increasing = y_[0] < y_[-1] assert_false(is_increasing) def test_isotonic_regression_auto_increasing(): # Set y and x for decreasing y = np.array([5, 6.1, 6, 7, 10, 9, 10]) x = np.arange(len(y)) # Create model and fit_transform ir = IsotonicRegression(increasing='auto') y_ = assert_no_warnings(ir.fit_transform, x, y) # Check that relationship increases is_increasing = y_[0] < y_[-1] assert_true(is_increasing) def test_assert_raises_exceptions(): ir = IsotonicRegression() rng = np.random.RandomState(42) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6]) assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7]) assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2]) assert_raises(ValueError, ir.transform, rng.randn(3, 10)) def test_isotonic_sample_weight_parameter_default_value(): # check if default value of sample_weight parameter is one ir = IsotonicRegression() # random test data rng = np.random.RandomState(42) n = 100 x = np.arange(n) y = rng.randint(-50, 50, size=(n,)) + 50. * np.log(1 + np.arange(n)) # check if value is correctly used weights = np.ones(n) y_set_value = ir.fit_transform(x, y, sample_weight=weights) y_default_value = ir.fit_transform(x, y) assert_array_equal(y_set_value, y_default_value) def test_isotonic_min_max_boundaries(): # check if min value is used correctly ir = IsotonicRegression(y_min=2, y_max=4) n = 6 x = np.arange(n) y = np.arange(n) y_test = [2, 2, 2, 3, 4, 4] y_result = np.round(ir.fit_transform(x, y)) assert_array_equal(y_result, y_test) def test_isotonic_sample_weight(): ir = IsotonicRegression() x = [1, 2, 3, 4, 5, 6, 7] y = [1, 41, 51, 1, 2, 5, 24] sample_weight = [1, 2, 3, 4, 5, 6, 7] expected_y = [1, 13.95, 13.95, 13.95, 13.95, 13.95, 24] received_y = ir.fit_transform(x, y, sample_weight=sample_weight) assert_array_equal(expected_y, received_y) def test_isotonic_regression_oob_raise(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") ir.fit(x, y) # Check that an exception is thrown assert_raises(ValueError, ir.predict, [min(x) - 10, max(x) + 10]) def test_isotonic_regression_oob_clip(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") ir.fit(x, y) # Predict from training and test x and check that min/max match. y1 = ir.predict([min(x) - 10, max(x) + 10]) y2 = ir.predict(x) assert_equal(max(y1), max(y2)) assert_equal(min(y1), min(y2)) def test_isotonic_regression_oob_nan(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="nan") ir.fit(x, y) # Predict from training and test x and check that we have two NaNs. y1 = ir.predict([min(x) - 10, max(x) + 10]) assert_equal(sum(np.isnan(y1)), 2) def test_isotonic_regression_oob_bad(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="xyz") # Make sure that we throw an error for bad out_of_bounds value assert_raises(ValueError, ir.fit, x, y) def test_isotonic_regression_oob_bad_after(): # Set y and x y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="raise") # Make sure that we throw an error for bad out_of_bounds value in transform ir.fit(x, y) ir.out_of_bounds = "xyz" assert_raises(ValueError, ir.transform, x) def test_isotonic_regression_pickle(): y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) # Create model and fit ir = IsotonicRegression(increasing='auto', out_of_bounds="clip") ir.fit(x, y) ir_ser = pickle.dumps(ir, pickle.HIGHEST_PROTOCOL) ir2 = pickle.loads(ir_ser) np.testing.assert_array_equal(ir.predict(x), ir2.predict(x)) def test_isotonic_duplicate_min_entry(): x = [0, 0, 1] y = [0, 0, 1] ir = IsotonicRegression(increasing=True, out_of_bounds="clip") ir.fit(x, y) all_predictions_finite = np.all(np.isfinite(ir.predict(x))) assert_true(all_predictions_finite) def test_isotonic_zero_weight_loop(): # Test from @ogrisel's issue: # https://github.com/scikit-learn/scikit-learn/issues/4297 # Get deterministic RNG with seed rng = np.random.RandomState(42) # Create regression and samples regression = IsotonicRegression() n_samples = 50 x = np.linspace(-3, 3, n_samples) y = x + rng.uniform(size=n_samples) # Get some random weights and zero out w = rng.uniform(size=n_samples) w[5:8] = 0 regression.fit(x, y, sample_weight=w) # This will hang in failure case. regression.fit(x, y, sample_weight=w)
bsd-3-clause
handroissuazo/tensorflow
tensorflow/contrib/learn/python/learn/estimators/__init__.py
12
11510
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """An estimator is a rule for calculating an estimate of a given quantity. # Estimators * **Estimators** are used to train and evaluate TensorFlow models. They support regression and classification problems. * **Classifiers** are functions that have discrete outcomes. * **Regressors** are functions that predict continuous values. ## Choosing the correct estimator * For **Regression** problems use one of the following: * `LinearRegressor`: Uses linear model. * `DNNRegressor`: Uses DNN. * `DNNLinearCombinedRegressor`: Uses Wide & Deep. * `TensorForestEstimator`: Uses RandomForest. Use `.predict()` for regression problems. * `Estimator`: Use when you need a custom model. * For **Classification** problems use one of the following: * `LinearClassifier`: Multiclass classifier using Linear model. * `DNNClassifier`: Multiclass classifier using DNN. * `DNNLinearCombinedClassifier`: Multiclass classifier using Wide & Deep. * `TensorForestEstimator`: Uses RandomForest. Use `.predict_proba()` when using for binary classification problems. * `SVM`: Binary classifier using linear SVMs. * `LogisticRegressor`: Use when you need custom model for binary classification. * `Estimator`: Use when you need custom model for N class classification. ## Pre-canned Estimators Pre-canned estimators are machine learning estimators premade for general purpose problems. If you need more customization, you can always write your own custom estimator as described in the section below. Pre-canned estimators are tested and optimized for speed and quality. ### Define the feature columns Here are some possible types of feature columns used as inputs to a pre-canned estimator. Feature columns may vary based on the estimator used. So you can see which feature columns are fed to each estimator in the below section. ```python sparse_feature_a = sparse_column_with_keys( column_name="sparse_feature_a", keys=["AB", "CD", ...]) embedding_feature_a = embedding_column( sparse_id_column=sparse_feature_a, dimension=3, combiner="sum") sparse_feature_b = sparse_column_with_hash_bucket( column_name="sparse_feature_b", hash_bucket_size=1000) embedding_feature_b = embedding_column( sparse_id_column=sparse_feature_b, dimension=16, combiner="sum") crossed_feature_a_x_b = crossed_column( columns=[sparse_feature_a, sparse_feature_b], hash_bucket_size=10000) real_feature = real_valued_column("real_feature") real_feature_buckets = bucketized_column( source_column=real_feature, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]) ``` ### Create the pre-canned estimator DNNClassifier, DNNRegressor, and DNNLinearCombinedClassifier are all pretty similar to each other in how you use them. You can easily plug in an optimizer and/or regularization to those estimators. #### DNNClassifier A classifier for TensorFlow DNN models. ```python my_features = [embedding_feature_a, embedding_feature_b] estimator = DNNClassifier( feature_columns=my_features, hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### DNNRegressor A regressor for TensorFlow DNN models. ```python my_features = [embedding_feature_a, embedding_feature_b] estimator = DNNRegressor( feature_columns=my_features, hidden_units=[1024, 512, 256]) # Or estimator using the ProximalAdagradOptimizer optimizer with # regularization. estimator = DNNRegressor( feature_columns=my_features, hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### DNNLinearCombinedClassifier A classifier for TensorFlow Linear and DNN joined training models. * Wide and deep model * Multi class (2 by default) ```python my_linear_features = [crossed_feature_a_x_b] my_deep_features = [embedding_feature_a, embedding_feature_b] estimator = DNNLinearCombinedClassifier( # Common settings n_classes=n_classes, weight_column_name=weight_column_name, # Wide settings linear_feature_columns=my_linear_features, linear_optimizer=tf.train.FtrlOptimizer(...), # Deep settings dnn_feature_columns=my_deep_features, dnn_hidden_units=[1000, 500, 100], dnn_optimizer=tf.train.AdagradOptimizer(...)) ``` #### LinearClassifier Train a linear model to classify instances into one of multiple possible classes. When number of possible classes is 2, this is binary classification. ```python my_features = [sparse_feature_b, crossed_feature_a_x_b] estimator = LinearClassifier( feature_columns=my_features, optimizer=tf.train.FtrlOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### LinearRegressor Train a linear regression model to predict a label value given observation of feature values. ```python my_features = [sparse_feature_b, crossed_feature_a_x_b] estimator = LinearRegressor( feature_columns=my_features) ``` ### LogisticRegressor Logistic regression estimator for binary classification. ```python # See tf.contrib.learn.Estimator(...) for details on model_fn structure def my_model_fn(...): pass estimator = LogisticRegressor(model_fn=my_model_fn) # Input builders def input_fn_train: pass estimator.fit(input_fn=input_fn_train) estimator.predict(x=x) ``` #### SVM - Support Vector Machine Support Vector Machine (SVM) model for binary classification. Currently only linear SVMs are supported. ```python my_features = [real_feature, sparse_feature_a] estimator = SVM( example_id_column='example_id', feature_columns=my_features, l2_regularization=10.0) ``` #### TensorForestEstimator Supports regression and binary classification. ```python params = tf.contrib.tensor_forest.python.tensor_forest.ForestHParams( num_classes=2, num_features=40, num_trees=10, max_nodes=1000) # Estimator using the default graph builder. estimator = TensorForestEstimator(params, model_dir=model_dir) # Or estimator using TrainingLossForest as the graph builder. estimator = TensorForestEstimator( params, graph_builder_class=tensor_forest.TrainingLossForest, model_dir=model_dir) # Input builders def input_fn_train: # returns x, y ... def input_fn_eval: # returns x, y ... estimator.fit(input_fn=input_fn_train) estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) ``` ### Use the estimator There are two main functions for using estimators, one of which is for training, and one of which is for evaluation. You can specify different data sources for each one in order to use different datasets for train and eval. ```python # Input builders def input_fn_train: # returns x, Y ... estimator.fit(input_fn=input_fn_train) def input_fn_eval: # returns x, Y ... estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) ``` ## Creating Custom Estimator To create a custom `Estimator`, provide a function to `Estimator`'s constructor that builds your model (`model_fn`, below): ```python estimator = tf.contrib.learn.Estimator( model_fn=model_fn, model_dir=model_dir) # Where the model's data (e.g., checkpoints) # are saved. ``` Here is a skeleton of this function, with descriptions of its arguments and return values in the accompanying tables: ```python def model_fn(features, targets, mode, params): # Logic to do the following: # 1. Configure the model via TensorFlow operations # 2. Define the loss function for training/evaluation # 3. Define the training operation/optimizer # 4. Generate predictions return predictions, loss, train_op ``` You may use `mode` and check against `tf.contrib.learn.ModeKeys.{TRAIN, EVAL, INFER}` to parameterize `model_fn`. In the Further Reading section below, there is an end-to-end TensorFlow tutorial for building a custom estimator. ## Additional Estimators There is an additional estimators under `tensorflow.contrib.factorization.python.ops`: * Gaussian mixture model (GMM) clustering ## Further reading For further reading, there are several tutorials with relevant topics, including: * [Overview of linear models](../../../tutorials/linear/overview.md) * [Linear model tutorial](../../../tutorials/wide/index.md) * [Wide and deep learning tutorial](../../../tutorials/wide_and_deep/index.md) * [Custom estimator tutorial](../../../tutorials/estimators/index.md) * [Building input functions](../../../tutorials/input_fn/index.md) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators._sklearn import NotFittedError from tensorflow.contrib.learn.python.learn.estimators.constants import ProblemType from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNClassifier from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNRegressor from tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined import DNNLinearCombinedClassifier from tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined import DNNLinearCombinedRegressor from tensorflow.contrib.learn.python.learn.estimators.estimator import BaseEstimator from tensorflow.contrib.learn.python.learn.estimators.estimator import Estimator from tensorflow.contrib.learn.python.learn.estimators.estimator import infer_real_valued_columns_from_input from tensorflow.contrib.learn.python.learn.estimators.estimator import infer_real_valued_columns_from_input_fn from tensorflow.contrib.learn.python.learn.estimators.estimator import SKCompat from tensorflow.contrib.learn.python.learn.estimators.kmeans import KMeansClustering from tensorflow.contrib.learn.python.learn.estimators.linear import LinearClassifier from tensorflow.contrib.learn.python.learn.estimators.linear import LinearRegressor from tensorflow.contrib.learn.python.learn.estimators.logistic_regressor import LogisticRegressor from tensorflow.contrib.learn.python.learn.estimators.metric_key import MetricKey from tensorflow.contrib.learn.python.learn.estimators.model_fn import ModeKeys from tensorflow.contrib.learn.python.learn.estimators.model_fn import ModelFnOps from tensorflow.contrib.learn.python.learn.estimators.prediction_key import PredictionKey from tensorflow.contrib.learn.python.learn.estimators.run_config import ClusterConfig from tensorflow.contrib.learn.python.learn.estimators.run_config import Environment from tensorflow.contrib.learn.python.learn.estimators.run_config import RunConfig from tensorflow.contrib.learn.python.learn.estimators.run_config import TaskType from tensorflow.contrib.learn.python.learn.estimators.svm import SVM
apache-2.0
h2educ/scikit-learn
sklearn/tests/test_learning_curve.py
225
10791
# Author: Alexander Fabisch <[email protected]> # # License: BSD 3 clause import sys from sklearn.externals.six.moves import cStringIO as StringIO import numpy as np import warnings from sklearn.base import BaseEstimator from sklearn.learning_curve import learning_curve, validation_curve from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_warns from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.datasets import make_classification from sklearn.cross_validation import KFold from sklearn.linear_model import PassiveAggressiveClassifier class MockImprovingEstimator(BaseEstimator): """Dummy classifier to test the learning curve""" def __init__(self, n_max_train_sizes): self.n_max_train_sizes = n_max_train_sizes self.train_sizes = 0 self.X_subset = None def fit(self, X_subset, y_subset=None): self.X_subset = X_subset self.train_sizes = X_subset.shape[0] return self def predict(self, X): raise NotImplementedError def score(self, X=None, Y=None): # training score becomes worse (2 -> 1), test error better (0 -> 1) if self._is_training_data(X): return 2. - float(self.train_sizes) / self.n_max_train_sizes else: return float(self.train_sizes) / self.n_max_train_sizes def _is_training_data(self, X): return X is self.X_subset class MockIncrementalImprovingEstimator(MockImprovingEstimator): """Dummy classifier that provides partial_fit""" def __init__(self, n_max_train_sizes): super(MockIncrementalImprovingEstimator, self).__init__(n_max_train_sizes) self.x = None def _is_training_data(self, X): return self.x in X def partial_fit(self, X, y=None, **params): self.train_sizes += X.shape[0] self.x = X[0] class MockEstimatorWithParameter(BaseEstimator): """Dummy classifier to test the validation curve""" def __init__(self, param=0.5): self.X_subset = None self.param = param def fit(self, X_subset, y_subset): self.X_subset = X_subset self.train_sizes = X_subset.shape[0] return self def predict(self, X): raise NotImplementedError def score(self, X=None, y=None): return self.param if self._is_training_data(X) else 1 - self.param def _is_training_data(self, X): return X is self.X_subset def test_learning_curve(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) with warnings.catch_warnings(record=True) as w: train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=3, train_sizes=np.linspace(0.1, 1.0, 10)) if len(w) > 0: raise RuntimeError("Unexpected warning: %r" % w[0].message) assert_equal(train_scores.shape, (10, 3)) assert_equal(test_scores.shape, (10, 3)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_learning_curve_unsupervised(): X, _ = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y=None, cv=3, train_sizes=np.linspace(0.1, 1.0, 10)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_learning_curve_verbose(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) old_stdout = sys.stdout sys.stdout = StringIO() try: train_sizes, train_scores, test_scores = \ learning_curve(estimator, X, y, cv=3, verbose=1) finally: out = sys.stdout.getvalue() sys.stdout.close() sys.stdout = old_stdout assert("[learning_curve]" in out) def test_learning_curve_incremental_learning_not_possible(): X, y = make_classification(n_samples=2, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) # The mockup does not have partial_fit() estimator = MockImprovingEstimator(1) assert_raises(ValueError, learning_curve, estimator, X, y, exploit_incremental_learning=True) def test_learning_curve_incremental_learning(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockIncrementalImprovingEstimator(20) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=3, exploit_incremental_learning=True, train_sizes=np.linspace(0.1, 1.0, 10)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_learning_curve_incremental_learning_unsupervised(): X, _ = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockIncrementalImprovingEstimator(20) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y=None, cv=3, exploit_incremental_learning=True, train_sizes=np.linspace(0.1, 1.0, 10)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_learning_curve_batch_and_incremental_learning_are_equal(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) train_sizes = np.linspace(0.2, 1.0, 5) estimator = PassiveAggressiveClassifier(n_iter=1, shuffle=False) train_sizes_inc, train_scores_inc, test_scores_inc = \ learning_curve( estimator, X, y, train_sizes=train_sizes, cv=3, exploit_incremental_learning=True) train_sizes_batch, train_scores_batch, test_scores_batch = \ learning_curve( estimator, X, y, cv=3, train_sizes=train_sizes, exploit_incremental_learning=False) assert_array_equal(train_sizes_inc, train_sizes_batch) assert_array_almost_equal(train_scores_inc.mean(axis=1), train_scores_batch.mean(axis=1)) assert_array_almost_equal(test_scores_inc.mean(axis=1), test_scores_batch.mean(axis=1)) def test_learning_curve_n_sample_range_out_of_bounds(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[0, 1]) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[0.0, 1.0]) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[0.1, 1.1]) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[0, 20]) assert_raises(ValueError, learning_curve, estimator, X, y, cv=3, train_sizes=[1, 21]) def test_learning_curve_remove_duplicate_sample_sizes(): X, y = make_classification(n_samples=3, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(2) train_sizes, _, _ = assert_warns( RuntimeWarning, learning_curve, estimator, X, y, cv=3, train_sizes=np.linspace(0.33, 1.0, 3)) assert_array_equal(train_sizes, [1, 2]) def test_learning_curve_with_boolean_indices(): X, y = make_classification(n_samples=30, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) estimator = MockImprovingEstimator(20) cv = KFold(n=30, n_folds=3) train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, train_sizes=np.linspace(0.1, 1.0, 10)) assert_array_equal(train_sizes, np.linspace(2, 20, 10)) assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) def test_validation_curve(): X, y = make_classification(n_samples=2, n_features=1, n_informative=1, n_redundant=0, n_classes=2, n_clusters_per_class=1, random_state=0) param_range = np.linspace(0, 1, 10) with warnings.catch_warnings(record=True) as w: train_scores, test_scores = validation_curve( MockEstimatorWithParameter(), X, y, param_name="param", param_range=param_range, cv=2 ) if len(w) > 0: raise RuntimeError("Unexpected warning: %r" % w[0].message) assert_array_almost_equal(train_scores.mean(axis=1), param_range) assert_array_almost_equal(test_scores.mean(axis=1), 1 - param_range)
bsd-3-clause
Priyansh2/test
ltrc/extractor/classification/test.py
1
7909
# -*- coding: utf-8 -*- #! /usr/bin/env python3 from gensim import corpora, models import gensim from operator import itemgetter import numpy as np import sys import os import re import codecs import io import math from scipy import sparse from sklearn.cross_validation import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.base import TransformerMixin from sklearn import svm from sklearn import metrics from sklearn.pipeline import make_pipeline , Pipeline reload(sys) sys.setdefaultencoding('utf8') np.set_printoptions(threshold='nan') suffixes = { 1: ["ो", "े", "ू", "ु", "ी", "ि", "ा"], 2: ["कर", "ाओ", "िए", "ाई", "ाए", "ने", "नी", "ना", "ते", "ीं", "ती", "ता", "ाँ", "ां", "ों", "ें"], 3: ["ाकर", "ाइए", "ाईं", "ाया", "ेगी", "ेगा", "ोगी", "ोगे", "ाने", "ाना", "ाते", "ाती", "ाता", "तीं", "ाओं", "ाएं", "ुओं", "ुएं", "ुआं"], 4: ["ाएगी", "ाएगा", "ाओगी", "ाओगे", "एंगी", "ेंगी", "एंगे", "ेंगे", "ूंगी", "ूंगा", "ातीं", "नाओं", "नाएं", "ताओं", "ताएं", "ियाँ", "ियों", "ियां"], 5: ["ाएंगी", "ाएंगे", "ाऊंगी", "ाऊंगा", "ाइयाँ", "ाइयों", "ाइयां"], } categories=['A','C','D','E'] mappings={} mappings['A']=1 mappings['C']=3 mappings['D']=4 mappings['E']=5 path='/home/priyansh/Downloads/ltrc/1055/' train_data_path='/home/priyansh/Downloads/ltrc/extractor/clustering/four_class_devanagari/' path1=train_data_path+"A/" path2=train_data_path+"C/" path3=train_data_path+"D/" path4=train_data_path+"E/" documents=[] #contains all doc filenames along with class labels doc_info_with_label=[] #two tuple storage of doc info along with their respective labels def hi_stem(word): for L in 5, 4, 3, 2, 1: if len(word) > L + 1: for suf in suffixes[L]: if word.endswith(suf): return word[:-L] return word def store_data(dir_path_list): for dir_path in dir_path_list: class_name = dir_path.split("/")[8] for filename in os.listdir(dir_path): if filename not in documents: documents.append(filename+"+"+str(mappings[class_name])) infilename=os.path.join(dir_path,filename) with codecs.open(infilename,'r','utf-8') as fl: string='' for line in fl: for word in line.split(): if word!=" " or word!="\n": string+=word+" " fl.close() temp=[] temp.append(class_name) temp.append(string) doc_info_with_label.append(tuple(temp)) path_list=[] path_list.append(path1) path_list.append(path2) #path_list.append(path3) #path_list.append(path4) store_data(path_list) y = [d[0] for d in doc_info_with_label] #length is no:ofsamples corpus = [d[1] for d in doc_info_with_label] class feature_extractor(TransformerMixin): def __init__(self,*featurizers): self.featurizers = featurizers def fit(self,X,y=None): return self def transform(self,X): collection_features=[] for f in self.featurizers: collection_features.append(f(X)) feature_vect=np.array(collection_features[0]) if len(collection_features)>1: for i in range(1,len(collection_features)): feature_vect=np.concatenate((feature_vect,np.array(collection_features[i])),axis=1) #print feature_vect.shape return feature_vect.tolist() def tfidf_score(word,document_no,corpus_data): #print word my_word=word stopwords_path='/home/priyansh/Downloads/ltrc/extractor/' stop_words_filename='stopwords.txt' stopwords=[] #contain all stopwords with codecs.open(stopwords_path+stop_words_filename,'r','utf-8') as fl: for line in fl: for word in line.split(): stopwords.append(word) fl.close() document=corpus_data[document_no] #print document wordcount=0 total=0 temp = document.split() for i in temp: #print i if i not in stopwords: total+=1 if i==my_word: #print my_word #print word wordcount+=1 #print wordcount #print total tf = float(wordcount)/total #print tf #return tf(word,document)*idf(word,corpus_data) total_docs = len(corpus_data) count=0 for doc in corpus_data: temp=[] temp = doc.split() for i in temp: if i==word: count+=1 break total_docs_which_contains_the_words=count idf = math.log(total_docs/(1+total_docs_which_contains_the_words)) return tf*idf def tfidf(corpus_data): word_id_mapping={} cnt=0 stopwords_path='/home/priyansh/Downloads/ltrc/extractor/' stop_words_filename='stopwords.txt' stopwords=[] #contain all stopwords with codecs.open(stopwords_path+stop_words_filename,'r','utf-8') as fl: for line in fl: for word in line.split(): stopwords.append(word) fl.close() unique_words_in_corpus={} count=0 for data in corpus_data: corpus_id=count temp=[] temp=data.split() for word in temp: if word not in unique_words_in_corpus: unique_words_in_corpus[word]=corpus_id count+=1 stopped_unique_words_in_corpus={} for word in unique_words_in_corpus: if word not in stopwords: stopped_unique_words_in_corpus[word]=unique_words_in_corpus[word] word_id_mapping[word]=cnt cnt+=1 #print unique_words_in_corpus #print stopped_unique_words_in_corpus #print word_id_mapping feature_vect=[None]*len(corpus_data) #score_vect=[None]*cnt for i in range(0,len(corpus_data)): score_vect=[0]*cnt for word in stopped_unique_words_in_corpus: if i==stopped_unique_words_in_corpus[word]: #print word score=tfidf_score(word,i,corpus_data) #print score score_vect[word_id_mapping[word]]=score feature_vect[i]=score_vect return feature_vect def lda(corpus_data): stopwords_path='/home/priyansh/Downloads/ltrc/extractor/' stop_words_filename='stopwords.txt' stopwords=[] #contain all stopwords with codecs.open(stopwords_path+stop_words_filename,'r','utf-8') as fl: for line in fl: for word in line.split(): stopwords.append(word) fl.close() texts=[] for data in corpus_data: #print data tokens=[] temp=[] stopped_tokens=[] temp = data.split() for word in temp: tokens.append(word) #print tokens for i in tokens: if i not in stopwords: stopped_tokens.append(i) stemmed_tokens=[] for token in stopped_tokens: stemmed_token = hi_stem(token) stemmed_tokens.append(stemmed_token) texts.append(stemmed_tokens) dictionary = corpora.Dictionary(texts) corpus = [dictionary.doc2bow(text) for text in texts] num_topics=5 ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=10) doc_topics=[] for doc_vector in corpus: doc_topics.append(ldamodel[doc_vector]) for i in range(0,len(doc_topics)): doc_topics[i] = sorted(doc_topics[i],key=itemgetter(1),reverse=True) feature_vect=[] for i in doc_topics: prob_vect=[0]*num_topics #print i topic_num = i[0][0] topic_prob = i[0][1] prob_vect[topic_num]=topic_prob feature_vect.append(prob_vect) #print i #print feature_vect return feature_vect my_featurizer = feature_extractor(tfidf) X = my_featurizer.transform(corpus) #X = sparse.csr_matrix(X) X_train , X_test , y_train , y_test = train_test_split(X,y,test_size=0.2,random_state=42) #pipe = make_pipeline(my_featurizer,svm.LinearSVC()) #pipe.fit(X_train,y_train) #pred = pipe.predict(X_test) clf = svm.SVC(kernel='linear') clf.fit(X_train,y_train) pred = clf.predict(X_test) print "Expected output\n" print y_test print "\n" print "Output\n" print pred print "\n" score = clf.score(X_test,y_test) print score print "\n" print metrics.confusion_matrix(pred,y_test)
gpl-3.0
btabibian/scikit-learn
sklearn/feature_extraction/tests/test_text.py
8
35969
from __future__ import unicode_literals import warnings from sklearn.feature_extraction.text import strip_tags from sklearn.feature_extraction.text import strip_accents_unicode from sklearn.feature_extraction.text import strip_accents_ascii from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC from sklearn.base import clone import numpy as np from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal from numpy.testing import assert_raises from sklearn.utils.testing import (assert_equal, assert_false, assert_true, assert_not_equal, assert_almost_equal, assert_in, assert_less, assert_greater, assert_warns_message, assert_raise_message, clean_warning_registry, SkipTest) from collections import defaultdict, Mapping from functools import partial import pickle from io import StringIO JUNK_FOOD_DOCS = ( "the pizza pizza beer copyright", "the pizza burger beer copyright", "the the pizza beer beer copyright", "the burger beer beer copyright", "the coke burger coke copyright", "the coke burger burger", ) NOTJUNK_FOOD_DOCS = ( "the salad celeri copyright", "the salad salad sparkling water copyright", "the the celeri celeri copyright", "the tomato tomato salad water", "the tomato salad water copyright", ) ALL_FOOD_DOCS = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS def uppercase(s): return strip_accents_unicode(s).upper() def strip_eacute(s): return s.replace('\xe9', 'e') def split_tokenize(s): return s.split() def lazy_analyze(s): return ['the_ultimate_feature'] def test_strip_accents(): # check some classical latin accentuated symbols a = '\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb' expected = 'aaaaaaceeee' assert_equal(strip_accents_unicode(a), expected) a = '\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf9\xfa\xfb\xfc\xfd' expected = 'iiiinooooouuuuy' assert_equal(strip_accents_unicode(a), expected) # check some arabic a = '\u0625' # halef with a hamza below expected = '\u0627' # simple halef assert_equal(strip_accents_unicode(a), expected) # mix letters accentuated and not a = "this is \xe0 test" expected = 'this is a test' assert_equal(strip_accents_unicode(a), expected) def test_to_ascii(): # check some classical latin accentuated symbols a = '\xe0\xe1\xe2\xe3\xe4\xe5\xe7\xe8\xe9\xea\xeb' expected = 'aaaaaaceeee' assert_equal(strip_accents_ascii(a), expected) a = '\xec\xed\xee\xef\xf1\xf2\xf3\xf4\xf5\xf6\xf9\xfa\xfb\xfc\xfd' expected = 'iiiinooooouuuuy' assert_equal(strip_accents_ascii(a), expected) # check some arabic a = '\u0625' # halef with a hamza below expected = '' # halef has no direct ascii match assert_equal(strip_accents_ascii(a), expected) # mix letters accentuated and not a = "this is \xe0 test" expected = 'this is a test' assert_equal(strip_accents_ascii(a), expected) def test_word_analyzer_unigrams(): for Vectorizer in (CountVectorizer, HashingVectorizer): wa = Vectorizer(strip_accents='ascii').build_analyzer() text = ("J'ai mang\xe9 du kangourou ce midi, " "c'\xe9tait pas tr\xeas bon.") expected = ['ai', 'mange', 'du', 'kangourou', 'ce', 'midi', 'etait', 'pas', 'tres', 'bon'] assert_equal(wa(text), expected) text = "This is a test, really.\n\n I met Harry yesterday." expected = ['this', 'is', 'test', 'really', 'met', 'harry', 'yesterday'] assert_equal(wa(text), expected) wa = Vectorizer(input='file').build_analyzer() text = StringIO("This is a test with a file-like object!") expected = ['this', 'is', 'test', 'with', 'file', 'like', 'object'] assert_equal(wa(text), expected) # with custom preprocessor wa = Vectorizer(preprocessor=uppercase).build_analyzer() text = ("J'ai mang\xe9 du kangourou ce midi, " " c'\xe9tait pas tr\xeas bon.") expected = ['AI', 'MANGE', 'DU', 'KANGOUROU', 'CE', 'MIDI', 'ETAIT', 'PAS', 'TRES', 'BON'] assert_equal(wa(text), expected) # with custom tokenizer wa = Vectorizer(tokenizer=split_tokenize, strip_accents='ascii').build_analyzer() text = ("J'ai mang\xe9 du kangourou ce midi, " "c'\xe9tait pas tr\xeas bon.") expected = ["j'ai", 'mange', 'du', 'kangourou', 'ce', 'midi,', "c'etait", 'pas', 'tres', 'bon.'] assert_equal(wa(text), expected) def test_word_analyzer_unigrams_and_bigrams(): wa = CountVectorizer(analyzer="word", strip_accents='unicode', ngram_range=(1, 2)).build_analyzer() text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." expected = ['ai', 'mange', 'du', 'kangourou', 'ce', 'midi', 'etait', 'pas', 'tres', 'bon', 'ai mange', 'mange du', 'du kangourou', 'kangourou ce', 'ce midi', 'midi etait', 'etait pas', 'pas tres', 'tres bon'] assert_equal(wa(text), expected) def test_unicode_decode_error(): # decode_error default to strict, so this should fail # First, encode (as bytes) a unicode string. text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon." text_bytes = text.encode('utf-8') # Then let the Analyzer try to decode it as ascii. It should fail, # because we have given it an incorrect encoding. wa = CountVectorizer(ngram_range=(1, 2), encoding='ascii').build_analyzer() assert_raises(UnicodeDecodeError, wa, text_bytes) ca = CountVectorizer(analyzer='char', ngram_range=(3, 6), encoding='ascii').build_analyzer() assert_raises(UnicodeDecodeError, ca, text_bytes) def test_char_ngram_analyzer(): cnga = CountVectorizer(analyzer='char', strip_accents='unicode', ngram_range=(3, 6)).build_analyzer() text = "J'ai mang\xe9 du kangourou ce midi, c'\xe9tait pas tr\xeas bon" expected = ["j'a", "'ai", 'ai ', 'i m', ' ma'] assert_equal(cnga(text)[:5], expected) expected = ['s tres', ' tres ', 'tres b', 'res bo', 'es bon'] assert_equal(cnga(text)[-5:], expected) text = "This \n\tis a test, really.\n\n I met Harry yesterday" expected = ['thi', 'his', 'is ', 's i', ' is'] assert_equal(cnga(text)[:5], expected) expected = [' yeste', 'yester', 'esterd', 'sterda', 'terday'] assert_equal(cnga(text)[-5:], expected) cnga = CountVectorizer(input='file', analyzer='char', ngram_range=(3, 6)).build_analyzer() text = StringIO("This is a test with a file-like object!") expected = ['thi', 'his', 'is ', 's i', ' is'] assert_equal(cnga(text)[:5], expected) def test_char_wb_ngram_analyzer(): cnga = CountVectorizer(analyzer='char_wb', strip_accents='unicode', ngram_range=(3, 6)).build_analyzer() text = "This \n\tis a test, really.\n\n I met Harry yesterday" expected = [' th', 'thi', 'his', 'is ', ' thi'] assert_equal(cnga(text)[:5], expected) expected = ['yester', 'esterd', 'sterda', 'terday', 'erday '] assert_equal(cnga(text)[-5:], expected) cnga = CountVectorizer(input='file', analyzer='char_wb', ngram_range=(3, 6)).build_analyzer() text = StringIO("A test with a file-like object!") expected = [' a ', ' te', 'tes', 'est', 'st ', ' tes'] assert_equal(cnga(text)[:6], expected) def test_countvectorizer_custom_vocabulary(): vocab = {"pizza": 0, "beer": 1} terms = set(vocab.keys()) # Try a few of the supported types. for typ in [dict, list, iter, partial(defaultdict, int)]: v = typ(vocab) vect = CountVectorizer(vocabulary=v) vect.fit(JUNK_FOOD_DOCS) if isinstance(v, Mapping): assert_equal(vect.vocabulary_, vocab) else: assert_equal(set(vect.vocabulary_), terms) X = vect.transform(JUNK_FOOD_DOCS) assert_equal(X.shape[1], len(terms)) def test_countvectorizer_custom_vocabulary_pipeline(): what_we_like = ["pizza", "beer"] pipe = Pipeline([ ('count', CountVectorizer(vocabulary=what_we_like)), ('tfidf', TfidfTransformer())]) X = pipe.fit_transform(ALL_FOOD_DOCS) assert_equal(set(pipe.named_steps['count'].vocabulary_), set(what_we_like)) assert_equal(X.shape[1], len(what_we_like)) def test_countvectorizer_custom_vocabulary_repeated_indeces(): vocab = {"pizza": 0, "beer": 0} try: CountVectorizer(vocabulary=vocab) except ValueError as e: assert_in("vocabulary contains repeated indices", str(e).lower()) def test_countvectorizer_custom_vocabulary_gap_index(): vocab = {"pizza": 1, "beer": 2} try: CountVectorizer(vocabulary=vocab) except ValueError as e: assert_in("doesn't contain index", str(e).lower()) def test_countvectorizer_stop_words(): cv = CountVectorizer() cv.set_params(stop_words='english') assert_equal(cv.get_stop_words(), ENGLISH_STOP_WORDS) cv.set_params(stop_words='_bad_str_stop_') assert_raises(ValueError, cv.get_stop_words) cv.set_params(stop_words='_bad_unicode_stop_') assert_raises(ValueError, cv.get_stop_words) stoplist = ['some', 'other', 'words'] cv.set_params(stop_words=stoplist) assert_equal(cv.get_stop_words(), set(stoplist)) def test_countvectorizer_empty_vocabulary(): try: vect = CountVectorizer(vocabulary=[]) vect.fit(["foo"]) assert False, "we shouldn't get here" except ValueError as e: assert_in("empty vocabulary", str(e).lower()) try: v = CountVectorizer(max_df=1.0, stop_words="english") # fit on stopwords only v.fit(["to be or not to be", "and me too", "and so do you"]) assert False, "we shouldn't get here" except ValueError as e: assert_in("empty vocabulary", str(e).lower()) def test_fit_countvectorizer_twice(): cv = CountVectorizer() X1 = cv.fit_transform(ALL_FOOD_DOCS[:5]) X2 = cv.fit_transform(ALL_FOOD_DOCS[5:]) assert_not_equal(X1.shape[1], X2.shape[1]) def test_tf_idf_smoothing(): X = [[1, 1, 1], [1, 1, 0], [1, 0, 0]] tr = TfidfTransformer(smooth_idf=True, norm='l2') tfidf = tr.fit_transform(X).toarray() assert_true((tfidf >= 0).all()) # check normalization assert_array_almost_equal((tfidf ** 2).sum(axis=1), [1., 1., 1.]) # this is robust to features with only zeros X = [[1, 1, 0], [1, 1, 0], [1, 0, 0]] tr = TfidfTransformer(smooth_idf=True, norm='l2') tfidf = tr.fit_transform(X).toarray() assert_true((tfidf >= 0).all()) def test_tfidf_no_smoothing(): X = [[1, 1, 1], [1, 1, 0], [1, 0, 0]] tr = TfidfTransformer(smooth_idf=False, norm='l2') tfidf = tr.fit_transform(X).toarray() assert_true((tfidf >= 0).all()) # check normalization assert_array_almost_equal((tfidf ** 2).sum(axis=1), [1., 1., 1.]) # the lack of smoothing make IDF fragile in the presence of feature with # only zeros X = [[1, 1, 0], [1, 1, 0], [1, 0, 0]] tr = TfidfTransformer(smooth_idf=False, norm='l2') clean_warning_registry() with warnings.catch_warnings(record=True) as w: 1. / np.array([0.]) numpy_provides_div0_warning = len(w) == 1 in_warning_message = 'divide by zero' tfidf = assert_warns_message(RuntimeWarning, in_warning_message, tr.fit_transform, X).toarray() if not numpy_provides_div0_warning: raise SkipTest("Numpy does not provide div 0 warnings.") def test_sublinear_tf(): X = [[1], [2], [3]] tr = TfidfTransformer(sublinear_tf=True, use_idf=False, norm=None) tfidf = tr.fit_transform(X).toarray() assert_equal(tfidf[0], 1) 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(): # raw documents as an iterator train_data = iter(ALL_FOOD_DOCS[:-1]) test_data = [ALL_FOOD_DOCS[-1]] n_train = len(ALL_FOOD_DOCS) - 1 # test without vocabulary v1 = CountVectorizer(max_df=0.5) counts_train = v1.fit_transform(train_data) if hasattr(counts_train, 'tocsr'): counts_train = counts_train.tocsr() assert_equal(counts_train[0, v1.vocabulary_["pizza"]], 2) # build a vectorizer v1 with the same vocabulary as the one fitted by v1 v2 = CountVectorizer(vocabulary=v1.vocabulary_) # compare that the two vectorizer give the same output on the test sample for v in (v1, v2): counts_test = v.transform(test_data) if hasattr(counts_test, 'tocsr'): counts_test = counts_test.tocsr() vocabulary = v.vocabulary_ assert_equal(counts_test[0, vocabulary["salad"]], 1) assert_equal(counts_test[0, vocabulary["tomato"]], 1) assert_equal(counts_test[0, vocabulary["water"]], 1) # stop word from the fixed list assert_false("the" in vocabulary) # stop word found automatically by the vectorizer DF thresholding # words that are high frequent across the complete corpus are likely # to be not informative (either real stop words of extraction # artifacts) assert_false("copyright" in vocabulary) # not present in the sample assert_equal(counts_test[0, vocabulary["coke"]], 0) assert_equal(counts_test[0, vocabulary["burger"]], 0) assert_equal(counts_test[0, vocabulary["beer"]], 0) assert_equal(counts_test[0, vocabulary["pizza"]], 0) # test tf-idf t1 = TfidfTransformer(norm='l1') tfidf = t1.fit(counts_train).transform(counts_train).toarray() assert_equal(len(t1.idf_), len(v1.vocabulary_)) assert_equal(tfidf.shape, (n_train, len(v1.vocabulary_))) # test tf-idf with new data tfidf_test = t1.transform(counts_test).toarray() assert_equal(tfidf_test.shape, (len(test_data), len(v1.vocabulary_))) # test tf alone t2 = TfidfTransformer(norm='l1', use_idf=False) tf = t2.fit(counts_train).transform(counts_train).toarray() assert_false(hasattr(t2, "idf_")) # test idf transform with unlearned idf vector t3 = TfidfTransformer(use_idf=True) assert_raises(ValueError, t3.transform, counts_train) # test idf transform with incompatible n_features X = [[1, 1, 5], [1, 1, 0]] t3.fit(X) X_incompt = [[1, 3], [1, 3]] assert_raises(ValueError, t3.transform, X_incompt) # L1-normalized term frequencies sum to one assert_array_almost_equal(np.sum(tf, axis=1), [1.0] * n_train) # test the direct tfidf vectorizer # (equivalent to term count vectorizer + tfidf transformer) train_data = iter(ALL_FOOD_DOCS[:-1]) tv = TfidfVectorizer(norm='l1') tv.max_df = v1.max_df tfidf2 = tv.fit_transform(train_data).toarray() assert_false(tv.fixed_vocabulary_) assert_array_almost_equal(tfidf, tfidf2) # test the direct tfidf vectorizer with new data tfidf_test2 = tv.transform(test_data).toarray() assert_array_almost_equal(tfidf_test, tfidf_test2) # test transform on unfitted vectorizer with empty vocabulary v3 = CountVectorizer(vocabulary=None) assert_raises(ValueError, v3.transform, train_data) # ascii preprocessor? v3.set_params(strip_accents='ascii', lowercase=False) assert_equal(v3.build_preprocessor(), strip_accents_ascii) # error on bad strip_accents param v3.set_params(strip_accents='_gabbledegook_', preprocessor=None) assert_raises(ValueError, v3.build_preprocessor) # error with bad analyzer type v3.set_params = '_invalid_analyzer_type_' assert_raises(ValueError, v3.build_analyzer) def test_tfidf_vectorizer_setters(): tv = TfidfVectorizer(norm='l2', use_idf=False, smooth_idf=False, sublinear_tf=False) tv.norm = 'l1' assert_equal(tv._tfidf.norm, 'l1') tv.use_idf = True assert_true(tv._tfidf.use_idf) tv.smooth_idf = True assert_true(tv._tfidf.smooth_idf) tv.sublinear_tf = True assert_true(tv._tfidf.sublinear_tf) def test_hashing_vectorizer(): v = HashingVectorizer() X = v.transform(ALL_FOOD_DOCS) token_nnz = X.nnz assert_equal(X.shape, (len(ALL_FOOD_DOCS), v.n_features)) assert_equal(X.dtype, v.dtype) # By default the hashed values receive a random sign and l2 normalization # makes the feature values bounded assert_true(np.min(X.data) > -1) assert_true(np.min(X.data) < 0) assert_true(np.max(X.data) > 0) assert_true(np.max(X.data) < 1) # Check that the rows are normalized for i in range(X.shape[0]): assert_almost_equal(np.linalg.norm(X[0].data, 2), 1.0) # Check vectorization with some non-default parameters v = HashingVectorizer(ngram_range=(1, 2), non_negative=True, norm='l1') X = v.transform(ALL_FOOD_DOCS) assert_equal(X.shape, (len(ALL_FOOD_DOCS), v.n_features)) assert_equal(X.dtype, v.dtype) # ngrams generate more non zeros ngrams_nnz = X.nnz assert_true(ngrams_nnz > token_nnz) assert_true(ngrams_nnz < 2 * token_nnz) # makes the feature values bounded assert_true(np.min(X.data) > 0) assert_true(np.max(X.data) < 1) # Check that the rows are normalized for i in range(X.shape[0]): assert_almost_equal(np.linalg.norm(X[0].data, 1), 1.0) def test_feature_names(): cv = CountVectorizer(max_df=0.5) # test for Value error on unfitted/empty vocabulary assert_raises(ValueError, cv.get_feature_names) X = cv.fit_transform(ALL_FOOD_DOCS) n_samples, n_features = X.shape assert_equal(len(cv.vocabulary_), n_features) feature_names = cv.get_feature_names() assert_equal(len(feature_names), n_features) assert_array_equal(['beer', 'burger', 'celeri', 'coke', 'pizza', 'salad', 'sparkling', 'tomato', 'water'], feature_names) for idx, name in enumerate(feature_names): assert_equal(idx, cv.vocabulary_.get(name)) def test_vectorizer_max_features(): vec_factories = ( CountVectorizer, TfidfVectorizer, ) expected_vocabulary = set(['burger', 'beer', 'salad', 'pizza']) expected_stop_words = set([u'celeri', u'tomato', u'copyright', u'coke', u'sparkling', u'water', u'the']) for vec_factory in vec_factories: # test bounded number of extracted features vectorizer = vec_factory(max_df=0.6, max_features=4) vectorizer.fit(ALL_FOOD_DOCS) assert_equal(set(vectorizer.vocabulary_), expected_vocabulary) assert_equal(vectorizer.stop_words_, expected_stop_words) def test_count_vectorizer_max_features(): # Regression test: max_features didn't work correctly in 0.14. cv_1 = CountVectorizer(max_features=1) cv_3 = CountVectorizer(max_features=3) cv_None = CountVectorizer(max_features=None) counts_1 = cv_1.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) counts_3 = cv_3.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) counts_None = cv_None.fit_transform(JUNK_FOOD_DOCS).sum(axis=0) features_1 = cv_1.get_feature_names() features_3 = cv_3.get_feature_names() features_None = cv_None.get_feature_names() # The most common feature is "the", with frequency 7. assert_equal(7, counts_1.max()) assert_equal(7, counts_3.max()) assert_equal(7, counts_None.max()) # The most common feature should be the same assert_equal("the", features_1[np.argmax(counts_1)]) assert_equal("the", features_3[np.argmax(counts_3)]) assert_equal("the", features_None[np.argmax(counts_None)]) def test_vectorizer_max_df(): test_data = ['abc', 'dea', 'eat'] vect = CountVectorizer(analyzer='char', max_df=1.0) vect.fit(test_data) assert_true('a' in vect.vocabulary_.keys()) assert_equal(len(vect.vocabulary_.keys()), 6) assert_equal(len(vect.stop_words_), 0) vect.max_df = 0.5 # 0.5 * 3 documents -> max_doc_count == 1.5 vect.fit(test_data) assert_true('a' not in vect.vocabulary_.keys()) # {ae} ignored assert_equal(len(vect.vocabulary_.keys()), 4) # {bcdt} remain assert_true('a' in vect.stop_words_) assert_equal(len(vect.stop_words_), 2) vect.max_df = 1 vect.fit(test_data) assert_true('a' not in vect.vocabulary_.keys()) # {ae} ignored assert_equal(len(vect.vocabulary_.keys()), 4) # {bcdt} remain assert_true('a' in vect.stop_words_) assert_equal(len(vect.stop_words_), 2) def test_vectorizer_min_df(): test_data = ['abc', 'dea', 'eat'] vect = CountVectorizer(analyzer='char', min_df=1) vect.fit(test_data) assert_true('a' in vect.vocabulary_.keys()) assert_equal(len(vect.vocabulary_.keys()), 6) assert_equal(len(vect.stop_words_), 0) vect.min_df = 2 vect.fit(test_data) assert_true('c' not in vect.vocabulary_.keys()) # {bcdt} ignored assert_equal(len(vect.vocabulary_.keys()), 2) # {ae} remain assert_true('c' in vect.stop_words_) assert_equal(len(vect.stop_words_), 4) vect.min_df = 0.8 # 0.8 * 3 documents -> min_doc_count == 2.4 vect.fit(test_data) assert_true('c' not in vect.vocabulary_.keys()) # {bcdet} ignored assert_equal(len(vect.vocabulary_.keys()), 1) # {a} remains assert_true('c' in vect.stop_words_) assert_equal(len(vect.stop_words_), 5) def test_count_binary_occurrences(): # by default multiple occurrences are counted as longs test_data = ['aaabc', 'abbde'] vect = CountVectorizer(analyzer='char', max_df=1.0) X = vect.fit_transform(test_data).toarray() assert_array_equal(['a', 'b', 'c', 'd', 'e'], vect.get_feature_names()) assert_array_equal([[3, 1, 1, 0, 0], [1, 2, 0, 1, 1]], X) # using boolean features, we can fetch the binary occurrence info # instead. vect = CountVectorizer(analyzer='char', max_df=1.0, binary=True) X = vect.fit_transform(test_data).toarray() assert_array_equal([[1, 1, 1, 0, 0], [1, 1, 0, 1, 1]], X) # check the ability to change the dtype vect = CountVectorizer(analyzer='char', max_df=1.0, binary=True, dtype=np.float32) X_sparse = vect.fit_transform(test_data) assert_equal(X_sparse.dtype, np.float32) def test_hashed_binary_occurrences(): # by default multiple occurrences are counted as longs test_data = ['aaabc', 'abbde'] vect = HashingVectorizer(analyzer='char', non_negative=True, norm=None) X = vect.transform(test_data) assert_equal(np.max(X[0:1].data), 3) assert_equal(np.max(X[1:2].data), 2) assert_equal(X.dtype, np.float64) # using boolean features, we can fetch the binary occurrence info # instead. vect = HashingVectorizer(analyzer='char', non_negative=True, binary=True, norm=None) X = vect.transform(test_data) assert_equal(np.max(X.data), 1) assert_equal(X.dtype, np.float64) # check the ability to change the dtype vect = HashingVectorizer(analyzer='char', non_negative=True, binary=True, norm=None, dtype=np.float64) X = vect.transform(test_data) assert_equal(X.dtype, np.float64) def test_vectorizer_inverse_transform(): # raw documents data = ALL_FOOD_DOCS for vectorizer in (TfidfVectorizer(), CountVectorizer()): transformed_data = vectorizer.fit_transform(data) inversed_data = vectorizer.inverse_transform(transformed_data) analyze = vectorizer.build_analyzer() for doc, inversed_terms in zip(data, inversed_data): terms = np.sort(np.unique(analyze(doc))) inversed_terms = np.sort(np.unique(inversed_terms)) assert_array_equal(terms, inversed_terms) # Test that inverse_transform also works with numpy arrays transformed_data = transformed_data.toarray() inversed_data2 = vectorizer.inverse_transform(transformed_data) for terms, terms2 in zip(inversed_data, inversed_data2): assert_array_equal(np.sort(terms), np.sort(terms2)) def test_count_vectorizer_pipeline_grid_selection(): # raw documents data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS # label junk food as -1, the others as +1 target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) # split the dataset for model development and final evaluation train_data, test_data, target_train, target_test = train_test_split( data, target, test_size=.2, random_state=0) pipeline = Pipeline([('vect', CountVectorizer()), ('svc', LinearSVC())]) parameters = { 'vect__ngram_range': [(1, 1), (1, 2)], 'svc__loss': ('hinge', 'squared_hinge') } # find the best parameters for both the feature extraction and the # classifier grid_search = GridSearchCV(pipeline, parameters, n_jobs=1) # Check that the best model found by grid search is 100% correct on the # held out evaluation set. pred = grid_search.fit(train_data, target_train).predict(test_data) assert_array_equal(pred, target_test) # on this toy dataset bigram representation which is used in the last of # the grid_search is considered the best estimator since they all converge # to 100% accuracy models assert_equal(grid_search.best_score_, 1.0) best_vectorizer = grid_search.best_estimator_.named_steps['vect'] assert_equal(best_vectorizer.ngram_range, (1, 1)) def test_vectorizer_pipeline_grid_selection(): # raw documents data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS # label junk food as -1, the others as +1 target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) # split the dataset for model development and final evaluation train_data, test_data, target_train, target_test = train_test_split( data, target, test_size=.1, random_state=0) pipeline = Pipeline([('vect', TfidfVectorizer()), ('svc', LinearSVC())]) parameters = { 'vect__ngram_range': [(1, 1), (1, 2)], 'vect__norm': ('l1', 'l2'), 'svc__loss': ('hinge', 'squared_hinge'), } # find the best parameters for both the feature extraction and the # classifier grid_search = GridSearchCV(pipeline, parameters, n_jobs=1) # Check that the best model found by grid search is 100% correct on the # held out evaluation set. pred = grid_search.fit(train_data, target_train).predict(test_data) assert_array_equal(pred, target_test) # on this toy dataset bigram representation which is used in the last of # the grid_search is considered the best estimator since they all converge # to 100% accuracy models assert_equal(grid_search.best_score_, 1.0) best_vectorizer = grid_search.best_estimator_.named_steps['vect'] assert_equal(best_vectorizer.ngram_range, (1, 1)) assert_equal(best_vectorizer.norm, 'l2') assert_false(best_vectorizer.fixed_vocabulary_) def test_vectorizer_pipeline_cross_validation(): # raw documents data = JUNK_FOOD_DOCS + NOTJUNK_FOOD_DOCS # label junk food as -1, the others as +1 target = [-1] * len(JUNK_FOOD_DOCS) + [1] * len(NOTJUNK_FOOD_DOCS) pipeline = Pipeline([('vect', TfidfVectorizer()), ('svc', LinearSVC())]) cv_scores = cross_val_score(pipeline, data, target, cv=3) assert_array_equal(cv_scores, [1., 1., 1.]) def test_vectorizer_unicode(): # tests that the count vectorizer works with cyrillic. document = ( "\xd0\x9c\xd0\xb0\xd1\x88\xd0\xb8\xd0\xbd\xd0\xbd\xd0\xbe\xd0" "\xb5 \xd0\xbe\xd0\xb1\xd1\x83\xd1\x87\xd0\xb5\xd0\xbd\xd0\xb8\xd0" "\xb5 \xe2\x80\x94 \xd0\xbe\xd0\xb1\xd1\x88\xd0\xb8\xd1\x80\xd0\xbd" "\xd1\x8b\xd0\xb9 \xd0\xbf\xd0\xbe\xd0\xb4\xd1\x80\xd0\xb0\xd0\xb7" "\xd0\xb4\xd0\xb5\xd0\xbb \xd0\xb8\xd1\x81\xd0\xba\xd1\x83\xd1\x81" "\xd1\x81\xd1\x82\xd0\xb2\xd0\xb5\xd0\xbd\xd0\xbd\xd0\xbe\xd0\xb3" "\xd0\xbe \xd0\xb8\xd0\xbd\xd1\x82\xd0\xb5\xd0\xbb\xd0\xbb\xd0" "\xb5\xd0\xba\xd1\x82\xd0\xb0, \xd0\xb8\xd0\xb7\xd1\x83\xd1\x87" "\xd0\xb0\xd1\x8e\xd1\x89\xd0\xb8\xd0\xb9 \xd0\xbc\xd0\xb5\xd1\x82" "\xd0\xbe\xd0\xb4\xd1\x8b \xd0\xbf\xd0\xbe\xd1\x81\xd1\x82\xd1\x80" "\xd0\xbe\xd0\xb5\xd0\xbd\xd0\xb8\xd1\x8f \xd0\xb0\xd0\xbb\xd0\xb3" "\xd0\xbe\xd1\x80\xd0\xb8\xd1\x82\xd0\xbc\xd0\xbe\xd0\xb2, \xd1\x81" "\xd0\xbf\xd0\xbe\xd1\x81\xd0\xbe\xd0\xb1\xd0\xbd\xd1\x8b\xd1\x85 " "\xd0\xbe\xd0\xb1\xd1\x83\xd1\x87\xd0\xb0\xd1\x82\xd1\x8c\xd1\x81\xd1" "\x8f.") vect = CountVectorizer() X_counted = vect.fit_transform([document]) assert_equal(X_counted.shape, (1, 15)) vect = HashingVectorizer(norm=None, non_negative=True) X_hashed = vect.transform([document]) assert_equal(X_hashed.shape, (1, 2 ** 20)) # No collisions on such a small dataset assert_equal(X_counted.nnz, X_hashed.nnz) # When norm is None and non_negative, the tokens are counted up to # collisions assert_array_equal(np.sort(X_counted.data), np.sort(X_hashed.data)) def test_tfidf_vectorizer_with_fixed_vocabulary(): # non regression smoke test for inheritance issues vocabulary = ['pizza', 'celeri'] vect = TfidfVectorizer(vocabulary=vocabulary) X_1 = vect.fit_transform(ALL_FOOD_DOCS) X_2 = vect.transform(ALL_FOOD_DOCS) assert_array_almost_equal(X_1.toarray(), X_2.toarray()) assert_true(vect.fixed_vocabulary_) def test_pickling_vectorizer(): instances = [ HashingVectorizer(), HashingVectorizer(norm='l1'), HashingVectorizer(binary=True), HashingVectorizer(ngram_range=(1, 2)), CountVectorizer(), CountVectorizer(preprocessor=strip_tags), CountVectorizer(analyzer=lazy_analyze), CountVectorizer(preprocessor=strip_tags).fit(JUNK_FOOD_DOCS), CountVectorizer(strip_accents=strip_eacute).fit(JUNK_FOOD_DOCS), TfidfVectorizer(), TfidfVectorizer(analyzer=lazy_analyze), TfidfVectorizer().fit(JUNK_FOOD_DOCS), ] for orig in instances: s = pickle.dumps(orig) copy = pickle.loads(s) assert_equal(type(copy), orig.__class__) assert_equal(copy.get_params(), orig.get_params()) assert_array_equal( copy.fit_transform(JUNK_FOOD_DOCS).toarray(), orig.fit_transform(JUNK_FOOD_DOCS).toarray()) def test_countvectorizer_vocab_sets_when_pickling(): # ensure that vocabulary of type set is coerced to a list to # preserve iteration ordering after deserialization rng = np.random.RandomState(0) vocab_words = np.array(['beer', 'burger', 'celeri', 'coke', 'pizza', 'salad', 'sparkling', 'tomato', 'water']) for x in range(0, 100): vocab_set = set(rng.choice(vocab_words, size=5, replace=False)) cv = CountVectorizer(vocabulary=vocab_set) unpickled_cv = pickle.loads(pickle.dumps(cv)) cv.fit(ALL_FOOD_DOCS) unpickled_cv.fit(ALL_FOOD_DOCS) assert_equal(cv.get_feature_names(), unpickled_cv.get_feature_names()) def test_countvectorizer_vocab_dicts_when_pickling(): rng = np.random.RandomState(0) vocab_words = np.array(['beer', 'burger', 'celeri', 'coke', 'pizza', 'salad', 'sparkling', 'tomato', 'water']) for x in range(0, 100): vocab_dict = dict() words = rng.choice(vocab_words, size=5, replace=False) for y in range(0, 5): vocab_dict[words[y]] = y cv = CountVectorizer(vocabulary=vocab_dict) unpickled_cv = pickle.loads(pickle.dumps(cv)) cv.fit(ALL_FOOD_DOCS) unpickled_cv.fit(ALL_FOOD_DOCS) assert_equal(cv.get_feature_names(), unpickled_cv.get_feature_names()) def test_stop_words_removal(): # Ensure that deleting the stop_words_ attribute doesn't affect transform fitted_vectorizers = ( TfidfVectorizer().fit(JUNK_FOOD_DOCS), CountVectorizer(preprocessor=strip_tags).fit(JUNK_FOOD_DOCS), CountVectorizer(strip_accents=strip_eacute).fit(JUNK_FOOD_DOCS) ) for vect in fitted_vectorizers: vect_transform = vect.transform(JUNK_FOOD_DOCS).toarray() vect.stop_words_ = None stop_None_transform = vect.transform(JUNK_FOOD_DOCS).toarray() delattr(vect, 'stop_words_') stop_del_transform = vect.transform(JUNK_FOOD_DOCS).toarray() assert_array_equal(stop_None_transform, vect_transform) assert_array_equal(stop_del_transform, vect_transform) def test_pickling_transformer(): X = CountVectorizer().fit_transform(JUNK_FOOD_DOCS) orig = TfidfTransformer().fit(X) s = pickle.dumps(orig) copy = pickle.loads(s) assert_equal(type(copy), orig.__class__) assert_array_equal( copy.fit_transform(X).toarray(), orig.fit_transform(X).toarray()) def test_non_unique_vocab(): vocab = ['a', 'b', 'c', 'a', 'a'] vect = CountVectorizer(vocabulary=vocab) assert_raises(ValueError, vect.fit, []) def test_hashingvectorizer_nan_in_docs(): # np.nan can appear when using pandas to load text fields from a csv file # with missing values. message = "np.nan is an invalid document, expected byte or unicode string." exception = ValueError def func(): hv = HashingVectorizer() hv.fit_transform(['hello world', np.nan, 'hello hello']) assert_raise_message(exception, message, func) def test_tfidfvectorizer_binary(): # Non-regression test: TfidfVectorizer used to ignore its "binary" param. v = TfidfVectorizer(binary=True, use_idf=False, norm=None) assert_true(v.binary) X = v.fit_transform(['hello world', 'hello hello']).toarray() assert_array_equal(X.ravel(), [1, 1, 1, 0]) X2 = v.transform(['hello world', 'hello hello']).toarray() assert_array_equal(X2.ravel(), [1, 1, 1, 0]) def test_tfidfvectorizer_export_idf(): vect = TfidfVectorizer(use_idf=True) vect.fit(JUNK_FOOD_DOCS) assert_array_almost_equal(vect.idf_, vect._tfidf.idf_) def test_vectorizer_vocab_clone(): vect_vocab = TfidfVectorizer(vocabulary=["the"]) vect_vocab_clone = clone(vect_vocab) vect_vocab.fit(ALL_FOOD_DOCS) vect_vocab_clone.fit(ALL_FOOD_DOCS) assert_equal(vect_vocab_clone.vocabulary_, vect_vocab.vocabulary_) def test_vectorizer_string_object_as_input(): message = ("Iterable over raw text documents expected, " "string object received.") for vec in [CountVectorizer(), TfidfVectorizer(), HashingVectorizer()]: assert_raise_message( ValueError, message, vec.fit_transform, "hello world!") assert_raise_message( ValueError, message, vec.fit, "hello world!") assert_raise_message( ValueError, message, vec.transform, "hello world!")
bsd-3-clause
jundongl/PyFeaST
skfeature/example/test_CIFE.py
3
1485
import scipy.io from sklearn.metrics import accuracy_score from sklearn import cross_validation from sklearn import svm from skfeature.function.information_theoretical_based import CIFE def main(): # load data mat = scipy.io.loadmat('../data/colon.mat') X = mat['X'] # data X = X.astype(float) y = mat['Y'] # label y = y[:, 0] n_samples, n_features = X.shape # number of samples and number of features # split data into 10 folds ss = cross_validation.KFold(n_samples, n_folds=10, shuffle=True) # perform evaluation on classification task num_fea = 10 # number of selected features clf = svm.LinearSVC() # linear SVM correct = 0 for train, test in ss: # obtain the index of each feature on the training set idx,_,_ = CIFE.cife(X[train], y[train], n_selected_features=num_fea) # obtain the dataset on the selected features features = X[:, idx[0:num_fea]] # train a classification model with the selected features on the training dataset clf.fit(features[train], y[train]) # predict the class labels of test data y_predict = clf.predict(features[test]) # obtain the classification accuracy on the test data acc = accuracy_score(y[test], y_predict) correct = correct + acc # output the average classification accuracy over all 10 folds print 'Accuracy:', float(correct)/10 if __name__ == '__main__': main()
gpl-2.0
Sealos/Sarcasm
Proyecto Final/prueba.py
1
2337
import numpy as np from sklearn import datasets, svm """ iris = datasets.load_iris() iris_X = iris.data iris_y = iris.target np.unique(iris_y) np.random.seed(0) indices = np.random.permutation(len(iris_X)) iris_X_train = iris_X[indices[:-10]] iris_y_train = iris_y[indices[:-10]] iris_X_test = iris_X[indices[-10:]] iris_y_test = iris_y[indices[-10:]] svc = svm.SVC(kernel='rbf') svc.fit(iris_X_train, iris_y_train) print svc.predict(iris_X) """ import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets # import some data to play with iris = datasets.load_iris() # we create an instance of SVM and fit out data. We do not scale our # data since we want to plot the support vectors C = 1.0 # SVM regularization parameter print iris.data[1,1] 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 svc = svm.SVC(kernel='linear', C=C).fit(X, y) rbf_svc = svm.SVC(kernel='rbf', gamma=0.7, C=C).fit(X, y) poly_svc = svm.SVC(kernel='poly', degree=3, C=C).fit(X, y) lin_svc = svm.LinearSVC(C=C).fit(X, y) # create a mesh to plot in 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)) # title for the plots titles = ['SVC with linear kernel', 'LinearSVC (linear kernel)', 'SVC with RBF kernel', 'SVC with polynomial (degree 3) kernel'] for i, clf in enumerate((svc, lin_svc, rbf_svc, poly_svc)): # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. plt.subplot(2, 2, i + 1) plt.subplots_adjust(wspace=0.4, hspace=0.4) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.title(titles[i]) plt.show()
gpl-2.0
imaculate/scikit-learn
examples/applications/plot_species_distribution_modeling.py
55
7386
""" ============================= Species distribution modeling ============================= Modeling species' geographic distributions is an important problem in conservation biology. In this example we model the geographic distribution of two south american mammals given past observations and 14 environmental variables. Since we have only positive examples (there are no unsuccessful observations), we cast this problem as a density estimation problem and use the `OneClassSVM` provided by the package `sklearn.svm` as our modeling tool. The dataset is provided by Phillips et. al. (2006). If available, the example uses `basemap <http://matplotlib.org/basemap>`_ to plot the coast lines and national boundaries of South America. The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/details/3038/0>`_ , the Brown-throated Sloth. - `"Microryzomys minutus" <http://www.iucnredlist.org/details/13408/0>`_ , also known as the Forest Small Rice Rat, a rodent that lives in Peru, Colombia, Ecuador, Peru, and Venezuela. References ---------- * `"Maximum entropy modeling of species geographic distributions" <http://www.cs.princeton.edu/~schapire/papers/ecolmod.pdf>`_ S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006. """ # Authors: Peter Prettenhofer <[email protected]> # Jake Vanderplas <[email protected]> # # License: BSD 3 clause from __future__ import print_function from time import time import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.base import Bunch from sklearn.datasets import fetch_species_distributions from sklearn.datasets.species_distributions import construct_grids from sklearn import svm, metrics # if basemap is available, we'll use it. # otherwise, we'll improvise later... try: from mpl_toolkits.basemap import Basemap basemap = True except ImportError: basemap = False print(__doc__) def create_species_bunch(species_name, train, test, coverages, xgrid, ygrid): """Create a bunch with information about a particular organism This will use the test/train record arrays to extract the data specific to the given species name. """ bunch = Bunch(name=' '.join(species_name.split("_")[:2])) species_name = species_name.encode('ascii') points = dict(test=test, train=train) for label, pts in points.items(): # choose points associated with the desired species pts = pts[pts['species'] == species_name] bunch['pts_%s' % label] = pts # determine coverage values for each of the training & testing points ix = np.searchsorted(xgrid, pts['dd long']) iy = np.searchsorted(ygrid, pts['dd lat']) bunch['cov_%s' % label] = coverages[:, -iy, ix].T return bunch def plot_species_distribution(species=("bradypus_variegatus_0", "microryzomys_minutus_0")): """ Plot the species distribution. """ if len(species) > 2: print("Note: when more than two species are provided," " only the first two will be used") t0 = time() # Load the compressed data data = fetch_species_distributions() # Set up the data grid xgrid, ygrid = construct_grids(data) # The grid in x,y coordinates X, Y = np.meshgrid(xgrid, ygrid[::-1]) # create a bunch for each species BV_bunch = create_species_bunch(species[0], data.train, data.test, data.coverages, xgrid, ygrid) MM_bunch = create_species_bunch(species[1], data.train, data.test, data.coverages, xgrid, ygrid) # background points (grid coordinates) for evaluation np.random.seed(13) background_points = np.c_[np.random.randint(low=0, high=data.Ny, size=10000), np.random.randint(low=0, high=data.Nx, size=10000)].T # We'll make use of the fact that coverages[6] has measurements at all # land points. This will help us decide between land and water. land_reference = data.coverages[6] # Fit, predict, and plot for each species. for i, species in enumerate([BV_bunch, MM_bunch]): print("_" * 80) print("Modeling distribution of species '%s'" % species.name) # Standardize features mean = species.cov_train.mean(axis=0) std = species.cov_train.std(axis=0) train_cover_std = (species.cov_train - mean) / std # Fit OneClassSVM print(" - fit OneClassSVM ... ", end='') clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.5) clf.fit(train_cover_std) print("done.") # Plot map of South America plt.subplot(1, 2, i + 1) if basemap: print(" - plot coastlines using basemap") m = Basemap(projection='cyl', llcrnrlat=Y.min(), urcrnrlat=Y.max(), llcrnrlon=X.min(), urcrnrlon=X.max(), resolution='c') m.drawcoastlines() m.drawcountries() else: print(" - plot coastlines from coverage") plt.contour(X, Y, land_reference, levels=[-9999], colors="k", linestyles="solid") plt.xticks([]) plt.yticks([]) print(" - predict species distribution") # Predict species distribution using the training data Z = np.ones((data.Ny, data.Nx), dtype=np.float64) # We'll predict only for the land points. idx = np.where(land_reference > -9999) coverages_land = data.coverages[:, idx[0], idx[1]].T pred = clf.decision_function((coverages_land - mean) / std)[:, 0] Z *= pred.min() Z[idx[0], idx[1]] = pred levels = np.linspace(Z.min(), Z.max(), 25) Z[land_reference == -9999] = -9999 # plot contours of the prediction plt.contourf(X, Y, Z, levels=levels, cmap=plt.cm.Reds) plt.colorbar(format='%.2f') # scatter training/testing points plt.scatter(species.pts_train['dd long'], species.pts_train['dd lat'], s=2 ** 2, c='black', marker='^', label='train') plt.scatter(species.pts_test['dd long'], species.pts_test['dd lat'], s=2 ** 2, c='black', marker='x', label='test') plt.legend() plt.title(species.name) plt.axis('equal') # Compute AUC with regards to background points pred_background = Z[background_points[0], background_points[1]] pred_test = clf.decision_function((species.cov_test - mean) / std)[:, 0] scores = np.r_[pred_test, pred_background] y = np.r_[np.ones(pred_test.shape), np.zeros(pred_background.shape)] fpr, tpr, thresholds = metrics.roc_curve(y, scores) roc_auc = metrics.auc(fpr, tpr) plt.text(-35, -70, "AUC: %.3f" % roc_auc, ha="right") print("\n Area under the ROC curve : %f" % roc_auc) print("\ntime elapsed: %.2fs" % (time() - t0)) plot_species_distribution() plt.show()
bsd-3-clause
cdegroc/scikit-learn
sklearn/datasets/lfw.py
6
16362
"""Loader for the Labeled Faces in the Wild (LFW) dataset This dataset is a collection of JPEG pictures of famous people collected over the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. The typical task is called Face Verification: given a pair of two pictures, a binary classifier must predict whether the two images are from the same person. An alternative task, Face Recognition or Face Identification is: given the picture of the face of an unknown person, identify the name of the person by refering to a gallery of previously seen pictures of identified persons. Both Face Verification and Face Recognition are tasks that are typically performed on the output of a model trained to perform Face Detection. The most popular model for Face Detection is called Viola-Johns and is implemented in the OpenCV library. The LFW faces were extracted by this face detector from various online websites. """ # Copyright (c) 2011 Olivier Grisel <[email protected]> # License: Simplified BSD from os import listdir, makedirs, remove from os.path import join, exists, isdir import logging import numpy as np import urllib from .base import get_data_home, Bunch from ..externals.joblib import Memory logger = logging.getLogger(__name__) BASE_URL = "http://vis-www.cs.umass.edu/lfw/" ARCHIVE_NAME = "lfw.tgz" FUNNELED_ARCHIVE_NAME = "lfw-funneled.tgz" TARGET_FILENAMES = [ 'pairsDevTrain.txt', 'pairsDevTest.txt', 'pairs.txt', ] def scale_face(face): """Scale back to 0-1 range in case of normalization for plotting""" scaled = face - face.min() scaled /= scaled.max() return scaled # # Common private utilities for data fetching from the original LFW website # local disk caching, and image decoding. # def check_fetch_lfw(data_home=None, funneled=True, download_if_missing=True): """Helper function to download any missing LFW data""" data_home = get_data_home(data_home=data_home) lfw_home = join(data_home, "lfw_home") if funneled: archive_path = join(lfw_home, FUNNELED_ARCHIVE_NAME) data_folder_path = join(lfw_home, "lfw_funneled") archive_url = BASE_URL + FUNNELED_ARCHIVE_NAME else: archive_path = join(lfw_home, ARCHIVE_NAME) data_folder_path = join(lfw_home, "lfw") archive_url = BASE_URL + ARCHIVE_NAME if not exists(lfw_home): makedirs(lfw_home) for target_filename in TARGET_FILENAMES: target_filepath = join(lfw_home, target_filename) if not exists(target_filepath): if download_if_missing: url = BASE_URL + target_filename logger.warn("Downloading LFW metadata: %s", url) urllib.urlretrieve(url, target_filepath) else: raise IOError("%s is missing" % target_filepath) if not exists(data_folder_path): if not exists(archive_path): if download_if_missing: logger.warn("Downloading LFW data (~200MB): %s", archive_url) urllib.urlretrieve(archive_url, archive_path) else: raise IOError("%s is missing" % target_filepath) import tarfile logger.info("Decompressing the data archive to %s", data_folder_path) tarfile.open(archive_path, "r:gz").extractall(path=lfw_home) remove(archive_path) return lfw_home, data_folder_path def _load_imgs(file_paths, slice_, color, resize): """Internally used to load images""" # Try to import imread and imresize from PIL. We do this here to prevent # the whole sklearn.datasets module from depending on PIL. try: try: from scipy.misc import imread except ImportError: from scipy.misc.pilutil import imread from scipy.misc import imresize except ImportError: raise ImportError("The Python Imaging Library (PIL)" "is required to load data from jpeg files") # compute the portion of the images to load to respect the slice_ parameter # given by the caller default_slice = (slice(0, 250), slice(0, 250)) if slice_ is None: slice_ = default_slice else: slice_ = tuple(s or ds for s, ds in zip(slice_, default_slice)) h_slice, w_slice = slice_ h = (h_slice.stop - h_slice.start) / (h_slice.step or 1) w = (w_slice.stop - w_slice.start) / (w_slice.step or 1) if resize is not None: resize = float(resize) h = int(resize * h) w = int(resize * w) # allocate some contiguous memory to host the decoded image slices n_faces = len(file_paths) if not color: faces = np.zeros((n_faces, h, w), dtype=np.float32) else: faces = np.zeros((n_faces, h, w, 3), dtype=np.float32) # iterate over the collected file path to load the jpeg files as numpy # arrays for i, file_path in enumerate(file_paths): if i % 1000 == 0: logger.info("Loading face #%05d / %05d", i + 1, n_faces) face = np.asarray(imread(file_path)[slice_], dtype=np.float32) face /= 255.0 # scale uint8 coded colors to the [0.0, 1.0] floats if resize is not None: face = imresize(face, resize) if not color: # average the color channels to compute a gray levels # representaion face = face.mean(axis=2) faces[i, ...] = face return faces # # Task #1: Face Identification on picture with names # def _fetch_lfw_people(data_folder_path, slice_=None, color=False, resize=None, min_faces_per_person=0): """Perform the actual data loading for the lfw people dataset This operation is meant to be cached by a joblib wrapper. """ # scan the data folder content to retain people with more that # `min_faces_per_person` face pictures person_names, file_paths = [], [] for person_name in sorted(listdir(data_folder_path)): folder_path = join(data_folder_path, person_name) if not isdir(folder_path): continue paths = [join(folder_path, f) for f in listdir(folder_path)] n_pictures = len(paths) if n_pictures >= min_faces_per_person: person_name = person_name.replace('_', ' ') person_names.extend([person_name] * n_pictures) file_paths.extend(paths) n_faces = len(file_paths) if n_faces == 0: raise ValueError("min_faces_per_person=%d is too restrictive" % min_faces_per_person) target_names = np.unique(person_names) target = np.searchsorted(target_names, person_names) faces = _load_imgs(file_paths, slice_, color, resize) # shuffle the faces with a deterministic RNG scheme to avoid having # all faces of the same person in a row, as it would break some # cross validation and learning algorithms such as SGD and online # k-means that make an IID assumption indices = np.arange(n_faces) np.random.RandomState(42).shuffle(indices) faces, target = faces[indices], target[indices] return faces, target, target_names def fetch_lfw_people(data_home=None, funneled=True, resize=0.5, min_faces_per_person=None, color=False, slice_=(slice(70, 195), slice(78, 172)), download_if_missing=True): """Loader for the Labeled Faces in the Wild (LFW) people dataset This dataset is a collection of JPEG pictures of famous people collected on the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. Each pixel of each channel (color in RGB) is encoded by a float in range 0.0 - 1.0. The task is called Face Recognition (or Identification): given the picture of a face, find the name of the person given a training set (gallery). Parameters ---------- data_home: optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. funneled: boolean, optional, default: True Download and use the funneled variant of the dataset. resize: float, optional, default 0.5 Ratio used to resize the each face picture. min_faces_per_person: int, optional, default None The extracted dataset will only retain pictures of people that have at least `min_faces_per_person` different pictures. color: boolean, optional, default False Keep the 3 RGB channels instead of averaging them to a single gray level channel. If color is True the shape of the data has one more dimension than than the shape with color = False. slice_: optional Provide a custom 2D slice (height, width) to extract the 'interesting' part of the jpeg files and avoid use statistical correlation from the background download_if_missing: optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. """ lfw_home, data_folder_path = check_fetch_lfw( data_home=data_home, funneled=funneled, download_if_missing=download_if_missing) logger.info('Loading LFW people faces from %s', lfw_home) # wrap the loader in a memoizing function that will return memmaped data # arrays for optimal memory usage m = Memory(cachedir=lfw_home, compress=6, verbose=0) load_func = m.cache(_fetch_lfw_people) # load and memoize the pairs as np arrays faces, target, target_names = load_func( data_folder_path, resize=resize, min_faces_per_person=min_faces_per_person, color=color, slice_=slice_) # pack the results as a Bunch instance return Bunch(data=faces.reshape(len(faces), -1), images=faces, target=target, target_names=target_names, DESCR="LFW faces dataset") # # Task #2: Face Verification on pairs of face pictures # def _fetch_lfw_pairs(index_file_path, data_folder_path, slice_=None, color=False, resize=None): """Perform the actual data loading for the LFW pairs dataset This operation is meant to be cached by a joblib wrapper. """ # parse the index file to find the number of pairs to be able to allocate # the right amount of memory before starting to decode the jpeg files with open(index_file_path, 'rb') as index_file: split_lines = [ln.strip().split('\t') for ln in index_file] pair_specs = [sl for sl in split_lines if len(sl) > 2] n_pairs = len(pair_specs) # interating over the metadata lines for each pair to find the filename to # decode and load in memory target = np.zeros(n_pairs, dtype=np.int) file_paths = list() for i, components in enumerate(pair_specs): if len(components) == 3: target[i] = 1 pair = ( (components[0], int(components[1]) - 1), (components[0], int(components[2]) - 1), ) elif len(components) == 4: target[i] = 0 pair = ( (components[0], int(components[1]) - 1), (components[2], int(components[3]) - 1), ) else: raise ValueError("invalid line %d: %r" % (i + 1, components)) for j, (name, idx) in enumerate(pair): person_folder = join(data_folder_path, name) filenames = list(sorted(listdir(person_folder))) file_path = join(person_folder, filenames[idx]) file_paths.append(file_path) pairs = _load_imgs(file_paths, slice_, color, resize) shape = list(pairs.shape) n_faces = shape.pop(0) shape.insert(0, 2) shape.insert(0, n_faces // 2) pairs.shape = shape return pairs, target, np.array(['Different persons', 'Same person']) def load_lfw_people(download_if_missing=False, **kwargs): """Alias for fetch_lfw_people(download_if_missing=False) Check fetch_lfw_people.__doc__ for the documentation and parameter list. """ return fetch_lfw_people(download_if_missing=download_if_missing, **kwargs) def fetch_lfw_pairs(subset='train', data_home=None, funneled=True, resize=0.5, color=False, slice_=(slice(70, 195), slice(78, 172)), download_if_missing=True): """Loader for the Labeled Faces in the Wild (LFW) pairs dataset This dataset is a collection of JPEG pictures of famous people collected on the internet, all details are available on the official website: http://vis-www.cs.umass.edu/lfw/ Each picture is centered on a single face. Each pixel of each channel (color in RGB) is encoded by a float in range 0.0 - 1.0. The task is called Face Verification: given a pair of two pictures, a binary classifier must predict whether the two images are from the same person. In the official `README.txt`_ this task is described as the "Restricted" task. As I am not sure as to implement the "Unrestricted" variant correctly, I left it as unsupported for now. .. _`README.txt`: http://vis-www.cs.umass.edu/lfw/README.txt Parameters ---------- subset: optional, default: 'train' Select the dataset to load: 'train' for the development training set, 'test' for the development test set, and '10_folds' for the official evaluation set that is meant to be used with a 10-folds cross validation. data_home: optional, default: None Specify another download and cache folder for the datasets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. funneled: boolean, optional, default: True Download and use the funneled variant of the dataset. resize: float, optional, default 0.5 Ratio used to resize the each face picture. color: boolean, optional, default False Keep the 3 RGB channels instead of averaging them to a single gray level channel. If color is True the shape of the data has one more dimension than than the shape with color = False. slice_: optional Provide a custom 2D slice (height, width) to extract the 'interesting' part of the jpeg files and avoid use statistical correlation from the background download_if_missing: optional, True by default If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. """ lfw_home, data_folder_path = check_fetch_lfw( data_home=data_home, funneled=funneled, download_if_missing=download_if_missing) logger.info('Loading %s LFW pairs from %s', subset, lfw_home) # wrap the loader in a memoizing function that will return memmaped data # arrays for optimal memory usage m = Memory(cachedir=lfw_home, compress=6, verbose=0) load_func = m.cache(_fetch_lfw_pairs) # select the right metadata file according to the requested subset label_filenames = { 'train': 'pairsDevTrain.txt', 'test': 'pairsDevTest.txt', '10_folds': 'pairs.txt', } if subset not in label_filenames: raise ValueError("subset='%s' is invalid: should be one of %r" % ( subset, list(sorted(label_filenames.keys())))) index_file_path = join(lfw_home, label_filenames[subset]) # load and memoize the pairs as np arrays pairs, target, target_names = load_func( index_file_path, data_folder_path, resize=resize, color=color, slice_=slice_) # pack the results as a Bunch instance return Bunch(data=pairs.reshape(len(pairs), -1), pairs=pairs, target=target, target_names=target_names, DESCR="'%s' segment of the LFW pairs dataset" % subset) def load_lfw_pairs(download_if_missing=False, **kwargs): """Alias for fetch_lfw_pairs(download_if_missing=False) Check fetch_lfw_pairs.__doc__ for the documentation and parameter list. """ return fetch_lfw_pairs(download_if_missing=download_if_missing, **kwargs)
bsd-3-clause
Tong-Chen/scikit-learn
examples/svm/plot_separating_hyperplane.py
12
1252
""" ========================================= SVM: Maximum margin separating hyperplane ========================================= Plot the maximum margin separating hyperplane within a two-class separable dataset using a Support Vector Machines classifier with linear kernel. """ print(__doc__) import numpy as np import pylab as pl from sklearn import svm # we create 40 separable points np.random.seed(0) X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]] Y = [0] * 20 + [1] * 20 # fit the model clf = svm.SVC(kernel='linear') clf.fit(X, Y) # get the separating hyperplane w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - (clf.intercept_[0]) / w[1] # plot the parallels to the separating hyperplane that pass through the # support vectors b = clf.support_vectors_[0] yy_down = a * xx + (b[1] - a * b[0]) b = clf.support_vectors_[-1] yy_up = a * xx + (b[1] - a * b[0]) # plot the line, the points, and the nearest vectors to the plane pl.plot(xx, yy, 'k-') pl.plot(xx, yy_down, 'k--') pl.plot(xx, yy_up, 'k--') pl.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors='none') pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) pl.axis('tight') pl.show()
bsd-3-clause
RomainBrault/scikit-learn
sklearn/grid_search.py
5
40816
""" The :mod:`sklearn.grid_search` includes utilities to fine-tune the parameters of an estimator. """ from __future__ import print_function # Author: Alexandre Gramfort <[email protected]>, # Gael Varoquaux <[email protected]> # Andreas Mueller <[email protected]> # Olivier Grisel <[email protected]> # License: BSD 3 clause from abc import ABCMeta, abstractmethod from collections import Mapping, namedtuple, Sized from functools import partial, reduce from itertools import product import operator import warnings import numpy as np from .base import BaseEstimator, is_classifier, clone from .base import MetaEstimatorMixin from .cross_validation import check_cv from .cross_validation import _fit_and_score from .externals.joblib import Parallel, delayed from .externals import six from .utils import check_random_state from .utils.random import sample_without_replacement from .utils.validation import _num_samples, indexable from .utils.metaestimators import if_delegate_has_method from .metrics.scorer import check_scoring from .exceptions import ChangedBehaviorWarning __all__ = ['GridSearchCV', 'ParameterGrid', 'fit_grid_point', 'ParameterSampler', 'RandomizedSearchCV'] warnings.warn("This module was deprecated in version 0.18 in favor of the " "model_selection module into which all the refactored classes " "and functions are moved. This module will be removed in 0.20.", DeprecationWarning) class ParameterGrid(object): """Grid of parameters with a discrete number of values for each. .. deprecated:: 0.18 This module will be removed in 0.20. Use :class:`sklearn.model_selection.ParameterGrid` instead. Can be used to iterate over parameter value combinations with the Python built-in function iter. Read more in the :ref:`User Guide <grid_search>`. Parameters ---------- param_grid : dict of string to sequence, or sequence of such The parameter grid to explore, as a dictionary mapping estimator parameters to sequences of allowed values. An empty dict signifies default parameters. A sequence of dicts signifies a sequence of grids to search, and is useful to avoid exploring parameter combinations that make no sense or have no effect. See the examples below. Examples -------- >>> from sklearn.grid_search import ParameterGrid >>> param_grid = {'a': [1, 2], 'b': [True, False]} >>> list(ParameterGrid(param_grid)) == ( ... [{'a': 1, 'b': True}, {'a': 1, 'b': False}, ... {'a': 2, 'b': True}, {'a': 2, 'b': False}]) True >>> grid = [{'kernel': ['linear']}, {'kernel': ['rbf'], 'gamma': [1, 10]}] >>> list(ParameterGrid(grid)) == [{'kernel': 'linear'}, ... {'kernel': 'rbf', 'gamma': 1}, ... {'kernel': 'rbf', 'gamma': 10}] True >>> ParameterGrid(grid)[1] == {'kernel': 'rbf', 'gamma': 1} True See also -------- :class:`GridSearchCV`: uses ``ParameterGrid`` to perform a full parallelized parameter search. """ def __init__(self, param_grid): if isinstance(param_grid, Mapping): # wrap dictionary in a singleton list to support either dict # or list of dicts param_grid = [param_grid] self.param_grid = param_grid def __iter__(self): """Iterate over the points in the grid. Returns ------- params : iterator over dict of string to any Yields dictionaries mapping each estimator parameter to one of its allowed values. """ for p in self.param_grid: # Always sort the keys of a dictionary, for reproducibility items = sorted(p.items()) if not items: yield {} else: keys, values = zip(*items) for v in product(*values): params = dict(zip(keys, v)) yield params def __len__(self): """Number of points on the grid.""" # Product function that can handle iterables (np.product can't). product = partial(reduce, operator.mul) return sum(product(len(v) for v in p.values()) if p else 1 for p in self.param_grid) def __getitem__(self, ind): """Get the parameters that would be ``ind``th in iteration Parameters ---------- ind : int The iteration index Returns ------- params : dict of string to any Equal to list(self)[ind] """ # This is used to make discrete sampling without replacement memory # efficient. for sub_grid in self.param_grid: # XXX: could memoize information used here if not sub_grid: if ind == 0: return {} else: ind -= 1 continue # Reverse so most frequent cycling parameter comes first keys, values_lists = zip(*sorted(sub_grid.items())[::-1]) sizes = [len(v_list) for v_list in values_lists] total = np.product(sizes) if ind >= total: # Try the next grid ind -= total else: out = {} for key, v_list, n in zip(keys, values_lists, sizes): ind, offset = divmod(ind, n) out[key] = v_list[offset] return out raise IndexError('ParameterGrid index out of range') class ParameterSampler(object): """Generator on parameters sampled from given distributions. .. deprecated:: 0.18 This module will be removed in 0.20. Use :class:`sklearn.model_selection.ParameterSampler` instead. Non-deterministic iterable over random candidate combinations for hyper- parameter search. If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribution, sampling with replacement is used. It is highly recommended to use continuous distributions for continuous parameters. Note that as of SciPy 0.12, the ``scipy.stats.distributions`` do not accept a custom RNG instance and always use the singleton RNG from ``numpy.random``. Hence setting ``random_state`` will not guarantee a deterministic iteration whenever ``scipy.stats`` distributions are used to define the parameter search space. Read more in the :ref:`User Guide <grid_search>`. Parameters ---------- param_distributions : dict Dictionary where the keys are parameters and values are distributions from which a parameter is to be sampled. Distributions either have to provide a ``rvs`` function to sample from them, or can be given as a list of values, where a uniform distribution is assumed. n_iter : integer Number of parameter settings that are produced. random_state : int, RandomState instance or None, optional (default=None) Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Returns ------- params : dict of string to any **Yields** dictionaries mapping each estimator parameter to as sampled value. Examples -------- >>> from sklearn.grid_search import ParameterSampler >>> from scipy.stats.distributions import expon >>> import numpy as np >>> np.random.seed(0) >>> param_grid = {'a':[1, 2], 'b': expon()} >>> param_list = list(ParameterSampler(param_grid, n_iter=4)) >>> rounded_list = [dict((k, round(v, 6)) for (k, v) in d.items()) ... for d in param_list] >>> rounded_list == [{'b': 0.89856, 'a': 1}, ... {'b': 0.923223, 'a': 1}, ... {'b': 1.878964, 'a': 2}, ... {'b': 1.038159, 'a': 2}] True """ def __init__(self, param_distributions, n_iter, random_state=None): self.param_distributions = param_distributions self.n_iter = n_iter self.random_state = random_state def __iter__(self): # check if all distributions are given as lists # in this case we want to sample without replacement all_lists = np.all([not hasattr(v, "rvs") for v in self.param_distributions.values()]) rnd = check_random_state(self.random_state) if all_lists: # look up sampled parameter settings in parameter grid param_grid = ParameterGrid(self.param_distributions) grid_size = len(param_grid) if grid_size < self.n_iter: raise ValueError( "The total space of parameters %d is smaller " "than n_iter=%d." % (grid_size, self.n_iter) + " For exhaustive searches, use GridSearchCV.") for i in sample_without_replacement(grid_size, self.n_iter, random_state=rnd): yield param_grid[i] else: # Always sort the keys of a dictionary, for reproducibility items = sorted(self.param_distributions.items()) for _ in six.moves.range(self.n_iter): params = dict() for k, v in items: if hasattr(v, "rvs"): params[k] = v.rvs() else: params[k] = v[rnd.randint(len(v))] yield params def __len__(self): """Number of points that will be sampled.""" return self.n_iter def fit_grid_point(X, y, estimator, parameters, train, test, scorer, verbose, error_score='raise', **fit_params): """Run fit on one set of parameters. .. deprecated:: 0.18 This module will be removed in 0.20. Use :func:`sklearn.model_selection.fit_grid_point` instead. Parameters ---------- X : array-like, sparse matrix or list Input data. y : array-like or None Targets for input data. estimator : estimator object A object of that type is instantiated for each grid point. This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a ``score`` function, or ``scoring`` must be passed. parameters : dict Parameters to be set on estimator for this grid point. train : ndarray, dtype int or bool Boolean mask or indices for training set. test : ndarray, dtype int or bool Boolean mask or indices for test set. scorer : callable or None. If provided must be a scorer callable object / function with signature ``scorer(estimator, X, y)``. verbose : int Verbosity level. **fit_params : kwargs Additional parameter passed to the fit function of the estimator. error_score : 'raise' (default) or numeric Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error. Returns ------- score : float Score of this parameter setting on given training / test split. parameters : dict The parameters that have been evaluated. n_samples_test : int Number of test samples in this split. """ score, n_samples_test, _ = _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, error_score) return score, parameters, n_samples_test def _check_param_grid(param_grid): if hasattr(param_grid, 'items'): param_grid = [param_grid] for p in param_grid: for name, v in p.items(): if isinstance(v, np.ndarray) and v.ndim > 1: raise ValueError("Parameter array should be one-dimensional.") check = [isinstance(v, k) for k in (list, tuple, np.ndarray)] if True not in check: raise ValueError("Parameter values for parameter ({0}) need " "to be a sequence.".format(name)) if len(v) == 0: raise ValueError("Parameter values for parameter ({0}) need " "to be a non-empty sequence.".format(name)) class _CVScoreTuple (namedtuple('_CVScoreTuple', ('parameters', 'mean_validation_score', 'cv_validation_scores'))): # A raw namedtuple is very memory efficient as it packs the attributes # in a struct to get rid of the __dict__ of attributes in particular it # does not copy the string for the keys on each instance. # By deriving a namedtuple class just to introduce the __repr__ method we # would also reintroduce the __dict__ on the instance. By telling the # Python interpreter that this subclass uses static __slots__ instead of # dynamic attributes. Furthermore we don't need any additional slot in the # subclass so we set __slots__ to the empty tuple. __slots__ = () def __repr__(self): """Simple custom repr to summarize the main info""" return "mean: {0:.5f}, std: {1:.5f}, params: {2}".format( self.mean_validation_score, np.std(self.cv_validation_scores), self.parameters) class BaseSearchCV(six.with_metaclass(ABCMeta, BaseEstimator, MetaEstimatorMixin)): """Base class for hyper parameter search with cross-validation.""" @abstractmethod def __init__(self, estimator, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score='raise'): self.scoring = scoring self.estimator = estimator self.n_jobs = n_jobs self.fit_params = fit_params if fit_params is not None else {} self.iid = iid self.refit = refit self.cv = cv self.verbose = verbose self.pre_dispatch = pre_dispatch self.error_score = error_score @property def _estimator_type(self): return self.estimator._estimator_type @property def classes_(self): return self.best_estimator_.classes_ def score(self, X, y=None): """Returns the score on the given data, if the estimator has been refit. This uses the score defined by ``scoring`` where provided, and the ``best_estimator_.score`` method otherwise. Parameters ---------- X : array-like, shape = [n_samples, n_features] Input data, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] or [n_samples, n_output], optional Target relative to X for classification or regression; None for unsupervised learning. Returns ------- score : float Notes ----- * The long-standing behavior of this method changed in version 0.16. * It no longer uses the metric provided by ``estimator.score`` if the ``scoring`` parameter was set when fitting. """ if self.scorer_ is None: raise ValueError("No score function explicitly defined, " "and the estimator doesn't provide one %s" % self.best_estimator_) if self.scoring is not None and hasattr(self.best_estimator_, 'score'): warnings.warn("The long-standing behavior to use the estimator's " "score function in {0}.score has changed. The " "scoring parameter is now used." "".format(self.__class__.__name__), ChangedBehaviorWarning) return self.scorer_(self.best_estimator_, X, y) @if_delegate_has_method(delegate=('best_estimator_', 'estimator')) def predict(self, X): """Call predict on the estimator with the best found parameters. Only available if ``refit=True`` and the underlying estimator supports ``predict``. Parameters ----------- X : indexable, length n_samples Must fulfill the input assumptions of the underlying estimator. """ return self.best_estimator_.predict(X) @if_delegate_has_method(delegate=('best_estimator_', 'estimator')) def predict_proba(self, X): """Call predict_proba on the estimator with the best found parameters. Only available if ``refit=True`` and the underlying estimator supports ``predict_proba``. Parameters ----------- X : indexable, length n_samples Must fulfill the input assumptions of the underlying estimator. """ return self.best_estimator_.predict_proba(X) @if_delegate_has_method(delegate=('best_estimator_', 'estimator')) def predict_log_proba(self, X): """Call predict_log_proba on the estimator with the best found parameters. Only available if ``refit=True`` and the underlying estimator supports ``predict_log_proba``. Parameters ----------- X : indexable, length n_samples Must fulfill the input assumptions of the underlying estimator. """ return self.best_estimator_.predict_log_proba(X) @if_delegate_has_method(delegate=('best_estimator_', 'estimator')) def decision_function(self, X): """Call decision_function on the estimator with the best found parameters. Only available if ``refit=True`` and the underlying estimator supports ``decision_function``. Parameters ----------- X : indexable, length n_samples Must fulfill the input assumptions of the underlying estimator. """ return self.best_estimator_.decision_function(X) @if_delegate_has_method(delegate=('best_estimator_', 'estimator')) def transform(self, X): """Call transform on the estimator with the best found parameters. Only available if the underlying estimator supports ``transform`` and ``refit=True``. Parameters ----------- X : indexable, length n_samples Must fulfill the input assumptions of the underlying estimator. """ return self.best_estimator_.transform(X) @if_delegate_has_method(delegate=('best_estimator_', 'estimator')) def inverse_transform(self, Xt): """Call inverse_transform on the estimator with the best found parameters. Only available if the underlying estimator implements ``inverse_transform`` and ``refit=True``. Parameters ----------- Xt : indexable, length n_samples Must fulfill the input assumptions of the underlying estimator. """ return self.best_estimator_.inverse_transform(Xt) def _fit(self, X, y, parameter_iterable): """Actual fitting, performing the search over parameters.""" estimator = self.estimator cv = self.cv self.scorer_ = check_scoring(self.estimator, scoring=self.scoring) n_samples = _num_samples(X) X, y = indexable(X, y) if y is not None: if len(y) != n_samples: raise ValueError('Target variable (y) has a different number ' 'of samples (%i) than data (X: %i samples)' % (len(y), n_samples)) cv = check_cv(cv, X, y, classifier=is_classifier(estimator)) if self.verbose > 0: if isinstance(parameter_iterable, Sized): n_candidates = len(parameter_iterable) print("Fitting {0} folds for each of {1} candidates, totalling" " {2} fits".format(len(cv), n_candidates, n_candidates * len(cv))) base_estimator = clone(self.estimator) pre_dispatch = self.pre_dispatch out = Parallel( n_jobs=self.n_jobs, verbose=self.verbose, pre_dispatch=pre_dispatch )( delayed(_fit_and_score)(clone(base_estimator), X, y, self.scorer_, train, test, self.verbose, parameters, self.fit_params, return_parameters=True, error_score=self.error_score) for parameters in parameter_iterable for train, test in cv) # Out is a list of triplet: score, estimator, n_test_samples n_fits = len(out) n_folds = len(cv) scores = list() grid_scores = list() for grid_start in range(0, n_fits, n_folds): n_test_samples = 0 score = 0 all_scores = [] for this_score, this_n_test_samples, _, parameters in \ out[grid_start:grid_start + n_folds]: all_scores.append(this_score) if self.iid: this_score *= this_n_test_samples n_test_samples += this_n_test_samples score += this_score if self.iid: score /= float(n_test_samples) else: score /= float(n_folds) scores.append((score, parameters)) # TODO: shall we also store the test_fold_sizes? grid_scores.append(_CVScoreTuple( parameters, score, np.array(all_scores))) # Store the computed scores self.grid_scores_ = grid_scores # Find the best parameters by comparing on the mean validation score: # note that `sorted` is deterministic in the way it breaks ties best = sorted(grid_scores, key=lambda x: x.mean_validation_score, reverse=True)[0] self.best_params_ = best.parameters self.best_score_ = best.mean_validation_score if self.refit: # fit the best estimator using the entire dataset # clone first to work around broken estimators best_estimator = clone(base_estimator).set_params( **best.parameters) if y is not None: best_estimator.fit(X, y, **self.fit_params) else: best_estimator.fit(X, **self.fit_params) self.best_estimator_ = best_estimator return self class GridSearchCV(BaseSearchCV): """Exhaustive search over specified parameter values for an estimator. .. deprecated:: 0.18 This module will be removed in 0.20. Use :class:`sklearn.model_selection.GridSearchCV` instead. Important members are fit, predict. GridSearchCV implements a "fit" and a "score" method. It also implements "predict", "predict_proba", "decision_function", "transform" and "inverse_transform" if they are implemented in the estimator used. The parameters of the estimator used to apply these methods are optimized by cross-validated grid-search over a parameter grid. Read more in the :ref:`User Guide <grid_search>`. Parameters ---------- estimator : estimator object. A object of that type is instantiated for each grid point. This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a ``score`` function, or ``scoring`` must be passed. param_grid : dict or list of dictionaries Dictionary with parameters names (string) as keys and lists of parameter settings to try as values, or a list of such dictionaries, in which case the grids spanned by each dictionary in the list are explored. This enables searching over any sequence of parameter settings. scoring : string, callable or None, default=None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. If ``None``, the ``score`` method of the estimator is used. fit_params : dict, optional Parameters to pass to the fit method. n_jobs: int, default: 1 : The maximum number of estimators fit in parallel. - If -1 all CPUs are used. - If 1 is given, no parallel computing code is used at all, which is useful for debugging. - For ``n_jobs`` below -1, ``(n_cpus + n_jobs + 1)`` are used. For example, with ``n_jobs = -2`` all CPUs but one are used. .. versionchanged:: 0.17 Upgraded to joblib 0.9.3. pre_dispatch : int, or string, optional Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A string, giving an expression as a function of n_jobs, as in '2*n_jobs' iid : boolean, default=True If True, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds. cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - An object to be used as a cross-validation generator. - An iterable yielding train/test splits. For integer/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`sklearn.model_selection.StratifiedKFold` is used. In all other cases, :class:`sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. refit : boolean, default=True Refit the best estimator with the entire dataset. If "False", it is impossible to make predictions using this GridSearchCV instance after fitting. verbose : integer Controls the verbosity: the higher, the more messages. error_score : 'raise' (default) or numeric Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error. Examples -------- >>> from sklearn import svm, grid_search, datasets >>> iris = datasets.load_iris() >>> parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]} >>> svr = svm.SVC() >>> clf = grid_search.GridSearchCV(svr, parameters) >>> clf.fit(iris.data, iris.target) ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS GridSearchCV(cv=None, error_score=..., estimator=SVC(C=1.0, cache_size=..., class_weight=..., coef0=..., decision_function_shape='ovr', degree=..., gamma=..., kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=..., verbose=False), fit_params={}, iid=..., n_jobs=1, param_grid=..., pre_dispatch=..., refit=..., scoring=..., verbose=...) Attributes ---------- grid_scores_ : list of named tuples Contains scores for all parameter combinations in param_grid. Each entry corresponds to one parameter setting. Each named tuple has the attributes: * ``parameters``, a dict of parameter settings * ``mean_validation_score``, the mean score over the cross-validation folds * ``cv_validation_scores``, the list of scores for each fold best_estimator_ : estimator Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False. best_score_ : float Score of best_estimator on the left out data. best_params_ : dict Parameter setting that gave the best results on the hold out data. scorer_ : function Scorer function used on the held out data to choose the best parameters for the model. Notes ------ The parameters selected are those that maximize the score of the left out data, unless an explicit score is passed in which case it is used instead. If `n_jobs` was set to a value higher than one, the data is copied for each point in the grid (and not `n_jobs` times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set `pre_dispatch`. Then, the memory is copied only `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 * n_jobs`. See Also --------- :class:`ParameterGrid`: generates all the combinations of a hyperparameter grid. :func:`sklearn.cross_validation.train_test_split`: utility function to split the data into a development set usable for fitting a GridSearchCV instance and an evaluation set for its final evaluation. :func:`sklearn.metrics.make_scorer`: Make a scorer from a performance metric or loss function. """ def __init__(self, estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', error_score='raise'): super(GridSearchCV, self).__init__( estimator, scoring, fit_params, n_jobs, iid, refit, cv, verbose, pre_dispatch, error_score) self.param_grid = param_grid _check_param_grid(param_grid) def fit(self, X, y=None): """Run fit with all sets of parameters. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] or [n_samples, n_output], optional Target relative to X for classification or regression; None for unsupervised learning. """ return self._fit(X, y, ParameterGrid(self.param_grid)) class RandomizedSearchCV(BaseSearchCV): """Randomized search on hyper parameters. .. deprecated:: 0.18 This module will be removed in 0.20. Use :class:`sklearn.model_selection.RandomizedSearchCV` instead. RandomizedSearchCV implements a "fit" and a "score" method. It also implements "predict", "predict_proba", "decision_function", "transform" and "inverse_transform" if they are implemented in the estimator used. The parameters of the estimator used to apply these methods are optimized by cross-validated search over parameter settings. In contrast to GridSearchCV, not all parameter values are tried out, but rather a fixed number of parameter settings is sampled from the specified distributions. The number of parameter settings that are tried is given by n_iter. If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribution, sampling with replacement is used. It is highly recommended to use continuous distributions for continuous parameters. Read more in the :ref:`User Guide <randomized_parameter_search>`. Parameters ---------- estimator : estimator object. A object of that type is instantiated for each grid point. This is assumed to implement the scikit-learn estimator interface. Either estimator needs to provide a ``score`` function, or ``scoring`` must be passed. param_distributions : dict Dictionary with parameters names (string) as keys and distributions or lists of parameters to try. Distributions must provide a ``rvs`` method for sampling (such as those from scipy.stats.distributions). If a list is given, it is sampled uniformly. n_iter : int, default=10 Number of parameter settings that are sampled. n_iter trades off runtime vs quality of the solution. scoring : string, callable or None, default=None A string (see model evaluation documentation) or a scorer callable object / function with signature ``scorer(estimator, X, y)``. If ``None``, the ``score`` method of the estimator is used. fit_params : dict, optional Parameters to pass to the fit method. n_jobs: int, default: 1 : The maximum number of estimators fit in parallel. - If -1 all CPUs are used. - If 1 is given, no parallel computing code is used at all, which is useful for debugging. - For ``n_jobs`` below -1, ``(n_cpus + n_jobs + 1)`` are used. For example, with ``n_jobs = -2`` all CPUs but one are used. pre_dispatch : int, or string, optional Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A string, giving an expression as a function of n_jobs, as in '2*n_jobs' iid : boolean, default=True If True, the data is assumed to be identically distributed across the folds, and the loss minimized is the total loss per sample, and not the mean loss across the folds. cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - An object to be used as a cross-validation generator. - An iterable yielding train/test splits. For integer/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`sklearn.model_selection.StratifiedKFold` is used. In all other cases, :class:`sklearn.model_selection.KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. refit : boolean, default=True Refit the best estimator with the entire dataset. If "False", it is impossible to make predictions using this RandomizedSearchCV instance after fitting. verbose : integer Controls the verbosity: the higher, the more messages. random_state : int, RandomState instance or None, optional, default=None Pseudo random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. error_score : 'raise' (default) or numeric Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. This parameter does not affect the refit step, which will always raise the error. Attributes ---------- grid_scores_ : list of named tuples Contains scores for all parameter combinations in param_grid. Each entry corresponds to one parameter setting. Each named tuple has the attributes: * ``parameters``, a dict of parameter settings * ``mean_validation_score``, the mean score over the cross-validation folds * ``cv_validation_scores``, the list of scores for each fold best_estimator_ : estimator Estimator that was chosen by the search, i.e. estimator which gave highest score (or smallest loss if specified) on the left out data. Not available if refit=False. best_score_ : float Score of best_estimator on the left out data. best_params_ : dict Parameter setting that gave the best results on the hold out data. Notes ----- The parameters selected are those that maximize the score of the held-out data, according to the scoring parameter. If `n_jobs` was set to a value higher than one, the data is copied for each parameter setting(and not `n_jobs` times). This is done for efficiency reasons if individual jobs take very little time, but may raise errors if the dataset is large and not enough memory is available. A workaround in this case is to set `pre_dispatch`. Then, the memory is copied only `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 * n_jobs`. See Also -------- :class:`GridSearchCV`: Does exhaustive search over a grid of parameters. :class:`ParameterSampler`: A generator over parameter settings, constructed from param_distributions. """ def __init__(self, estimator, param_distributions, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*n_jobs', random_state=None, error_score='raise'): self.param_distributions = param_distributions self.n_iter = n_iter self.random_state = random_state super(RandomizedSearchCV, self).__init__( estimator=estimator, scoring=scoring, fit_params=fit_params, n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose, pre_dispatch=pre_dispatch, error_score=error_score) def fit(self, X, y=None): """Run fit on the estimator with randomly drawn parameters. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vector, where n_samples in the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] or [n_samples, n_output], optional Target relative to X for classification or regression; None for unsupervised learning. """ sampled_params = ParameterSampler(self.param_distributions, self.n_iter, random_state=self.random_state) return self._fit(X, y, sampled_params)
bsd-3-clause
abhitopia/tensorflow
tensorflow/contrib/learn/python/learn/estimators/__init__.py
17
12228
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """An estimator is a rule for calculating an estimate of a given quantity. # Estimators * **Estimators** are used to train and evaluate TensorFlow models. They support regression and classification problems. * **Classifiers** are functions that have discrete outcomes. * **Regressors** are functions that predict continuous values. ## Choosing the correct estimator * For **Regression** problems use one of the following: * `LinearRegressor`: Uses linear model. * `DNNRegressor`: Uses DNN. * `DNNLinearCombinedRegressor`: Uses Wide & Deep. * `TensorForestEstimator`: Uses RandomForest. See tf.contrib.tensor_forest.client.random_forest.TensorForestEstimator. * `Estimator`: Use when you need a custom model. * For **Classification** problems use one of the following: * `LinearClassifier`: Multiclass classifier using Linear model. * `DNNClassifier`: Multiclass classifier using DNN. * `DNNLinearCombinedClassifier`: Multiclass classifier using Wide & Deep. * `TensorForestEstimator`: Uses RandomForest. See tf.contrib.tensor_forest.client.random_forest.TensorForestEstimator. * `SVM`: Binary classifier using linear SVMs. * `LogisticRegressor`: Use when you need custom model for binary classification. * `Estimator`: Use when you need custom model for N class classification. ## Pre-canned Estimators Pre-canned estimators are machine learning estimators premade for general purpose problems. If you need more customization, you can always write your own custom estimator as described in the section below. Pre-canned estimators are tested and optimized for speed and quality. ### Define the feature columns Here are some possible types of feature columns used as inputs to a pre-canned estimator. Feature columns may vary based on the estimator used. So you can see which feature columns are fed to each estimator in the below section. ```python sparse_feature_a = sparse_column_with_keys( column_name="sparse_feature_a", keys=["AB", "CD", ...]) embedding_feature_a = embedding_column( sparse_id_column=sparse_feature_a, dimension=3, combiner="sum") sparse_feature_b = sparse_column_with_hash_bucket( column_name="sparse_feature_b", hash_bucket_size=1000) embedding_feature_b = embedding_column( sparse_id_column=sparse_feature_b, dimension=16, combiner="sum") crossed_feature_a_x_b = crossed_column( columns=[sparse_feature_a, sparse_feature_b], hash_bucket_size=10000) real_feature = real_valued_column("real_feature") real_feature_buckets = bucketized_column( source_column=real_feature, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]) ``` ### Create the pre-canned estimator DNNClassifier, DNNRegressor, and DNNLinearCombinedClassifier are all pretty similar to each other in how you use them. You can easily plug in an optimizer and/or regularization to those estimators. #### DNNClassifier A classifier for TensorFlow DNN models. ```python my_features = [embedding_feature_a, embedding_feature_b] estimator = DNNClassifier( feature_columns=my_features, hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### DNNRegressor A regressor for TensorFlow DNN models. ```python my_features = [embedding_feature_a, embedding_feature_b] estimator = DNNRegressor( feature_columns=my_features, hidden_units=[1024, 512, 256]) # Or estimator using the ProximalAdagradOptimizer optimizer with # regularization. estimator = DNNRegressor( feature_columns=my_features, hidden_units=[1024, 512, 256], optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### DNNLinearCombinedClassifier A classifier for TensorFlow Linear and DNN joined training models. * Wide and deep model * Multi class (2 by default) ```python my_linear_features = [crossed_feature_a_x_b] my_deep_features = [embedding_feature_a, embedding_feature_b] estimator = DNNLinearCombinedClassifier( # Common settings n_classes=n_classes, weight_column_name=weight_column_name, # Wide settings linear_feature_columns=my_linear_features, linear_optimizer=tf.train.FtrlOptimizer(...), # Deep settings dnn_feature_columns=my_deep_features, dnn_hidden_units=[1000, 500, 100], dnn_optimizer=tf.train.AdagradOptimizer(...)) ``` #### LinearClassifier Train a linear model to classify instances into one of multiple possible classes. When number of possible classes is 2, this is binary classification. ```python my_features = [sparse_feature_b, crossed_feature_a_x_b] estimator = LinearClassifier( feature_columns=my_features, optimizer=tf.train.FtrlOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) ``` #### LinearRegressor Train a linear regression model to predict a label value given observation of feature values. ```python my_features = [sparse_feature_b, crossed_feature_a_x_b] estimator = LinearRegressor( feature_columns=my_features) ``` ### LogisticRegressor Logistic regression estimator for binary classification. ```python # See tf.contrib.learn.Estimator(...) for details on model_fn structure def my_model_fn(...): pass estimator = LogisticRegressor(model_fn=my_model_fn) # Input builders def input_fn_train: pass estimator.fit(input_fn=input_fn_train) estimator.predict(x=x) ``` #### SVM - Support Vector Machine Support Vector Machine (SVM) model for binary classification. Currently only linear SVMs are supported. ```python my_features = [real_feature, sparse_feature_a] estimator = SVM( example_id_column='example_id', feature_columns=my_features, l2_regularization=10.0) ``` #### DynamicRnnEstimator An `Estimator` that uses a recurrent neural network with dynamic unrolling. ```python problem_type = ProblemType.CLASSIFICATION # or REGRESSION prediction_type = PredictionType.SINGLE_VALUE # or MULTIPLE_VALUE estimator = DynamicRnnEstimator(problem_type, prediction_type, my_feature_columns) ``` ### Use the estimator There are two main functions for using estimators, one of which is for training, and one of which is for evaluation. You can specify different data sources for each one in order to use different datasets for train and eval. ```python # Input builders def input_fn_train: # returns x, Y ... estimator.fit(input_fn=input_fn_train) def input_fn_eval: # returns x, Y ... estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) ``` ## Creating Custom Estimator To create a custom `Estimator`, provide a function to `Estimator`'s constructor that builds your model (`model_fn`, below): ```python estimator = tf.contrib.learn.Estimator( model_fn=model_fn, model_dir=model_dir) # Where the model's data (e.g., checkpoints) # are saved. ``` Here is a skeleton of this function, with descriptions of its arguments and return values in the accompanying tables: ```python def model_fn(features, targets, mode, params): # Logic to do the following: # 1. Configure the model via TensorFlow operations # 2. Define the loss function for training/evaluation # 3. Define the training operation/optimizer # 4. Generate predictions return predictions, loss, train_op ``` You may use `mode` and check against `tf.contrib.learn.ModeKeys.{TRAIN, EVAL, INFER}` to parameterize `model_fn`. In the Further Reading section below, there is an end-to-end TensorFlow tutorial for building a custom estimator. ## Additional Estimators There is an additional estimators under `tensorflow.contrib.factorization.python.ops`: * Gaussian mixture model (GMM) clustering ## Further reading For further reading, there are several tutorials with relevant topics, including: * [Overview of linear models](../../../tutorials/linear/overview.md) * [Linear model tutorial](../../../tutorials/wide/index.md) * [Wide and deep learning tutorial](../../../tutorials/wide_and_deep/index.md) * [Custom estimator tutorial](../../../tutorials/estimators/index.md) * [Building input functions](../../../tutorials/input_fn/index.md) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators._sklearn import NotFittedError from tensorflow.contrib.learn.python.learn.estimators.constants import ProblemType from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNClassifier from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNEstimator from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNRegressor from tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined import DNNLinearCombinedClassifier from tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined import DNNLinearCombinedEstimator from tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined import DNNLinearCombinedRegressor from tensorflow.contrib.learn.python.learn.estimators.dynamic_rnn_estimator import DynamicRnnEstimator from tensorflow.contrib.learn.python.learn.estimators.estimator import BaseEstimator from tensorflow.contrib.learn.python.learn.estimators.estimator import Estimator from tensorflow.contrib.learn.python.learn.estimators.estimator import infer_real_valued_columns_from_input from tensorflow.contrib.learn.python.learn.estimators.estimator import infer_real_valued_columns_from_input_fn from tensorflow.contrib.learn.python.learn.estimators.estimator import SKCompat from tensorflow.contrib.learn.python.learn.estimators.head import binary_svm_head from tensorflow.contrib.learn.python.learn.estimators.head import Head from tensorflow.contrib.learn.python.learn.estimators.head import multi_class_head from tensorflow.contrib.learn.python.learn.estimators.head import multi_head from tensorflow.contrib.learn.python.learn.estimators.head import multi_label_head from tensorflow.contrib.learn.python.learn.estimators.head import no_op_train_fn from tensorflow.contrib.learn.python.learn.estimators.head import poisson_regression_head from tensorflow.contrib.learn.python.learn.estimators.head import regression_head from tensorflow.contrib.learn.python.learn.estimators.kmeans import KMeansClustering from tensorflow.contrib.learn.python.learn.estimators.linear import LinearClassifier from tensorflow.contrib.learn.python.learn.estimators.linear import LinearEstimator from tensorflow.contrib.learn.python.learn.estimators.linear import LinearRegressor from tensorflow.contrib.learn.python.learn.estimators.logistic_regressor import LogisticRegressor from tensorflow.contrib.learn.python.learn.estimators.metric_key import MetricKey from tensorflow.contrib.learn.python.learn.estimators.model_fn import ModeKeys from tensorflow.contrib.learn.python.learn.estimators.model_fn import ModelFnOps from tensorflow.contrib.learn.python.learn.estimators.prediction_key import PredictionKey from tensorflow.contrib.learn.python.learn.estimators.run_config import ClusterConfig from tensorflow.contrib.learn.python.learn.estimators.run_config import Environment from tensorflow.contrib.learn.python.learn.estimators.run_config import RunConfig from tensorflow.contrib.learn.python.learn.estimators.run_config import TaskType from tensorflow.contrib.learn.python.learn.estimators.svm import SVM
apache-2.0
ankurankan/scikit-learn
examples/linear_model/plot_sgd_penalties.py
249
1563
""" ============== SGD: Penalties ============== Plot the contours of the three penalties. All of the above are supported by :class:`sklearn.linear_model.stochastic_gradient`. """ from __future__ import division print(__doc__) import numpy as np import matplotlib.pyplot as plt def l1(xs): return np.array([np.sqrt((1 - np.sqrt(x ** 2.0)) ** 2.0) for x in xs]) def l2(xs): return np.array([np.sqrt(1.0 - x ** 2.0) for x in xs]) def el(xs, z): return np.array([(2 - 2 * x - 2 * z + 4 * x * z - (4 * z ** 2 - 8 * x * z ** 2 + 8 * x ** 2 * z ** 2 - 16 * x ** 2 * z ** 3 + 8 * x * z ** 3 + 4 * x ** 2 * z ** 4) ** (1. / 2) - 2 * x * z ** 2) / (2 - 4 * z) for x in xs]) def cross(ext): plt.plot([-ext, ext], [0, 0], "k-") plt.plot([0, 0], [-ext, ext], "k-") xs = np.linspace(0, 1, 100) alpha = 0.501 # 0.5 division throuh zero cross(1.2) plt.plot(xs, l1(xs), "r-", label="L1") plt.plot(xs, -1.0 * l1(xs), "r-") plt.plot(-1 * xs, l1(xs), "r-") plt.plot(-1 * xs, -1.0 * l1(xs), "r-") plt.plot(xs, l2(xs), "b-", label="L2") plt.plot(xs, -1.0 * l2(xs), "b-") plt.plot(-1 * xs, l2(xs), "b-") plt.plot(-1 * xs, -1.0 * l2(xs), "b-") plt.plot(xs, el(xs, alpha), "y-", label="Elastic Net") plt.plot(xs, -1.0 * el(xs, alpha), "y-") plt.plot(-1 * xs, el(xs, alpha), "y-") plt.plot(-1 * xs, -1.0 * el(xs, alpha), "y-") plt.xlabel(r"$w_0$") plt.ylabel(r"$w_1$") plt.legend() plt.axis("equal") plt.show()
bsd-3-clause
hrjn/scikit-learn
examples/covariance/plot_lw_vs_oas.py
159
2951
""" ============================= Ledoit-Wolf vs OAS estimation ============================= The usual covariance maximum likelihood estimate can be regularized using shrinkage. Ledoit and Wolf proposed a close formula to compute the asymptotically optimal shrinkage parameter (minimizing a MSE criterion), yielding the Ledoit-Wolf covariance estimate. Chen et al. proposed an improvement of the Ledoit-Wolf shrinkage parameter, the OAS coefficient, whose convergence is significantly better under the assumption that the data are Gaussian. This example, inspired from Chen's publication [1], shows a comparison of the estimated MSE of the LW and OAS methods, using Gaussian distributed data. [1] "Shrinkage Algorithms for MMSE Covariance Estimation" Chen et al., IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from scipy.linalg import toeplitz, cholesky from sklearn.covariance import LedoitWolf, OAS np.random.seed(0) ############################################################################### n_features = 100 # simulation covariance matrix (AR(1) process) r = 0.1 real_cov = toeplitz(r ** np.arange(n_features)) coloring_matrix = cholesky(real_cov) n_samples_range = np.arange(6, 31, 1) repeat = 100 lw_mse = np.zeros((n_samples_range.size, repeat)) oa_mse = np.zeros((n_samples_range.size, repeat)) lw_shrinkage = np.zeros((n_samples_range.size, repeat)) oa_shrinkage = np.zeros((n_samples_range.size, repeat)) for i, n_samples in enumerate(n_samples_range): for j in range(repeat): X = np.dot( np.random.normal(size=(n_samples, n_features)), coloring_matrix.T) lw = LedoitWolf(store_precision=False, assume_centered=True) lw.fit(X) lw_mse[i, j] = lw.error_norm(real_cov, scaling=False) lw_shrinkage[i, j] = lw.shrinkage_ oa = OAS(store_precision=False, assume_centered=True) oa.fit(X) oa_mse[i, j] = oa.error_norm(real_cov, scaling=False) oa_shrinkage[i, j] = oa.shrinkage_ # plot MSE plt.subplot(2, 1, 1) plt.errorbar(n_samples_range, lw_mse.mean(1), yerr=lw_mse.std(1), label='Ledoit-Wolf', color='navy', lw=2) plt.errorbar(n_samples_range, oa_mse.mean(1), yerr=oa_mse.std(1), label='OAS', color='darkorange', lw=2) plt.ylabel("Squared error") plt.legend(loc="upper right") plt.title("Comparison of covariance estimators") plt.xlim(5, 31) # plot shrinkage coefficient plt.subplot(2, 1, 2) plt.errorbar(n_samples_range, lw_shrinkage.mean(1), yerr=lw_shrinkage.std(1), label='Ledoit-Wolf', color='navy', lw=2) plt.errorbar(n_samples_range, oa_shrinkage.mean(1), yerr=oa_shrinkage.std(1), label='OAS', color='darkorange', lw=2) plt.xlabel("n_samples") plt.ylabel("Shrinkage") plt.legend(loc="lower right") plt.ylim(plt.ylim()[0], 1. + (plt.ylim()[1] - plt.ylim()[0]) / 10.) plt.xlim(5, 31) plt.show()
bsd-3-clause
ahoyosid/scikit-learn
sklearn/decomposition/__init__.py
99
1331
""" The :mod:`sklearn.decomposition` module includes matrix decomposition algorithms, including among others PCA, NMF or ICA. Most of the algorithms of this module can be regarded as dimensionality reduction techniques. """ from .nmf import NMF, ProjectedGradientNMF from .pca import PCA, RandomizedPCA from .incremental_pca import IncrementalPCA from .kernel_pca import KernelPCA from .sparse_pca import SparsePCA, MiniBatchSparsePCA from .truncated_svd import TruncatedSVD from .fastica_ import FastICA, fastica from .dict_learning import (dict_learning, dict_learning_online, sparse_encode, DictionaryLearning, MiniBatchDictionaryLearning, SparseCoder) from .factor_analysis import FactorAnalysis from ..utils.extmath import randomized_svd __all__ = ['DictionaryLearning', 'FastICA', 'IncrementalPCA', 'KernelPCA', 'MiniBatchDictionaryLearning', 'MiniBatchSparsePCA', 'NMF', 'PCA', 'ProjectedGradientNMF', 'RandomizedPCA', 'SparseCoder', 'SparsePCA', 'dict_learning', 'dict_learning_online', 'fastica', 'randomized_svd', 'sparse_encode', 'FactorAnalysis', 'TruncatedSVD']
bsd-3-clause
ahoyosid/scikit-learn
sklearn/__check_build/__init__.py
345
1671
""" Module to give helpful messages to the user that did not compile the scikit properly. """ import os INPLACE_MSG = """ It appears that you are importing a local scikit-learn source tree. For this, you need to have an inplace install. Maybe you are in the source directory and you need to try from another location.""" STANDARD_MSG = """ If you have used an installer, please check that it is suited for your Python version, your operating system and your platform.""" def raise_build_error(e): # Raise a comprehensible error and list the contents of the # directory to help debugging on the mailing list. local_dir = os.path.split(__file__)[0] msg = STANDARD_MSG if local_dir == "sklearn/__check_build": # Picking up the local install: this will work only if the # install is an 'inplace build' msg = INPLACE_MSG dir_content = list() for i, filename in enumerate(os.listdir(local_dir)): if ((i + 1) % 3): dir_content.append(filename.ljust(26)) else: dir_content.append(filename + '\n') raise ImportError("""%s ___________________________________________________________________________ Contents of %s: %s ___________________________________________________________________________ It seems that scikit-learn has not been built correctly. If you have installed scikit-learn from source, please do not forget to build the package before using it: run `python setup.py install` or `make` in the source directory. %s""" % (e, local_dir, ''.join(dir_content).strip(), msg)) try: from ._check_build import check_build except ImportError as e: raise_build_error(e)
bsd-3-clause
ryfeus/lambda-packs
LightGBM_sklearn_scipy_numpy/source/sklearn/ensemble/__init__.py
153
1382
""" The :mod:`sklearn.ensemble` module includes ensemble-based methods for classification, regression and anomaly detection. """ from .base import BaseEnsemble from .forest import RandomForestClassifier from .forest import RandomForestRegressor from .forest import RandomTreesEmbedding from .forest import ExtraTreesClassifier from .forest import ExtraTreesRegressor from .bagging import BaggingClassifier from .bagging import BaggingRegressor from .iforest import IsolationForest from .weight_boosting import AdaBoostClassifier from .weight_boosting import AdaBoostRegressor from .gradient_boosting import GradientBoostingClassifier from .gradient_boosting import GradientBoostingRegressor from .voting_classifier import VotingClassifier from . import bagging from . import forest from . import weight_boosting from . import gradient_boosting from . import partial_dependence __all__ = ["BaseEnsemble", "RandomForestClassifier", "RandomForestRegressor", "RandomTreesEmbedding", "ExtraTreesClassifier", "ExtraTreesRegressor", "BaggingClassifier", "BaggingRegressor", "IsolationForest", "GradientBoostingClassifier", "GradientBoostingRegressor", "AdaBoostClassifier", "AdaBoostRegressor", "VotingClassifier", "bagging", "forest", "gradient_boosting", "partial_dependence", "weight_boosting"]
mit
tillraab/thunderfish
setup.py
3
2124
from setuptools import setup, find_packages exec(open('thunderfish/version.py').read()) long_description = """ # ThunderFish Algorithms and programs for analysing electric field recordings of weakly electric fish. [Documentation](https://bendalab.github.io/thunderfish) | [API Reference](https://bendalab.github.io/thunderfish/api) Weakly electric fish generate an electric organ discharge (EOD). In wave-type fish the EOD resembles a sinewave of a specific frequency and with higher harmonics. In pulse-type fish EODs have a distinct waveform and are separated in time. The thunderfish package provides algorithms and tools for analysing both wavefish and pulsefish EODs. """ setup( name = 'thunderfish', version = __version__, author = 'Jan Benda, Juan F. Sehuanes, Till Raab, Jörg Henninger, Jan Grewe, Fabian Sinz, Liz Weerdmeester', author_email = "[email protected]", description = 'Algorithms and scripts for analyzing recordings of electric fish waveforms.', long_description = long_description, long_description_content_type = "text/markdown", url = "https://github.com/bendalab/thunderfish", license = "GPLv3", classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Science/Research", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Natural Language :: English", "Programming Language :: Python :: 3", "Operating System :: OS Independent", "Topic :: Scientific/Engineering", "Topic :: Software Development :: Libraries :: Python Modules", ], packages = find_packages(exclude = ['contrib', 'docs', 'tests*']), entry_points = { 'console_scripts': [ 'thunderfish = thunderfish.thunderfish:main', 'fishfinder = thunderfish.fishfinder:main', 'collectfish = thunderfish.collectfish:main', 'eodexplorer = thunderfish.eodexplorer:main', ]}, python_requires = '>=3.4', install_requires = ['sklearn', 'scipy', 'numpy', 'matplotlib', 'audioio'], )
gpl-3.0
mhdella/scikit-learn
sklearn/tests/test_kernel_ridge.py
342
3027
import numpy as np import scipy.sparse as sp from sklearn.datasets import make_regression from sklearn.linear_model import Ridge from sklearn.kernel_ridge import KernelRidge from sklearn.metrics.pairwise import pairwise_kernels from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_array_almost_equal X, y = make_regression(n_features=10) Xcsr = sp.csr_matrix(X) Xcsc = sp.csc_matrix(X) Y = np.array([y, y]).T def test_kernel_ridge(): pred = Ridge(alpha=1, fit_intercept=False).fit(X, y).predict(X) pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X) assert_array_almost_equal(pred, pred2) def test_kernel_ridge_csr(): pred = Ridge(alpha=1, fit_intercept=False, solver="cholesky").fit(Xcsr, y).predict(Xcsr) pred2 = KernelRidge(kernel="linear", alpha=1).fit(Xcsr, y).predict(Xcsr) assert_array_almost_equal(pred, pred2) def test_kernel_ridge_csc(): pred = Ridge(alpha=1, fit_intercept=False, solver="cholesky").fit(Xcsc, y).predict(Xcsc) pred2 = KernelRidge(kernel="linear", alpha=1).fit(Xcsc, y).predict(Xcsc) assert_array_almost_equal(pred, pred2) def test_kernel_ridge_singular_kernel(): # alpha=0 causes a LinAlgError in computing the dual coefficients, # which causes a fallback to a lstsq solver. This is tested here. pred = Ridge(alpha=0, fit_intercept=False).fit(X, y).predict(X) kr = KernelRidge(kernel="linear", alpha=0) ignore_warnings(kr.fit)(X, y) pred2 = kr.predict(X) assert_array_almost_equal(pred, pred2) def test_kernel_ridge_precomputed(): for kernel in ["linear", "rbf", "poly", "cosine"]: K = pairwise_kernels(X, X, metric=kernel) pred = KernelRidge(kernel=kernel).fit(X, y).predict(X) pred2 = KernelRidge(kernel="precomputed").fit(K, y).predict(K) assert_array_almost_equal(pred, pred2) def test_kernel_ridge_precomputed_kernel_unchanged(): K = np.dot(X, X.T) K2 = K.copy() KernelRidge(kernel="precomputed").fit(K, y) assert_array_almost_equal(K, K2) def test_kernel_ridge_sample_weights(): K = np.dot(X, X.T) # precomputed kernel sw = np.random.RandomState(0).rand(X.shape[0]) pred = Ridge(alpha=1, fit_intercept=False).fit(X, y, sample_weight=sw).predict(X) pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, y, sample_weight=sw).predict(X) pred3 = KernelRidge(kernel="precomputed", alpha=1).fit(K, y, sample_weight=sw).predict(K) assert_array_almost_equal(pred, pred2) assert_array_almost_equal(pred, pred3) def test_kernel_ridge_multi_output(): pred = Ridge(alpha=1, fit_intercept=False).fit(X, Y).predict(X) pred2 = KernelRidge(kernel="linear", alpha=1).fit(X, Y).predict(X) assert_array_almost_equal(pred, pred2) pred3 = KernelRidge(kernel="linear", alpha=1).fit(X, y).predict(X) pred3 = np.array([pred3, pred3]).T assert_array_almost_equal(pred2, pred3)
bsd-3-clause
drammock/mne-python
mne/conftest.py
1
23095
# -*- coding: utf-8 -*- # Author: Eric Larson <[email protected]> # # License: BSD (3-clause) from contextlib import contextmanager from distutils.version import LooseVersion import gc import os import os.path as op from pathlib import Path import shutil import sys import warnings import pytest import numpy as np import mne from mne.datasets import testing from mne.fixes import has_numba from mne.stats import cluster_level from mne.utils import _pl, _assert_no_instances, numerics test_path = testing.data_path(download=False) s_path = op.join(test_path, 'MEG', 'sample') fname_evoked = op.join(s_path, 'sample_audvis_trunc-ave.fif') fname_cov = op.join(s_path, 'sample_audvis_trunc-cov.fif') fname_fwd = op.join(s_path, 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') fname_fwd_full = op.join(s_path, 'sample_audvis_trunc-meg-eeg-oct-6-fwd.fif') bem_path = op.join(test_path, 'subjects', 'sample', 'bem') fname_bem = op.join(bem_path, 'sample-1280-bem.fif') fname_aseg = op.join(test_path, 'subjects', 'sample', 'mri', 'aseg.mgz') subjects_dir = op.join(test_path, 'subjects') fname_src = op.join(bem_path, 'sample-oct-4-src.fif') subjects_dir = op.join(test_path, 'subjects') fname_cov = op.join(s_path, 'sample_audvis_trunc-cov.fif') fname_trans = op.join(s_path, 'sample_audvis_trunc-trans.fif') collect_ignore = ['export/_eeglab.py'] def pytest_configure(config): """Configure pytest options.""" # Markers for marker in ('slowtest', 'ultraslowtest'): config.addinivalue_line('markers', marker) # Fixtures for fixture in ('matplotlib_config',): config.addinivalue_line('usefixtures', fixture) # Warnings # - Once SciPy updates not to have non-integer and non-tuple errors (1.2.0) # we should remove them from here. # - This list should also be considered alongside reset_warnings in # doc/conf.py. warning_lines = r""" error:: ignore:.*deprecated and ignored since IPython.*:DeprecationWarning ignore::ImportWarning ignore:the matrix subclass:PendingDeprecationWarning ignore:numpy.dtype size changed:RuntimeWarning ignore:.*HasTraits.trait_.*:DeprecationWarning ignore:.*takes no parameters:DeprecationWarning ignore:joblib not installed:RuntimeWarning ignore:Using a non-tuple sequence for multidimensional indexing:FutureWarning ignore:using a non-integer number instead of an integer will result in an error:DeprecationWarning ignore:Importing from numpy.testing.decorators is deprecated:DeprecationWarning ignore:np.loads is deprecated, use pickle.loads instead:DeprecationWarning ignore:The oldnumeric module will be dropped:DeprecationWarning ignore:Collection picker None could not be converted to float:UserWarning ignore:covariance is not positive-semidefinite:RuntimeWarning ignore:Can only plot ICA components:RuntimeWarning ignore:Matplotlib is building the font cache using fc-list:UserWarning ignore:Using or importing the ABCs from 'collections':DeprecationWarning ignore:`formatargspec` is deprecated:DeprecationWarning # This is only necessary until sklearn updates their wheels for NumPy 1.16 ignore:numpy.ufunc size changed:RuntimeWarning ignore:.*mne-realtime.*:DeprecationWarning ignore:.*imp.*:DeprecationWarning ignore:Exception creating Regex for oneOf.*:SyntaxWarning ignore:scipy\.gradient is deprecated.*:DeprecationWarning ignore:sklearn\.externals\.joblib is deprecated.*:FutureWarning ignore:The sklearn.*module.*deprecated.*:FutureWarning ignore:.*trait.*handler.*deprecated.*:DeprecationWarning ignore:.*rich_compare.*metadata.*deprecated.*:DeprecationWarning ignore:.*In future, it will be an error for 'np.bool_'.*:DeprecationWarning ignore:.*`np.bool` is a deprecated alias.*:DeprecationWarning ignore:.*`np.int` is a deprecated alias.*:DeprecationWarning ignore:.*`np.float` is a deprecated alias.*:DeprecationWarning ignore:.*`np.object` is a deprecated alias.*:DeprecationWarning ignore:.*`np.long` is a deprecated alias:DeprecationWarning ignore:.*Converting `np\.character` to a dtype is deprecated.*:DeprecationWarning ignore:.*sphinx\.util\.smartypants is deprecated.*: ignore:.*pandas\.util\.testing is deprecated.*: ignore:.*tostring.*is deprecated.*:DeprecationWarning ignore:.*QDesktopWidget\.availableGeometry.*:DeprecationWarning ignore:Unable to enable faulthandler.*:UserWarning ignore:Fetchers from the nilearn.*:FutureWarning ignore:SelectableGroups dict interface is deprecated\. Use select\.:DeprecationWarning ignore:Call to deprecated class vtk.*:DeprecationWarning ignore:Call to deprecated method.*Deprecated since.*:DeprecationWarning always:.*get_data.* is deprecated in favor of.*:DeprecationWarning always::ResourceWarning """ # noqa: E501 for warning_line in warning_lines.split('\n'): warning_line = warning_line.strip() if warning_line and not warning_line.startswith('#'): config.addinivalue_line('filterwarnings', warning_line) # Have to be careful with autouse=True, but this is just an int comparison # so it shouldn't really add appreciable overhead @pytest.fixture(autouse=True) def check_verbose(request): """Set to the default logging level to ensure it's tested properly.""" starting_level = mne.utils.logger.level yield # ensures that no tests break the global state try: assert mne.utils.logger.level == starting_level except AssertionError: pytest.fail('.'.join([request.module.__name__, request.function.__name__]) + ' modifies logger.level') @pytest.fixture(autouse=True) def close_all(): """Close all matplotlib plots, regardless of test status.""" # This adds < 1 µS in local testing, and we have ~2500 tests, so ~2 ms max import matplotlib.pyplot as plt yield plt.close('all') @pytest.fixture(autouse=True) def add_mne(doctest_namespace): """Add mne to the namespace.""" doctest_namespace["mne"] = mne @pytest.fixture(scope='function') def verbose_debug(): """Run a test with debug verbosity.""" with mne.utils.use_log_level('debug'): yield @pytest.fixture(scope='session') def matplotlib_config(): """Configure matplotlib for viz tests.""" import matplotlib from matplotlib import cbook # Allow for easy interactive debugging with a call like: # # $ MNE_MPL_TESTING_BACKEND=Qt5Agg pytest mne/viz/tests/test_raw.py -k annotation -x --pdb # noqa: E501 # try: want = os.environ['MNE_MPL_TESTING_BACKEND'] except KeyError: want = 'agg' # don't pop up windows with warnings.catch_warnings(record=True): # ignore warning warnings.filterwarnings('ignore') matplotlib.use(want, force=True) import matplotlib.pyplot as plt assert plt.get_backend() == want # overwrite some params that can horribly slow down tests that # users might have changed locally (but should not otherwise affect # functionality) plt.ioff() plt.rcParams['figure.dpi'] = 100 try: from traits.etsconfig.api import ETSConfig except Exception: pass else: ETSConfig.toolkit = 'qt4' # Make sure that we always reraise exceptions in handlers orig = cbook.CallbackRegistry class CallbackRegistryReraise(orig): def __init__(self, exception_handler=None): args = () if LooseVersion(matplotlib.__version__) >= LooseVersion('2.1'): args += (exception_handler,) super(CallbackRegistryReraise, self).__init__(*args) cbook.CallbackRegistry = CallbackRegistryReraise @pytest.fixture(scope='session') def ci_macos(): """Determine if running on MacOS CI.""" return (os.getenv('CI', 'false').lower() == 'true' and sys.platform == 'darwin') @pytest.fixture(scope='session') def azure_windows(): """Determine if running on Azure Windows.""" return (os.getenv('AZURE_CI_WINDOWS', 'false').lower() == 'true' and sys.platform.startswith('win')) @pytest.fixture() def check_gui_ci(ci_macos, azure_windows): """Skip tests that are not reliable on CIs.""" if azure_windows or ci_macos: pytest.skip('Skipping GUI tests on MacOS CIs and Azure Windows') @pytest.fixture(scope='session', params=[testing._pytest_param()]) def _evoked(): # This one is session scoped, so be sure not to modify it (use evoked # instead) evoked = mne.read_evokeds(fname_evoked, condition='Left Auditory', baseline=(None, 0)) evoked.crop(0, 0.2) return evoked @pytest.fixture() def evoked(_evoked): """Get evoked data.""" return _evoked.copy() @pytest.fixture(scope='function', params=[testing._pytest_param()]) def noise_cov(): """Get a noise cov from the testing dataset.""" return mne.read_cov(fname_cov) @pytest.fixture(scope='function') def bias_params_free(evoked, noise_cov): """Provide inputs for free bias functions.""" fwd = mne.read_forward_solution(fname_fwd) return _bias_params(evoked, noise_cov, fwd) @pytest.fixture(scope='function') def bias_params_fixed(evoked, noise_cov): """Provide inputs for fixed bias functions.""" fwd = mne.read_forward_solution(fname_fwd) mne.convert_forward_solution( fwd, force_fixed=True, surf_ori=True, copy=False) return _bias_params(evoked, noise_cov, fwd) def _bias_params(evoked, noise_cov, fwd): evoked.pick_types(meg=True, eeg=True, exclude=()) # restrict to limited set of verts (small src here) and one hemi for speed vertices = [fwd['src'][0]['vertno'].copy(), []] stc = mne.SourceEstimate( np.zeros((sum(len(v) for v in vertices), 1)), vertices, 0, 1) fwd = mne.forward.restrict_forward_to_stc(fwd, stc) assert fwd['sol']['row_names'] == noise_cov['names'] assert noise_cov['names'] == evoked.ch_names evoked = mne.EvokedArray(fwd['sol']['data'].copy(), evoked.info) data_cov = noise_cov.copy() data = fwd['sol']['data'] @ fwd['sol']['data'].T data *= 1e-14 # 100 nAm at each source, effectively (1e-18 would be 1 nAm) # This is rank-deficient, so let's make it actually positive semidefinite # by regularizing a tiny bit data.flat[::data.shape[0] + 1] += mne.make_ad_hoc_cov(evoked.info)['data'] # Do our projection proj, _, _ = mne.io.proj.make_projector( data_cov['projs'], data_cov['names']) data = proj @ data @ proj.T data_cov['data'][:] = data assert data_cov['data'].shape[0] == len(noise_cov['names']) want = np.arange(fwd['sol']['data'].shape[1]) if not mne.forward.is_fixed_orient(fwd): want //= 3 return evoked, fwd, noise_cov, data_cov, want @pytest.fixture def garbage_collect(): """Garbage collect on exit.""" yield gc.collect() @pytest.fixture(params=["mayavi", "pyvista"]) def renderer(request, garbage_collect): """Yield the 3D backends.""" with _use_backend(request.param, interactive=False) as renderer: yield renderer @pytest.fixture(params=["pyvista"]) def renderer_pyvista(request, garbage_collect): """Yield the PyVista backend.""" with _use_backend(request.param, interactive=False) as renderer: yield renderer @pytest.fixture(params=["notebook"]) def renderer_notebook(request): """Yield the 3D notebook renderer.""" with _use_backend(request.param, interactive=False) as renderer: yield renderer @pytest.fixture(scope="module", params=["pyvista"]) def renderer_interactive_pyvista(request): """Yield the interactive PyVista backend.""" with _use_backend(request.param, interactive=True) as renderer: yield renderer @pytest.fixture(scope="module", params=["pyvista", "mayavi"]) def renderer_interactive(request): """Yield the interactive 3D backends.""" with _use_backend(request.param, interactive=True) as renderer: if renderer._get_3d_backend() == 'mayavi': with warnings.catch_warnings(record=True): try: from surfer import Brain # noqa: 401 analysis:ignore except Exception: pytest.skip('Requires PySurfer') yield renderer @contextmanager def _use_backend(backend_name, interactive): from mne.viz.backends.renderer import _use_test_3d_backend _check_skip_backend(backend_name) with _use_test_3d_backend(backend_name, interactive=interactive): from mne.viz.backends import renderer try: yield renderer finally: renderer.backend._close_all() def _check_skip_backend(name): from mne.viz.backends.tests._utils import (has_mayavi, has_pyvista, has_pyqt5, has_imageio_ffmpeg) check_pyvista = name in ('pyvista', 'notebook') check_pyqt5 = name in ('mayavi', 'pyvista') if name == 'mayavi': if not has_mayavi(): pytest.skip("Test skipped, requires mayavi.") elif name == 'pyvista': if not has_imageio_ffmpeg(): pytest.skip("Test skipped, requires imageio-ffmpeg") if check_pyvista and not has_pyvista(): pytest.skip("Test skipped, requires pyvista.") if check_pyqt5 and not has_pyqt5(): pytest.skip("Test skipped, requires PyQt5.") @pytest.fixture(scope='session') def pixel_ratio(): """Get the pixel ratio.""" from mne.viz.backends.tests._utils import (has_mayavi, has_pyvista, has_pyqt5) if not (has_mayavi() or has_pyvista()) or not has_pyqt5(): return 1. from PyQt5.QtWidgets import QApplication, QMainWindow _ = QApplication.instance() or QApplication([]) window = QMainWindow() ratio = float(window.devicePixelRatio()) window.close() return ratio @pytest.fixture(scope='function', params=[testing._pytest_param()]) def subjects_dir_tmp(tmpdir): """Copy MNE-testing-data subjects_dir to a temp dir for manipulation.""" for key in ('sample', 'fsaverage'): shutil.copytree(op.join(subjects_dir, key), str(tmpdir.join(key))) return str(tmpdir) # Scoping these as session will make things faster, but need to make sure # not to modify them in-place in the tests, so keep them private @pytest.fixture(scope='session', params=[testing._pytest_param()]) def _evoked_cov_sphere(_evoked): """Compute a small evoked/cov/sphere combo for use with forwards.""" evoked = _evoked.copy().pick_types(meg=True) evoked.pick_channels(evoked.ch_names[::4]) assert len(evoked.ch_names) == 77 cov = mne.read_cov(fname_cov) sphere = mne.make_sphere_model('auto', 'auto', evoked.info) return evoked, cov, sphere @pytest.fixture(scope='session') def _fwd_surf(_evoked_cov_sphere): """Compute a forward for a surface source space.""" evoked, cov, sphere = _evoked_cov_sphere src_surf = mne.read_source_spaces(fname_src) return mne.make_forward_solution( evoked.info, fname_trans, src_surf, sphere, mindist=5.0) @pytest.fixture(scope='session') def _fwd_subvolume(_evoked_cov_sphere): """Compute a forward for a surface source space.""" pytest.importorskip('nibabel') evoked, cov, sphere = _evoked_cov_sphere volume_labels = ['Left-Cerebellum-Cortex', 'right-Cerebellum-Cortex'] with pytest.raises(ValueError, match=r"Did you mean one of \['Right-Cere"): mne.setup_volume_source_space( 'sample', pos=20., volume_label=volume_labels, subjects_dir=subjects_dir) volume_labels[1] = 'R' + volume_labels[1][1:] src_vol = mne.setup_volume_source_space( 'sample', pos=20., volume_label=volume_labels, subjects_dir=subjects_dir, add_interpolator=False) return mne.make_forward_solution( evoked.info, fname_trans, src_vol, sphere, mindist=5.0) @pytest.fixture(scope='session') def _all_src_types_fwd(_fwd_surf, _fwd_subvolume): """Create all three forward types (surf, vol, mixed).""" fwds = dict(surface=_fwd_surf, volume=_fwd_subvolume) with pytest.raises(RuntimeError, match='Invalid source space with kinds'): fwds['volume']['src'] + fwds['surface']['src'] # mixed (4) fwd = fwds['surface'].copy() f2 = fwds['volume'] for keys, axis in [(('source_rr',), 0), (('source_nn',), 0), (('sol', 'data'), 1), (('_orig_sol',), 1)]: a, b = fwd, f2 key = keys[0] if len(keys) > 1: a, b = a[key], b[key] key = keys[1] a[key] = np.concatenate([a[key], b[key]], axis=axis) fwd['sol']['ncol'] = fwd['sol']['data'].shape[1] fwd['nsource'] = fwd['sol']['ncol'] // 3 fwd['src'] = fwd['src'] + f2['src'] fwds['mixed'] = fwd return fwds @pytest.fixture(scope='session') def _all_src_types_inv_evoked(_evoked_cov_sphere, _all_src_types_fwd): """Compute inverses for all source types.""" evoked, cov, _ = _evoked_cov_sphere invs = dict() for kind, fwd in _all_src_types_fwd.items(): assert fwd['src'].kind == kind with pytest.warns(RuntimeWarning, match='has magnitude'): invs[kind] = mne.minimum_norm.make_inverse_operator( evoked.info, fwd, cov) return invs, evoked @pytest.fixture(scope='function') def all_src_types_inv_evoked(_all_src_types_inv_evoked): """All source types of inverses, allowing for possible modification.""" invs, evoked = _all_src_types_inv_evoked invs = {key: val.copy() for key, val in invs.items()} evoked = evoked.copy() return invs, evoked @pytest.fixture(scope='function') def mixed_fwd_cov_evoked(_evoked_cov_sphere, _all_src_types_fwd): """Compute inverses for all source types.""" evoked, cov, _ = _evoked_cov_sphere return _all_src_types_fwd['mixed'].copy(), cov.copy(), evoked.copy() @pytest.fixture(scope='session') @pytest.mark.slowtest @pytest.mark.parametrize(params=[testing._pytest_param()]) def src_volume_labels(): """Create a 7mm source space with labels.""" pytest.importorskip('nibabel') volume_labels = mne.get_volume_labels_from_aseg(fname_aseg) src = mne.setup_volume_source_space( 'sample', 7., mri='aseg.mgz', volume_label=volume_labels, add_interpolator=False, bem=fname_bem, subjects_dir=subjects_dir) lut, _ = mne.read_freesurfer_lut() assert len(volume_labels) == 46 assert volume_labels[0] == 'Unknown' assert lut['Unknown'] == 0 # it will be excluded during label gen return src, tuple(volume_labels), lut def _fail(*args, **kwargs): raise AssertionError('Test should not download') @pytest.fixture(scope='function') def download_is_error(monkeypatch): """Prevent downloading by raising an error when it's attempted.""" monkeypatch.setattr(mne.utils.fetching, '_get_http', _fail) @pytest.fixture() def brain_gc(request): """Ensure that brain can be properly garbage collected.""" keys = ( 'renderer_interactive', 'renderer_interactive_pyvista', 'renderer_interactive_pysurfer', 'renderer', 'renderer_pyvista', 'renderer_notebook', ) assert set(request.fixturenames) & set(keys) != set() for key in keys: if key in request.fixturenames: is_pv = request.getfixturevalue(key)._get_3d_backend() == 'pyvista' close_func = request.getfixturevalue(key).backend._close_all break if not is_pv: yield return import pyvista if LooseVersion(pyvista.__version__) <= LooseVersion('0.26.1'): yield return from mne.viz import Brain ignore = set(id(o) for o in gc.get_objects()) yield close_func() # no need to warn if the test itself failed, pytest-harvest helps us here try: outcome = request.node.harvest_rep_call except Exception: outcome = 'failed' if outcome != 'passed': return _assert_no_instances(Brain, 'after') # We only check VTK for PyVista -- Mayavi/PySurfer is not as strict objs = gc.get_objects() bad = list() for o in objs: try: name = o.__class__.__name__ except Exception: # old Python, probably pass else: if name.startswith('vtk') and id(o) not in ignore: bad.append(name) del o del objs, ignore, Brain assert len(bad) == 0, 'VTK objects linger:\n' + '\n'.join(bad) def pytest_sessionfinish(session, exitstatus): """Handle the end of the session.""" n = session.config.option.durations if n is None: return print('\n') try: import pytest_harvest except ImportError: print('Module-level timings require pytest-harvest') return from py.io import TerminalWriter # get the number to print res = pytest_harvest.get_session_synthesis_dct(session) files = dict() for key, val in res.items(): parts = Path(key.split(':')[0]).parts # split mne/tests/test_whatever.py into separate categories since these # are essentially submodule-level tests. Keeping just [:3] works, # except for mne/viz where we want level-4 granulatity parts = parts[:4 if parts[:2] == ('mne', 'viz') else 3] if not parts[-1].endswith('.py'): parts = parts + ('',) file_key = '/'.join(parts) files[file_key] = files.get(file_key, 0) + val['pytest_duration_s'] files = sorted(list(files.items()), key=lambda x: x[1])[::-1] # print files = files[:n] if len(files): writer = TerminalWriter() writer.line() # newline writer.sep('=', f'slowest {n} test module{_pl(n)}') names, timings = zip(*files) timings = [f'{timing:0.2f}s total' for timing in timings] rjust = max(len(timing) for timing in timings) timings = [timing.rjust(rjust) for timing in timings] for name, timing in zip(names, timings): writer.line(f'{timing.ljust(15)}{name}') @pytest.fixture(scope="function", params=('Numba', 'NumPy')) def numba_conditional(monkeypatch, request): """Test both code paths on machines that have Numba.""" assert request.param in ('Numba', 'NumPy') if request.param == 'NumPy' and has_numba: monkeypatch.setattr( cluster_level, '_get_buddies', cluster_level._get_buddies_fallback) monkeypatch.setattr( cluster_level, '_get_selves', cluster_level._get_selves_fallback) monkeypatch.setattr( cluster_level, '_where_first', cluster_level._where_first_fallback) monkeypatch.setattr( numerics, '_arange_div', numerics._arange_div_fallback) if request.param == 'Numba' and not has_numba: pytest.skip('Numba not installed') yield request.param
bsd-3-clause
eickenberg/scikit-learn
examples/plot_isotonic_regression.py
303
1767
""" =================== Isotonic Regression =================== An illustration of the isotonic regression on generated data. The isotonic regression finds a non-decreasing approximation of a function while minimizing the mean squared error on the training data. The benefit of such a model is that it does not assume any form for the target function such as linearity. For comparison a linear regression is also presented. """ print(__doc__) # Author: Nelle Varoquaux <[email protected]> # Alexandre Gramfort <[email protected]> # Licence: BSD import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from sklearn.linear_model import LinearRegression from sklearn.isotonic import IsotonicRegression from sklearn.utils import check_random_state n = 100 x = np.arange(n) rs = check_random_state(0) y = rs.randint(-50, 50, size=(n,)) + 50. * np.log(1 + np.arange(n)) ############################################################################### # Fit IsotonicRegression and LinearRegression models ir = IsotonicRegression() y_ = ir.fit_transform(x, y) lr = LinearRegression() lr.fit(x[:, np.newaxis], y) # x needs to be 2d for LinearRegression ############################################################################### # plot result segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)] lc = LineCollection(segments, zorder=0) lc.set_array(np.ones(len(y))) lc.set_linewidths(0.5 * np.ones(n)) fig = plt.figure() plt.plot(x, y, 'r.', markersize=12) plt.plot(x, y_, 'g.-', markersize=12) plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-') plt.gca().add_collection(lc) plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right') plt.title('Isotonic regression') plt.show()
bsd-3-clause
cysuncn/python
crawler/rent/dataAnalyse/ziroomAnalysis.py
1
13803
# -*- coding: utf-8 -*- """ Created on Mon Jul 3 12:16:17 2017 @author: zhanglu01 """ import json import pandas as pd import matplotlib.pyplot as plot import ziroomAnalysis.geohash as geohash def line_json_load(filename): with open(filename, 'r', encoding='utf-8') as f: lines = f.readlines() df = pd.DataFrame() i = 0 for line in lines: tmp_df = pd.DataFrame(json.loads(line), index=[i]) tmp_df["price"] = tmp_df["price"].astype("int") tmp_df["area"] = tmp_df["area"].astype("float") tmp_df["lng"] = tmp_df["lng"].astype("float") tmp_df["lat"] = tmp_df["lat"].astype("float") if tmp_df.iloc[0]["time_unit"] == "每天": tmp_df.price[i] = tmp_df.price[i]*30 df = df.append(tmp_df) i += 1 return df filename = 'F:/PyWorkspace/ziroomAnalysis/0729/ziroomBeijing.json' df = line_json_load(filename) df = df.drop_duplicates() df = df[(df['time_unit']!='每天') & (df['direction']!='南北') & (df['floorLoc']!='') & (df['floorTotal']!='')] #不同租赁方式的统计量 #df["price_per_m2"] = df["price"]/df["area"] groups = df.groupby(df["rentType"]) rt_count = groups.size() rt_mean = groups.mean().rename(columns={'price':'mean_price'}) rt_max = groups.max().rename(columns={'price':'max_price'}) rt_min = groups.min().rename(columns={'price':'min_price'}) rt_median = groups.median().rename(columns={'price':'median_price'}) rentTypeDf = pd.concat([rt_mean["mean_price"],pd.DataFrame(rt_count,columns=["count"]),rt_max["max_price"],rt_min["min_price"],rt_median["median_price"]],axis=1) #df[df['price']==990]["link"] ############合租分析############ #每100元为区间段统计数量 he_intervals = {100*x:0 for x in range(64)} for price in df[df['rentType']=='合']['price']: he_intervals[price//100*100] += 1 plot.bar(he_intervals.keys(), he_intervals.values(), width=100, alpha = .5, color = 'blue') plot.xlabel(u"月租(元)", fontproperties='SimHei') plot.ylabel(u"房间数量", fontproperties='SimHei') plot.show() #将经纬度转换成字符串编码,将同一个格子里的点合并,目的是减少热力图中的打点数量 geohash_dict = dict() for house in df[df['rentType']=='合'].iterrows(): geohash_code = geohash.encode(house[1]["lat"], house[1]["lng"], 6) if geohash_code in geohash_dict.keys(): geohash_dict[geohash_code] += 1 else: geohash_dict[geohash_code] = 1 #将he_position_str的值替换“房间数量热力图.html”中相应的值 he_position_str = "" for code in geohash_dict: he_position_str += '{{"lng": {0}, "lat": {1}, "count": {2}}},\n'.format(geohash.decode_exactly(code)[1],geohash.decode_exactly(code)[0],geohash_dict[code]) #将he_position_price_str的值替换“价格在地图上的分布.html”中相应的值 he_position_price_str = "" for house in df[df['rentType']=='合'].iterrows(): if house[1]["price"]<2000: he_position_price_str += '{{"lng": {0}, "lat": {1}, "count": {2}}},\n'.format(house[1]["lng"],house[1]["lat"],5) elif house[1]["price"]<3000: he_position_price_str += '{{"lng": {0}, "lat": {1}, "count": {2}}},\n'.format(house[1]["lng"],house[1]["lat"],10) else: he_position_price_str += '{{"lng": {0}, "lat": {1}, "count": {2}}},\n'.format(house[1]["lng"],house[1]["lat"],15) ############################地理位置聚类############################ from sklearn.cluster import KMeans import matplotlib.pyplot as plt #用来评估簇的个数是否合适,每个簇的样本点到这个簇的中心点的距离之和越小说明簇分的越好,选取临界点的簇个数 __clfInertia__ = [] for i in range(2,30,1): clf = KMeans(n_clusters=i) s = clf.fit(df[(df['rentType']=='合') & (df['price']>=3000)][["lng", "lat"]]) __clfInertia__.append([i, clf.inertia_]) plt.plot([x[0] for x in __clfInertia__], [x[1] for x in __clfInertia__],'b*') plt.plot([x[0] for x in __clfInertia__], [x[1] for x in __clfInertia__],'r') #调用kmeans类 clf = KMeans(n_clusters=4) s = clf.fit(df[(df['rentType']=='合') & (df['price']>=3000)][["lng", "lat"]]) print(s) #n个中心 print(clf.cluster_centers_) ############################随机森林回归############################ from math import radians,sin,cos,degrees,atan2,atan,tan,acos from sklearn.ensemble import RandomForestRegressor from sklearn.preprocessing import LabelEncoder,OneHotEncoder from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV def getDegree(latA, lngA, latB, lngB): """ Args: point p1(latA, lngA) point p2(latB, lngB) Returns: bearing between the two GPS points, default: the basis of heading direction is north """ radLatA = radians(latA) radLngA = radians(lngA) radLatB = radians(latB) radLngB = radians(lngB) dLng = radLngB - radLngA y = sin(dLng) * cos(radLatB) x = cos(radLatA) * sin(radLatB) - sin(radLatA) * cos(radLatB) * cos(dLng) brng = degrees(atan2(y, x)) brng = (brng + 360) % 360 return brng def getDistance(latA, lngA, latB, lngB): ra = 6378140 # radius of equator: meter rb = 6356755 # radius of polar: meter flatten = (ra - rb) / ra # Partial rate of the earth # change angle to radians radLatA = radians(latA) radLngA = radians(lngA) radLatB = radians(latB) radLngB = radians(lngB) pA = atan(rb / ra * tan(radLatA)) pB = atan(rb / ra * tan(radLatB)) x = acos(sin(pA) * sin(pB) + cos(pA) * cos(pB) * cos(radLngA - radLngB)) c1 = (sin(x) - x) * (sin(pA) + sin(pB))**2 / cos(x / 2)**2 c2 = (sin(x) + x) * (sin(pA) - sin(pB))**2 / sin(x / 2)**2 dr = flatten / 8 * (c1 - c2) distance = ra * (x + dr) return distance df['degree'] = df.apply(lambda row: getDegree(39.915129,116.403981,row.lat,row.lng), axis=1) df['distance'] = df.apply(lambda row: getDistance(39.915129,116.403981,row.lat,row.lng), axis=1) #df['distance1'] = df.apply(lambda row: getDistance(39.93573198,116.33882039,row.lat,row.lng), axis=1) #df['distance2'] = df.apply(lambda row: getDistance(39.9934964,116.45926247,row.lat,row.lng), axis=1) #df['distance3'] = df.apply(lambda row: getDistance(39.91515228,116.4790283,row.lat,row.lng), axis=1) #df['distance4'] = df.apply(lambda row: getDistance(40.04388111,116.35319092,row.lat,row.lng), axis=1) #df['distance5'] = df.apply(lambda row: getDistance(39.929654,116.403119,row.lat,row.lng), axis=1) rf_data = df[(df.rentType=='合') & (df.time_unit!='每天') & (df.floorLoc!='') & (df.floorTotal!='')][['area','confGen','confType','direction','floorLoc','floorTotal','nearestSubWayDist','privateBalcony','privateBathroom','rooms','halls','district','degree','distance','link','price']] rf_data = rf_data.reset_index(drop=True) #重置索引 confGenLe = LabelEncoder() rf_data['confGen']=confGenLe.fit_transform(rf_data['confGen']) list(confGenLe.classes_) confTypeLe = LabelEncoder() rf_data['confType']=confTypeLe.fit_transform(rf_data['confType']) list(confTypeLe.classes_) directionLe = LabelEncoder() rf_data['direction']=directionLe.fit_transform(rf_data['direction']) list(directionLe.classes_) districtLe = LabelEncoder() rf_data['district']=districtLe.fit_transform(rf_data['district']) list(districtLe.classes_) rf_data.nearestSubWayDist = rf_data.nearestSubWayDist.replace('','5000') #one-hot encoding def one_hot_encode(label_set,data): oneHotEnc = OneHotEncoder() oneHotEnc.fit(label_set) result=oneHotEnc.transform(data).toarray() return result oneHotEncodes = one_hot_encode( [[0,0,0,0],[1,1,1,1],[2,2,2,2],[3,3,3,3],[0,4,4,4],[0,5,5,5],[0,0,6,6],[0,0,7,7],[0,0,0,8],[0,0,0,9],[0,0,0,10],[0,0,0,11],[0,0,0,12]], rf_data[['confGen','confType','direction','district']]) #将二维list转dataframe one_hot_columns = ["confGen0", "confGen1", "confGen2", "confGen3", "confType0", "confType1", "confType2", "confType3", "confType4", "confType5", "direction0", "direction1", "direction2", "direction3", "direction4", "direction5", "direction6", "direction7", "district0", "district1", "district2", "district3", "district4", "district5", "district6", "district7", "district8", "district9", "district10", "district11", "district12"] rf_data[one_hot_columns] = pd.DataFrame(oneHotEncodes,columns=one_hot_columns) rf_data=rf_data.drop(['confGen','confType','direction','district'],axis=1) tmp_link=rf_data[['link','price']] rf_data=rf_data.drop(['link','price'],axis=1) rf_data[['link','price']]=tmp_link X_train, X_test, y_train, y_test = train_test_split(rf_data.iloc[:,0:42], rf_data.iloc[:,[42]], test_size=0.33, random_state=42) #训练模型_start #首先对n_estimators进行网格搜索 param_test1= {'n_estimators':list(range(450,550,10))} gsearch1= GridSearchCV(estimator = RandomForestRegressor(max_features="log2", min_samples_leaf=2, oob_score=True), param_grid =param_test1, scoring=None, cv=5) gsearch1.fit(X_train.iloc[:,0:18],y_train) gsearch1.grid_scores_,gsearch1.best_params_, gsearch1.best_score_ #接着对决策树最大深度max_depth和内部节点再划分所需最小样本数min_samples_split进行网格搜索。 param_test2= {'max_depth':list(range(80,100,2)), 'min_samples_split':list(range(2,101,2))} gsearch2= GridSearchCV(estimator = RandomForestRegressor(n_estimators=50, max_features="log2", min_samples_leaf=2, oob_score=True), param_grid = param_test2,scoring=None,iid=False, cv=5) gsearch2.fit(X_train.iloc[:,0:18],y_train) gsearch2.grid_scores_,gsearch2.best_params_, gsearch2.best_score_ #再对内部节点再划分所需最小样本数min_samples_split和叶子节点最少样本数min_samples_leaf一起调参 param_test3= {'min_samples_split':list(range(2,10,2)), 'min_samples_leaf':list(range(2,20,2))} gsearch3= GridSearchCV(estimator = RandomForestRegressor(n_estimators=50, max_features="log2",max_depth=96, oob_score=True), param_grid = param_test3,scoring=None,iid=False, cv=5) gsearch3.fit(X_train.iloc[:,0:18],y_train) gsearch3.grid_scores_,gsearch3.best_params_, gsearch3.best_score_ #最后再对最大特征数max_features做调参: param_test4= {'max_features':list(range(2,17,1))} gsearch4= GridSearchCV(estimator = RandomForestRegressor(n_estimators=50,max_depth=96,min_samples_split=4,min_samples_leaf=2, oob_score=True), param_grid = param_test4,scoring=None,iid=False, cv=5) gsearch4.fit(X_train.iloc[:,0:18],y_train) gsearch4.grid_scores_,gsearch4.best_params_, gsearch4.best_score_ rf_classifier = RandomForestRegressor(n_estimators=540,max_features=12,max_depth=96,min_samples_split=4,min_samples_leaf=2, oob_score=True) rf_classifier.fit(X_train.iloc[:,0:41],y_train) rf_classifier.oob_score_ #袋外分 pd.Series(rf_classifier.feature_importances_,index=X_train.columns[0:41]).sort_values(ascending=False) #特征重要性排序 #训练模型_end #模型预测_start results = rf_classifier.predict(X_test.iloc[:,0:41]).astype(int) rf_classifier.score(X_test.iloc[:,0:41],y_test) #模型准确度 pddf = pd.DataFrame({'actual':y_test.price,'predict':results,'link':X_test.link,'size':X_test.area}) pddf['diff'] = abs(pddf.predict-pddf.actual)/pddf.actual pddf_ordered = pddf.sort(columns='diff', ascending=False) #模型预测_end #############################灰色关联分析############################# he_df = df[(df['rentType']=='合') & (df.time_unit!='每天') & (df.area>8) & (df.price<2200)] #过滤超出自己心理预期的数据 he_df['co_distance'] = he_df.apply(lambda row: getDistance(39.988122,116.319725,row.lat,row.lng), axis=1) #计算到公司的距离 #指标无量纲化(离差标准化) he_feature_max = he_df[['area','price','co_distance']].max() he_feature_min = he_df[['area','price','co_distance']].min() he_df['area_nondim'] = he_df.apply(lambda row: (row.area-he_feature_min.area)/(he_feature_max.area-he_feature_min.area), axis=1) he_df['price_nondim'] = he_df.apply(lambda row: (row.price-he_feature_min.price)/(he_feature_max.price-he_feature_min.price), axis=1) he_df['co_distance_nondim'] = he_df.apply(lambda row: (row.co_distance-he_feature_min.co_distance)/(he_feature_max.co_distance-he_feature_min.co_distance), axis=1) #计算关联系数 opt_series = pd.Series([1,0,0], index=['area_nondim','price_nondim','co_distance_nondim']) #设定最优化序列 he_df['area_nondim_opt_diff'] = he_df.apply(lambda row: abs(row.area_nondim-opt_series.area_nondim), axis=1) he_df['price_nondim_opt_diff'] = he_df.apply(lambda row: abs(row.price_nondim-opt_series.price_nondim), axis=1) he_df['co_distance_nondim_opt_diff'] = he_df.apply(lambda row: abs(row.co_distance_nondim-opt_series.co_distance_nondim), axis=1) min_nondim_opt_diff = min(min(he_df['area_nondim_opt_diff']),min(he_df['price_nondim_opt_diff']),min(he_df['co_distance_nondim_opt_diff'])) max_nondim_opt_diff = max(max(he_df['area_nondim_opt_diff']),max(he_df['price_nondim_opt_diff']),max(he_df['co_distance_nondim_opt_diff'])) he_df['area_cor'] = he_df.apply(lambda row: (min_nondim_opt_diff+0.5*max_nondim_opt_diff)/(row.area_nondim_opt_diff+0.5*max_nondim_opt_diff), axis=1) he_df['price_cor'] = he_df.apply(lambda row: (min_nondim_opt_diff+0.5*max_nondim_opt_diff)/(row.price_nondim_opt_diff+0.5*max_nondim_opt_diff), axis=1) he_df['co_distance_cor'] = he_df.apply(lambda row: (min_nondim_opt_diff+0.5*max_nondim_opt_diff)/(row.co_distance_nondim_opt_diff+0.5*max_nondim_opt_diff), axis=1) he_df['room_cor_order'] = he_df['area_cor']/6+he_df['price_cor']/3+he_df['co_distance_cor']/2 he_ordered_df = he_df.sort(columns='room_cor_order', ascending=False) #房间关联系数倒排
gpl-3.0
nhuntwalker/astroML
examples/datasets/plot_sdss_galaxy_colors.py
3
1300
""" SDSS Galaxy Colors ------------------ The function :func:`fetch_sdss_galaxy_colors` used below actually queries the SDSS CASjobs server for the colors of the 50,000 galaxies. Below we extract the :math:`u - g` and :math:`g - r` colors for 5000 stars, and scatter-plot the results """ # Author: Jake VanderPlas <[email protected]> # License: BSD # The figure is an example from astroML: see http://astroML.github.com import numpy as np from matplotlib import pyplot as plt from sklearn.neighbors import KNeighborsRegressor from astroML.datasets import fetch_sdss_galaxy_colors #------------------------------------------------------------ # Download data data = fetch_sdss_galaxy_colors() data = data[::10] # truncate for plotting # Extract colors and spectral class ug = data['u'] - data['g'] gr = data['g'] - data['r'] spec_class = data['specClass'] stars = (spec_class == 2) qsos = (spec_class == 3) #------------------------------------------------------------ # Prepare plot fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlim(-0.5, 2.5) ax.set_ylim(-0.5, 1.5) ax.plot(ug[stars], gr[stars], '.', ms=4, c='b', label='stars') ax.plot(ug[qsos], gr[qsos], '.', ms=4, c='r', label='qsos') ax.legend(loc=2) ax.set_xlabel('$u-g$') ax.set_ylabel('$g-r$') plt.show()
bsd-2-clause
liberatorqjw/scikit-learn
sklearn/neighbors/regression.py
39
10464
"""Nearest Neighbor Regression""" # Authors: Jake Vanderplas <[email protected]> # Fabian Pedregosa <[email protected]> # Alexandre Gramfort <[email protected]> # Sparseness support by Lars Buitinck <[email protected]> # Multi-output support by Arnaud Joly <[email protected]> # # License: BSD 3 clause (C) INRIA, University of Amsterdam import numpy as np from .base import _get_weights, _check_weights, NeighborsBase, KNeighborsMixin from .base import RadiusNeighborsMixin, SupervisedFloatMixin from ..base import RegressorMixin from ..utils import check_array class KNeighborsRegressor(NeighborsBase, KNeighborsMixin, SupervisedFloatMixin, RegressorMixin): """Regression based on k-nearest neighbors. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Parameters ---------- n_neighbors : int, optional (default = 5) Number of neighbors to use by default for :meth:`k_neighbors` queries. weights : str or callable weight function used in prediction. Possible values: - 'uniform' : uniform weights. All points in each neighborhood are weighted equally. - 'distance' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metric : string or DistanceMetric object (default='minkowski') the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of the DistanceMetric class for a list of available metrics. p : integer, optional (default = 2) Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params: dict, optional (default = None) additional keyword arguments for the metric function. Examples -------- >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import KNeighborsRegressor >>> neigh = KNeighborsRegressor(n_neighbors=2) >>> neigh.fit(X, y) # doctest: +ELLIPSIS KNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [ 0.5] See also -------- NearestNeighbors RadiusNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes ----- See :ref:`Nearest Neighbors <neighbors>` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. .. warning:: Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor `k+1` and `k`, have identical distances but but different labels, the results will depend on the ordering of the training data. http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm """ def __init__(self, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, **kwargs): self._init_params(n_neighbors=n_neighbors, algorithm=algorithm, leaf_size=leaf_size, metric=metric, p=p, metric_params=metric_params, **kwargs) self.weights = _check_weights(weights) def predict(self, X): """Predict the target for the provided data Parameters ---------- X : array or matrix, shape = [n_samples, n_features] Returns ------- y : array of int, shape = [n_samples] or [n_samples, n_outputs] Target values """ X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.kneighbors(X) weights = _get_weights(neigh_dist, self.weights) _y = self._y if _y.ndim == 1: _y = _y.reshape((-1, 1)) if weights is None: y_pred = np.mean(_y[neigh_ind], axis=1) else: y_pred = np.empty((X.shape[0], _y.shape[1]), dtype=np.float) denom = np.sum(weights, axis=1) for j in range(_y.shape[1]): num = np.sum(_y[neigh_ind, j] * weights, axis=1) y_pred[:, j] = num / denom if self._y.ndim == 1: y_pred = y_pred.ravel() return y_pred class RadiusNeighborsRegressor(NeighborsBase, RadiusNeighborsMixin, SupervisedFloatMixin, RegressorMixin): """Regression based on neighbors within a fixed radius. The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set. Parameters ---------- radius : float, optional (default = 1.0) Range of parameter space to use by default for :meth`radius_neighbors` queries. weights : str or callable weight function used in prediction. Possible values: - 'uniform' : uniform weights. All points in each neighborhood are weighted equally. - 'distance' : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away. - [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights. Uniform weights are used by default. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, optional Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDtree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, optional (default = 30) Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metric : string or DistanceMetric object (default='minkowski') the distance metric to use for the tree. The default metric is minkowski, and with p=2 is equivalent to the standard Euclidean metric. See the documentation of the DistanceMetric class for a list of available metrics. p : integer, optional (default = 2) Power parameter for the Minkowski metric. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params: dict, optional (default = None) additional keyword arguments for the metric function. Examples -------- >>> X = [[0], [1], [2], [3]] >>> y = [0, 0, 1, 1] >>> from sklearn.neighbors import RadiusNeighborsRegressor >>> neigh = RadiusNeighborsRegressor(radius=1.0) >>> neigh.fit(X, y) # doctest: +ELLIPSIS RadiusNeighborsRegressor(...) >>> print(neigh.predict([[1.5]])) [ 0.5] See also -------- NearestNeighbors KNeighborsRegressor KNeighborsClassifier RadiusNeighborsClassifier Notes ----- See :ref:`Nearest Neighbors <neighbors>` in the online documentation for a discussion of the choice of ``algorithm`` and ``leaf_size``. http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm """ def __init__(self, radius=1.0, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, **kwargs): self._init_params(radius=radius, algorithm=algorithm, leaf_size=leaf_size, p=p, metric=metric, metric_params=metric_params, **kwargs) self.weights = _check_weights(weights) def predict(self, X): """Predict the target for the provided data Parameters ---------- X : array or matrix, shape = [n_samples, n_features] Returns ------- y : array of int, shape = [n_samples] or [n_samples, n_outputs] Target values """ X = check_array(X, accept_sparse='csr') neigh_dist, neigh_ind = self.radius_neighbors(X) weights = _get_weights(neigh_dist, self.weights) _y = self._y if _y.ndim == 1: _y = _y.reshape((-1, 1)) if weights is None: y_pred = np.array([np.mean(_y[ind, :], axis=0) for ind in neigh_ind]) else: y_pred = np.array([(np.average(_y[ind, :], axis=0, weights=weights[i])) for (i, ind) in enumerate(neigh_ind)]) if self._y.ndim == 1: y_pred = y_pred.ravel() return y_pred
bsd-3-clause
HolgerPeters/scikit-learn
examples/ensemble/plot_forest_importances_faces.py
403
1519
""" ================================================= Pixel importances with a parallel forest of trees ================================================= This example shows the use of forests of trees to evaluate the importance of the pixels in an image classification task (faces). The hotter the pixel, the more important. The code below also illustrates how the construction and the computation of the predictions can be parallelized within multiple jobs. """ print(__doc__) from time import time import matplotlib.pyplot as plt from sklearn.datasets import fetch_olivetti_faces from sklearn.ensemble import ExtraTreesClassifier # Number of cores to use to perform parallel fitting of the forest model n_jobs = 1 # Load the faces dataset data = fetch_olivetti_faces() X = data.images.reshape((len(data.images), -1)) y = data.target mask = y < 5 # Limit to 5 classes X = X[mask] y = y[mask] # Build a forest and compute the pixel importances print("Fitting ExtraTreesClassifier on faces data with %d cores..." % n_jobs) t0 = time() forest = ExtraTreesClassifier(n_estimators=1000, max_features=128, n_jobs=n_jobs, random_state=0) forest.fit(X, y) print("done in %0.3fs" % (time() - t0)) importances = forest.feature_importances_ importances = importances.reshape(data.images[0].shape) # Plot pixel importances plt.matshow(importances, cmap=plt.cm.hot) plt.title("Pixel importances with forests of trees") plt.show()
bsd-3-clause
RPGOne/Skynet
imbalanced-learn-master/examples/under-sampling/plot_cluster_centroids.py
3
1884
""" ================= Cluster centroids ================= An illustration of the cluster centroids method. """ print(__doc__) import matplotlib.pyplot as plt import seaborn as sns sns.set() # Define some color for the plotting almost_black = '#262626' palette = sns.color_palette() from sklearn.datasets import make_classification from sklearn.decomposition import PCA from imblearn.under_sampling import ClusterCentroids # Generate the dataset X, y = make_classification(n_classes=2, class_sep=2, weights=[0.1, 0.9], n_informative=3, n_redundant=1, flip_y=0, n_features=20, n_clusters_per_class=1, n_samples=5000, random_state=10) # Instanciate a PCA object for the sake of easy visualisation pca = PCA(n_components=2) # Fit and transform x to visualise inside a 2D feature space X_vis = pca.fit_transform(X) # Apply Cluster Centroids cc = ClusterCentroids() X_resampled, y_resampled = cc.fit_sample(X, y) X_res_vis = pca.transform(X_resampled) # Two subplots, unpack the axes array immediately f, (ax1, ax2) = plt.subplots(1, 2) ax1.scatter(X_vis[y == 0, 0], X_vis[y == 0, 1], label="Class #0", alpha=0.5, edgecolor=almost_black, facecolor=palette[0], linewidth=0.15) ax1.scatter(X_vis[y == 1, 0], X_vis[y == 1, 1], label="Class #1", alpha=0.5, edgecolor=almost_black, facecolor=palette[2], linewidth=0.15) ax1.set_title('Original set') ax2.scatter(X_res_vis[y_resampled == 0, 0], X_res_vis[y_resampled == 0, 1], label="Class #0", alpha=.5, edgecolor=almost_black, facecolor=palette[0], linewidth=0.15) ax2.scatter(X_res_vis[y_resampled == 1, 0], X_res_vis[y_resampled == 1, 1], label="Class #1", alpha=.5, edgecolor=almost_black, facecolor=palette[2], linewidth=0.15) ax2.set_title('Cluster centroids') plt.show()
bsd-3-clause
xavierwu/scikit-learn
examples/svm/plot_svm_scale_c.py
223
5375
""" ============================================== Scaling the regularization parameter for SVCs ============================================== The following example illustrates the effect of scaling the regularization parameter when using :ref:`svm` for :ref:`classification <svm_classification>`. For SVC classification, we are interested in a risk minimization for the equation: .. math:: C \sum_{i=1, n} \mathcal{L} (f(x_i), y_i) + \Omega (w) where - :math:`C` is used to set the amount of regularization - :math:`\mathcal{L}` is a `loss` function of our samples and our model parameters. - :math:`\Omega` is a `penalty` function of our model parameters If we consider the loss function to be the individual error per sample, then the data-fit term, or the sum of the error for each sample, will increase as we add more samples. The penalization term, however, will not increase. When using, for example, :ref:`cross validation <cross_validation>`, to set the amount of regularization with `C`, there will be a different amount of samples between the main problem and the smaller problems within the folds of the cross validation. Since our loss function is dependent on the amount of samples, the latter will influence the selected value of `C`. The question that arises is `How do we optimally adjust C to account for the different amount of training samples?` The figures below are used to illustrate the effect of scaling our `C` to compensate for the change in the number of samples, in the case of using an `l1` penalty, as well as the `l2` penalty. l1-penalty case ----------------- In the `l1` case, theory says that prediction consistency (i.e. that under given hypothesis, the estimator learned predicts as well as a model knowing the true distribution) is not possible because of the bias of the `l1`. It does say, however, that model consistency, in terms of finding the right set of non-zero parameters as well as their signs, can be achieved by scaling `C1`. l2-penalty case ----------------- The theory says that in order to achieve prediction consistency, the penalty parameter should be kept constant as the number of samples grow. Simulations ------------ The two figures below plot the values of `C` on the `x-axis` and the corresponding cross-validation scores on the `y-axis`, for several different fractions of a generated data-set. In the `l1` penalty case, the cross-validation-error correlates best with the test-error, when scaling our `C` with the number of samples, `n`, which can be seen in the first figure. For the `l2` penalty case, the best result comes from the case where `C` is not scaled. .. topic:: Note: Two separate datasets are used for the two different plots. The reason behind this is the `l1` case works better on sparse data, while `l2` is better suited to the non-sparse case. """ print(__doc__) # Author: Andreas Mueller <[email protected]> # Jaques Grobler <[email protected]> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.svm import LinearSVC from sklearn.cross_validation import ShuffleSplit from sklearn.grid_search import GridSearchCV from sklearn.utils import check_random_state from sklearn import datasets rnd = check_random_state(1) # set up dataset n_samples = 100 n_features = 300 # l1 data (only 5 informative features) X_1, y_1 = datasets.make_classification(n_samples=n_samples, n_features=n_features, n_informative=5, random_state=1) # l2 data: non sparse, but less features y_2 = np.sign(.5 - rnd.rand(n_samples)) X_2 = rnd.randn(n_samples, n_features / 5) + y_2[:, np.newaxis] X_2 += 5 * rnd.randn(n_samples, n_features / 5) clf_sets = [(LinearSVC(penalty='l1', loss='squared_hinge', dual=False, tol=1e-3), np.logspace(-2.3, -1.3, 10), X_1, y_1), (LinearSVC(penalty='l2', loss='squared_hinge', dual=True, tol=1e-4), np.logspace(-4.5, -2, 10), X_2, y_2)] colors = ['b', 'g', 'r', 'c'] for fignum, (clf, cs, X, y) in enumerate(clf_sets): # set up the plot for each regressor plt.figure(fignum, figsize=(9, 10)) for k, train_size in enumerate(np.linspace(0.3, 0.7, 3)[::-1]): param_grid = dict(C=cs) # To get nice curve, we need a large number of iterations to # reduce the variance grid = GridSearchCV(clf, refit=False, param_grid=param_grid, cv=ShuffleSplit(n=n_samples, train_size=train_size, n_iter=250, random_state=1)) grid.fit(X, y) scores = [x[1] for x in grid.grid_scores_] scales = [(1, 'No scaling'), ((n_samples * train_size), '1/n_samples'), ] for subplotnum, (scaler, name) in enumerate(scales): plt.subplot(2, 1, subplotnum + 1) plt.xlabel('C') plt.ylabel('CV Score') grid_cs = cs * float(scaler) # scale the C's plt.semilogx(grid_cs, scores, label="fraction %.2f" % train_size) plt.title('scaling=%s, penalty=%s, loss=%s' % (name, clf.penalty, clf.loss)) plt.legend(loc="best") plt.show()
bsd-3-clause
BiaDarkia/scikit-learn
examples/plot_multioutput_face_completion.py
79
2986
""" ============================================== Face completion with a multi-output estimators ============================================== This example shows the use of multi-output estimator to complete images. The goal is to predict the lower half of a face given its upper half. The first column of images shows true faces. The next columns illustrate how extremely randomized trees, k nearest neighbors, linear regression and ridge regression complete the lower half of those faces. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import fetch_olivetti_faces from sklearn.utils.validation import check_random_state from sklearn.ensemble import ExtraTreesRegressor from sklearn.neighbors import KNeighborsRegressor from sklearn.linear_model import LinearRegression from sklearn.linear_model import RidgeCV # Load the faces datasets data = fetch_olivetti_faces() targets = data.target data = data.images.reshape((len(data.images), -1)) train = data[targets < 30] test = data[targets >= 30] # Test on independent people # Test on a subset of people n_faces = 5 rng = check_random_state(4) face_ids = rng.randint(test.shape[0], size=(n_faces, )) test = test[face_ids, :] n_pixels = data.shape[1] # Upper half of the faces X_train = train[:, :(n_pixels + 1) // 2] # Lower half of the faces y_train = train[:, n_pixels // 2:] X_test = test[:, :(n_pixels + 1) // 2] y_test = test[:, n_pixels // 2:] # Fit estimators ESTIMATORS = { "Extra trees": ExtraTreesRegressor(n_estimators=10, max_features=32, random_state=0), "K-nn": KNeighborsRegressor(), "Linear regression": LinearRegression(), "Ridge": RidgeCV(), } y_test_predict = dict() for name, estimator in ESTIMATORS.items(): estimator.fit(X_train, y_train) y_test_predict[name] = estimator.predict(X_test) # Plot the completed faces image_shape = (64, 64) n_cols = 1 + len(ESTIMATORS) plt.figure(figsize=(2. * n_cols, 2.26 * n_faces)) plt.suptitle("Face completion with multi-output estimators", size=16) for i in range(n_faces): true_face = np.hstack((X_test[i], y_test[i])) if i: sub = plt.subplot(n_faces, n_cols, i * n_cols + 1) else: sub = plt.subplot(n_faces, n_cols, i * n_cols + 1, title="true faces") sub.axis("off") sub.imshow(true_face.reshape(image_shape), cmap=plt.cm.gray, interpolation="nearest") for j, est in enumerate(sorted(ESTIMATORS)): completed_face = np.hstack((X_test[i], y_test_predict[est][i])) if i: sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j) else: sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j, title=est) sub.axis("off") sub.imshow(completed_face.reshape(image_shape), cmap=plt.cm.gray, interpolation="nearest") plt.show()
bsd-3-clause
justincassidy/scikit-learn
examples/text/document_classification_20newsgroups.py
222
10500
""" ====================================================== Classification of text documents using sparse features ====================================================== This is an example showing how scikit-learn can be used to classify documents by topics using a bag-of-words approach. This example uses a scipy.sparse matrix to store the features and demonstrates various classifiers that can efficiently handle sparse matrices. The dataset used in this example is the 20 newsgroups dataset. It will be automatically downloaded, then cached. The bar plot indicates the accuracy, training time (normalized) and test time (normalized) of each classifier. """ # Author: Peter Prettenhofer <[email protected]> # Olivier Grisel <[email protected]> # Mathieu Blondel <[email protected]> # Lars Buitinck <[email protected]> # License: BSD 3 clause from __future__ import print_function import logging import numpy as np from optparse import OptionParser import sys from time import time import matplotlib.pyplot as plt from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer from sklearn.feature_selection import SelectKBest, chi2 from sklearn.linear_model import RidgeClassifier from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC from sklearn.linear_model import SGDClassifier from sklearn.linear_model import Perceptron from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.naive_bayes import BernoulliNB, MultinomialNB from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import NearestCentroid from sklearn.ensemble import RandomForestClassifier from sklearn.utils.extmath import density from sklearn import metrics # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') # parse commandline arguments op = OptionParser() op.add_option("--report", action="store_true", dest="print_report", help="Print a detailed classification report.") op.add_option("--chi2_select", action="store", type="int", dest="select_chi2", help="Select some number of features using a chi-squared test") op.add_option("--confusion_matrix", action="store_true", dest="print_cm", help="Print the confusion matrix.") op.add_option("--top10", action="store_true", dest="print_top10", help="Print ten most discriminative terms per class" " for every classifier.") op.add_option("--all_categories", action="store_true", dest="all_categories", help="Whether to use all categories or not.") op.add_option("--use_hashing", action="store_true", help="Use a hashing vectorizer.") op.add_option("--n_features", action="store", type=int, default=2 ** 16, help="n_features when using the hashing vectorizer.") op.add_option("--filtered", action="store_true", help="Remove newsgroup information that is easily overfit: " "headers, signatures, and quoting.") (opts, args) = op.parse_args() if len(args) > 0: op.error("this script takes no arguments.") sys.exit(1) print(__doc__) op.print_help() print() ############################################################################### # Load some categories from the training set if opts.all_categories: categories = None else: categories = [ 'alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space', ] if opts.filtered: remove = ('headers', 'footers', 'quotes') else: remove = () print("Loading 20 newsgroups dataset for categories:") print(categories if categories else "all") data_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42, remove=remove) data_test = fetch_20newsgroups(subset='test', categories=categories, shuffle=True, random_state=42, remove=remove) print('data loaded') categories = data_train.target_names # for case categories == None def size_mb(docs): return sum(len(s.encode('utf-8')) for s in docs) / 1e6 data_train_size_mb = size_mb(data_train.data) data_test_size_mb = size_mb(data_test.data) print("%d documents - %0.3fMB (training set)" % ( len(data_train.data), data_train_size_mb)) print("%d documents - %0.3fMB (test set)" % ( len(data_test.data), data_test_size_mb)) print("%d categories" % len(categories)) print() # split a training set and a test set y_train, y_test = data_train.target, data_test.target print("Extracting features from the training data using a sparse vectorizer") t0 = time() if opts.use_hashing: vectorizer = HashingVectorizer(stop_words='english', non_negative=True, n_features=opts.n_features) X_train = vectorizer.transform(data_train.data) else: vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english') X_train = vectorizer.fit_transform(data_train.data) duration = time() - t0 print("done in %fs at %0.3fMB/s" % (duration, data_train_size_mb / duration)) print("n_samples: %d, n_features: %d" % X_train.shape) print() print("Extracting features from the test data using the same vectorizer") t0 = time() X_test = vectorizer.transform(data_test.data) duration = time() - t0 print("done in %fs at %0.3fMB/s" % (duration, data_test_size_mb / duration)) print("n_samples: %d, n_features: %d" % X_test.shape) print() # mapping from integer feature name to original token string if opts.use_hashing: feature_names = None else: feature_names = vectorizer.get_feature_names() if opts.select_chi2: print("Extracting %d best features by a chi-squared test" % opts.select_chi2) t0 = time() ch2 = SelectKBest(chi2, k=opts.select_chi2) X_train = ch2.fit_transform(X_train, y_train) X_test = ch2.transform(X_test) if feature_names: # keep selected feature names feature_names = [feature_names[i] for i in ch2.get_support(indices=True)] print("done in %fs" % (time() - t0)) print() if feature_names: feature_names = np.asarray(feature_names) def trim(s): """Trim string to fit on terminal (assuming 80-column display)""" return s if len(s) <= 80 else s[:77] + "..." ############################################################################### # Benchmark classifiers def benchmark(clf): print('_' * 80) print("Training: ") print(clf) t0 = time() clf.fit(X_train, y_train) train_time = time() - t0 print("train time: %0.3fs" % train_time) t0 = time() pred = clf.predict(X_test) test_time = time() - t0 print("test time: %0.3fs" % test_time) score = metrics.accuracy_score(y_test, pred) print("accuracy: %0.3f" % score) if hasattr(clf, 'coef_'): print("dimensionality: %d" % clf.coef_.shape[1]) print("density: %f" % density(clf.coef_)) if opts.print_top10 and feature_names is not None: print("top 10 keywords per class:") for i, category in enumerate(categories): top10 = np.argsort(clf.coef_[i])[-10:] print(trim("%s: %s" % (category, " ".join(feature_names[top10])))) print() if opts.print_report: print("classification report:") print(metrics.classification_report(y_test, pred, target_names=categories)) if opts.print_cm: print("confusion matrix:") print(metrics.confusion_matrix(y_test, pred)) print() clf_descr = str(clf).split('(')[0] return clf_descr, score, train_time, test_time results = [] for clf, name in ( (RidgeClassifier(tol=1e-2, solver="lsqr"), "Ridge Classifier"), (Perceptron(n_iter=50), "Perceptron"), (PassiveAggressiveClassifier(n_iter=50), "Passive-Aggressive"), (KNeighborsClassifier(n_neighbors=10), "kNN"), (RandomForestClassifier(n_estimators=100), "Random forest")): print('=' * 80) print(name) results.append(benchmark(clf)) for penalty in ["l2", "l1"]: print('=' * 80) print("%s penalty" % penalty.upper()) # Train Liblinear model results.append(benchmark(LinearSVC(loss='l2', penalty=penalty, dual=False, tol=1e-3))) # Train SGD model results.append(benchmark(SGDClassifier(alpha=.0001, n_iter=50, penalty=penalty))) # Train SGD with Elastic Net penalty print('=' * 80) print("Elastic-Net penalty") results.append(benchmark(SGDClassifier(alpha=.0001, n_iter=50, penalty="elasticnet"))) # Train NearestCentroid without threshold print('=' * 80) print("NearestCentroid (aka Rocchio classifier)") results.append(benchmark(NearestCentroid())) # Train sparse Naive Bayes classifiers print('=' * 80) print("Naive Bayes") results.append(benchmark(MultinomialNB(alpha=.01))) results.append(benchmark(BernoulliNB(alpha=.01))) print('=' * 80) print("LinearSVC with L1-based feature selection") # The smaller C, the stronger the regularization. # The more regularization, the more sparsity. results.append(benchmark(Pipeline([ ('feature_selection', LinearSVC(penalty="l1", dual=False, tol=1e-3)), ('classification', LinearSVC()) ]))) # make some plots indices = np.arange(len(results)) results = [[x[i] for x in results] for i in range(4)] clf_names, score, training_time, test_time = results training_time = np.array(training_time) / np.max(training_time) test_time = np.array(test_time) / np.max(test_time) plt.figure(figsize=(12, 8)) plt.title("Score") plt.barh(indices, score, .2, label="score", color='r') plt.barh(indices + .3, training_time, .2, label="training time", color='g') plt.barh(indices + .6, test_time, .2, label="test time", color='b') plt.yticks(()) plt.legend(loc='best') plt.subplots_adjust(left=.25) plt.subplots_adjust(top=.95) plt.subplots_adjust(bottom=.05) for i, c in zip(indices, clf_names): plt.text(-.3, i, c) plt.show()
bsd-3-clause
h2educ/scikit-learn
sklearn/decomposition/tests/test_incremental_pca.py
297
8265
"""Tests for Incremental PCA.""" import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_raises from sklearn import datasets from sklearn.decomposition import PCA, IncrementalPCA iris = datasets.load_iris() def test_incremental_pca(): # Incremental PCA on dense arrays. X = iris.data batch_size = X.shape[0] // 3 ipca = IncrementalPCA(n_components=2, batch_size=batch_size) pca = PCA(n_components=2) pca.fit_transform(X) X_transformed = ipca.fit_transform(X) np.testing.assert_equal(X_transformed.shape, (X.shape[0], 2)) assert_almost_equal(ipca.explained_variance_ratio_.sum(), pca.explained_variance_ratio_.sum(), 1) for n_components in [1, 2, X.shape[1]]: ipca = IncrementalPCA(n_components, batch_size=batch_size) ipca.fit(X) cov = ipca.get_covariance() precision = ipca.get_precision() assert_array_almost_equal(np.dot(cov, precision), np.eye(X.shape[1])) def test_incremental_pca_check_projection(): # Test that the projection of data is correct. rng = np.random.RandomState(1999) n, p = 100, 3 X = rng.randn(n, p) * .1 X[:10] += np.array([3, 4, 5]) Xt = 0.1 * rng.randn(1, p) + np.array([3, 4, 5]) # Get the reconstruction of the generated data X # Note that Xt has the same "components" as X, just separated # This is what we want to ensure is recreated correctly Yt = IncrementalPCA(n_components=2).fit(X).transform(Xt) # Normalize Yt /= np.sqrt((Yt ** 2).sum()) # Make sure that the first element of Yt is ~1, this means # the reconstruction worked as expected assert_almost_equal(np.abs(Yt[0][0]), 1., 1) def test_incremental_pca_inverse(): # Test that the projection of data can be inverted. rng = np.random.RandomState(1999) n, p = 50, 3 X = rng.randn(n, p) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed # signal (since the data is almost of rank n_components) ipca = IncrementalPCA(n_components=2, batch_size=10).fit(X) Y = ipca.transform(X) Y_inverse = ipca.inverse_transform(Y) assert_almost_equal(X, Y_inverse, decimal=3) def test_incremental_pca_validation(): # Test that n_components is >=1 and <= n_features. X = [[0, 1], [1, 0]] for n_components in [-1, 0, .99, 3]: assert_raises(ValueError, IncrementalPCA(n_components, batch_size=10).fit, X) def test_incremental_pca_set_params(): # Test that components_ sign is stable over batch sizes. rng = np.random.RandomState(1999) n_samples = 100 n_features = 20 X = rng.randn(n_samples, n_features) X2 = rng.randn(n_samples, n_features) X3 = rng.randn(n_samples, n_features) ipca = IncrementalPCA(n_components=20) ipca.fit(X) # Decreasing number of components ipca.set_params(n_components=10) assert_raises(ValueError, ipca.partial_fit, X2) # Increasing number of components ipca.set_params(n_components=15) assert_raises(ValueError, ipca.partial_fit, X3) # Returning to original setting ipca.set_params(n_components=20) ipca.partial_fit(X) def test_incremental_pca_num_features_change(): # Test that changing n_components will raise an error. rng = np.random.RandomState(1999) n_samples = 100 X = rng.randn(n_samples, 20) X2 = rng.randn(n_samples, 50) ipca = IncrementalPCA(n_components=None) ipca.fit(X) assert_raises(ValueError, ipca.partial_fit, X2) def test_incremental_pca_batch_signs(): # Test that components_ sign is stable over batch sizes. rng = np.random.RandomState(1999) n_samples = 100 n_features = 3 X = rng.randn(n_samples, n_features) all_components = [] batch_sizes = np.arange(10, 20) for batch_size in batch_sizes: ipca = IncrementalPCA(n_components=None, batch_size=batch_size).fit(X) all_components.append(ipca.components_) for i, j in zip(all_components[:-1], all_components[1:]): assert_almost_equal(np.sign(i), np.sign(j), decimal=6) def test_incremental_pca_batch_values(): # Test that components_ values are stable over batch sizes. rng = np.random.RandomState(1999) n_samples = 100 n_features = 3 X = rng.randn(n_samples, n_features) all_components = [] batch_sizes = np.arange(20, 40, 3) for batch_size in batch_sizes: ipca = IncrementalPCA(n_components=None, batch_size=batch_size).fit(X) all_components.append(ipca.components_) for i, j in zip(all_components[:-1], all_components[1:]): assert_almost_equal(i, j, decimal=1) def test_incremental_pca_partial_fit(): # Test that fit and partial_fit get equivalent results. rng = np.random.RandomState(1999) n, p = 50, 3 X = rng.randn(n, p) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed # signal (since the data is almost of rank n_components) batch_size = 10 ipca = IncrementalPCA(n_components=2, batch_size=batch_size).fit(X) pipca = IncrementalPCA(n_components=2, batch_size=batch_size) # Add one to make sure endpoint is included batch_itr = np.arange(0, n + 1, batch_size) for i, j in zip(batch_itr[:-1], batch_itr[1:]): pipca.partial_fit(X[i:j, :]) assert_almost_equal(ipca.components_, pipca.components_, decimal=3) def test_incremental_pca_against_pca_iris(): # Test that IncrementalPCA and PCA are approximate (to a sign flip). X = iris.data Y_pca = PCA(n_components=2).fit_transform(X) Y_ipca = IncrementalPCA(n_components=2, batch_size=25).fit_transform(X) assert_almost_equal(np.abs(Y_pca), np.abs(Y_ipca), 1) def test_incremental_pca_against_pca_random_data(): # Test that IncrementalPCA and PCA are approximate (to a sign flip). rng = np.random.RandomState(1999) n_samples = 100 n_features = 3 X = rng.randn(n_samples, n_features) + 5 * rng.rand(1, n_features) Y_pca = PCA(n_components=3).fit_transform(X) Y_ipca = IncrementalPCA(n_components=3, batch_size=25).fit_transform(X) assert_almost_equal(np.abs(Y_pca), np.abs(Y_ipca), 1) def test_explained_variances(): # Test that PCA and IncrementalPCA calculations match X = datasets.make_low_rank_matrix(1000, 100, tail_strength=0., effective_rank=10, random_state=1999) prec = 3 n_samples, n_features = X.shape for nc in [None, 99]: pca = PCA(n_components=nc).fit(X) ipca = IncrementalPCA(n_components=nc, batch_size=100).fit(X) assert_almost_equal(pca.explained_variance_, ipca.explained_variance_, decimal=prec) assert_almost_equal(pca.explained_variance_ratio_, ipca.explained_variance_ratio_, decimal=prec) assert_almost_equal(pca.noise_variance_, ipca.noise_variance_, decimal=prec) def test_whitening(): # Test that PCA and IncrementalPCA transforms match to sign flip. X = datasets.make_low_rank_matrix(1000, 10, tail_strength=0., effective_rank=2, random_state=1999) prec = 3 n_samples, n_features = X.shape for nc in [None, 9]: pca = PCA(whiten=True, n_components=nc).fit(X) ipca = IncrementalPCA(whiten=True, n_components=nc, batch_size=250).fit(X) Xt_pca = pca.transform(X) Xt_ipca = ipca.transform(X) assert_almost_equal(np.abs(Xt_pca), np.abs(Xt_ipca), decimal=prec) Xinv_ipca = ipca.inverse_transform(Xt_ipca) Xinv_pca = pca.inverse_transform(Xt_pca) assert_almost_equal(X, Xinv_ipca, decimal=prec) assert_almost_equal(X, Xinv_pca, decimal=prec) assert_almost_equal(Xinv_pca, Xinv_ipca, decimal=prec)
bsd-3-clause
iismd17/scikit-learn
examples/feature_selection/plot_rfe_with_cross_validation.py
226
1384
""" =================================================== Recursive feature elimination with cross-validation =================================================== A recursive feature elimination example with automatic tuning of the number of features selected with cross-validation. """ print(__doc__) import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.cross_validation import StratifiedKFold from sklearn.feature_selection import RFECV from sklearn.datasets import make_classification # Build a classification task using 3 informative features X, y = make_classification(n_samples=1000, n_features=25, n_informative=3, n_redundant=2, n_repeated=0, n_classes=8, n_clusters_per_class=1, random_state=0) # Create the RFE object and compute a cross-validated score. svc = SVC(kernel="linear") # The "accuracy" scoring is proportional to the number of correct # classifications rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(y, 2), scoring='accuracy') rfecv.fit(X, y) print("Optimal number of features : %d" % rfecv.n_features_) # Plot number of features VS. cross-validation scores plt.figure() plt.xlabel("Number of features selected") plt.ylabel("Cross validation score (nb of correct classifications)") plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_) plt.show()
bsd-3-clause
JPFrancoia/scikit-learn
sklearn/semi_supervised/tests/test_label_propagation.py
44
2262
""" test the label propagation module """ import numpy as np from sklearn.utils.testing import assert_equal from sklearn.semi_supervised import label_propagation from sklearn.metrics.pairwise import rbf_kernel from numpy.testing import assert_array_almost_equal from numpy.testing import assert_array_equal ESTIMATORS = [ (label_propagation.LabelPropagation, {'kernel': 'rbf'}), (label_propagation.LabelPropagation, {'kernel': 'knn', 'n_neighbors': 2}), (label_propagation.LabelPropagation, { 'kernel': lambda x, y: rbf_kernel(x, y, gamma=20) }), (label_propagation.LabelSpreading, {'kernel': 'rbf'}), (label_propagation.LabelSpreading, {'kernel': 'knn', 'n_neighbors': 2}), (label_propagation.LabelSpreading, { 'kernel': lambda x, y: rbf_kernel(x, y, gamma=20) }), ] def test_fit_transduction(): samples = [[1., 0.], [0., 2.], [1., 3.]] labels = [0, 1, -1] for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) assert_equal(clf.transduction_[2], 1) def test_distribution(): samples = [[1., 0.], [0., 1.], [1., 1.]] labels = [0, 1, -1] for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) if parameters['kernel'] == 'knn': continue # unstable test; changes in k-NN ordering break it assert_array_almost_equal(clf.predict_proba([[1., 0.0]]), np.array([[1., 0.]]), 2) else: assert_array_almost_equal(np.asarray(clf.label_distributions_[2]), np.array([.5, .5]), 2) def test_predict(): samples = [[1., 0.], [0., 2.], [1., 3.]] labels = [0, 1, -1] for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) assert_array_equal(clf.predict([[0.5, 2.5]]), np.array([1])) def test_predict_proba(): samples = [[1., 0.], [0., 1.], [1., 2.5]] labels = [0, 1, -1] for estimator, parameters in ESTIMATORS: clf = estimator(**parameters).fit(samples, labels) assert_array_almost_equal(clf.predict_proba([[1., 1.]]), np.array([[0.5, 0.5]]))
bsd-3-clause
wgm2111/wgm-coursera
machine-learning/machine-learning-ex5/ex5/wgm-ex5.py
1
2281
""" An example script that fits the data with linear regression with a different orders of polynomial. """ # imports import scipy as sp import numpy as np import scipy.io as sio import sklearn.linear_model as linear_model import matplotlib.pyplot as plt # import data ex5_data = sio.loadmat('ex5data1.mat') # Loads the matlab/octave file as a dict # Define variables X = ex5_data['X'] y = ex5_data["y"] Xtest = ex5_data['Xtest'] ytest = ex5_data['ytest'] Xval = ex5_data['Xval'] yval = ex5_data['yval'] # Define higer order features up to polynomial 10 N = 10 X10 = np.array([X.squeeze()**n for n in range(1,N+1)]).transpose() Xtest10 = np.array([Xtest.squeeze()**n for n in range(1,N+1)]).transpose() # Define a lr model and fit for each order polynomial lr_models = [linear_model.LinearRegression(normalize=True) for n in range(N)] [lr_model.fit(X10[:,:n+1], y) for n, lr_model in zip(range(N), lr_models)] lr_models_ridgeCV = [linear_model.RidgeCV([1e-5, 1e-4, 1e-3, 1e-2, 1e-1], normalize=True) for n in range(N)] [lr_model_ridgeCV.fit(X10[:,:n+1], y) for n, lr_model_ridgeCV in zip(range(N), lr_models_ridgeCV)] # Compute the training and test errors for i, models in zip([0,1], [lr_models, lr_models_ridgeCV]): yfit_train = np.array([lr_model.predict(X10[:,:n+1]) for n, lr_model in zip(range(N), models)]) yfit_test = np.array([lr_model.predict(Xtest10[:,:n+1]) for n, lr_model in zip(range(N), models)]) # Cost functions for Npoly = sp.arange(1,11) J_train = 1 / (2.0 * yfit_train.shape[1]) * ((y - yfit_train)**2).sum(1) J_test = 1 / (2.0 * yfit_test.shape[1]) * ((ytest - yfit_test)**2).sum(1) # Make a plot if i == 0 : f0 = plt.figure(0, (5,5), facecolor='white') f0.clf() a0 = f0.add_axes([.1, .1, .85, .85]) a0.plot(Npoly, J_train, 'b', linewidth=2, label="err-train") a0.plot(Npoly, J_test, 'g', linewidth=2, label="err-test") a0.set_title("Error as a function of polynomial order") else: a0.plot(Npoly, J_train, '--b', linewidth=2, label="err-train-RidgeCV") a0.plot(Npoly, J_test, '--g', linewidth=2, label="err-test-RidgeCV") a0.set_ybound(.001, 40) a0.set_xbound(.5, 9.5) a0.legend() f0.show() f0.savefig("wgm-ex5-learning-curve.png")
gpl-2.0
lakshayg/tensorflow
tensorflow/contrib/factorization/python/ops/gmm_test.py
41
9763
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for ops.gmm.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib.factorization.python.ops import gmm as gmm_lib from tensorflow.contrib.learn.python.learn.estimators import kmeans from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import random_seed as random_seed_lib from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import random_ops from tensorflow.python.platform import flags from tensorflow.python.platform import test from tensorflow.python.training import queue_runner FLAGS = flags.FLAGS class GMMTest(test.TestCase): def input_fn(self, batch_size=None, points=None): batch_size = batch_size or self.batch_size points = points if points is not None else self.points num_points = points.shape[0] def _fn(): x = constant_op.constant(points) if batch_size == num_points: return x, None indices = random_ops.random_uniform(constant_op.constant([batch_size]), minval=0, maxval=num_points-1, dtype=dtypes.int32, seed=10) return array_ops.gather(x, indices), None return _fn def setUp(self): np.random.seed(3) random_seed_lib.set_random_seed(2) self.num_centers = 2 self.num_dims = 2 self.num_points = 4000 self.batch_size = self.num_points self.true_centers = self.make_random_centers(self.num_centers, self.num_dims) self.points, self.assignments, self.scores = self.make_random_points( self.true_centers, self.num_points) self.true_score = np.add.reduce(self.scores) # Use initial means from kmeans (just like scikit-learn does). clusterer = kmeans.KMeansClustering(num_clusters=self.num_centers) clusterer.fit(input_fn=lambda: (constant_op.constant(self.points), None), steps=30) self.initial_means = clusterer.clusters() @staticmethod def make_random_centers(num_centers, num_dims): return np.round( np.random.rand(num_centers, num_dims).astype(np.float32) * 500) @staticmethod def make_random_points(centers, num_points): num_centers, num_dims = centers.shape assignments = np.random.choice(num_centers, num_points) offsets = np.round( np.random.randn(num_points, num_dims).astype(np.float32) * 20) points = centers[assignments] + offsets means = [ np.mean( points[assignments == center], axis=0) for center in xrange(num_centers) ] covs = [ np.cov(points[assignments == center].T) for center in xrange(num_centers) ] scores = [] for r in xrange(num_points): scores.append( np.sqrt( np.dot( np.dot(points[r, :] - means[assignments[r]], np.linalg.inv(covs[assignments[r]])), points[r, :] - means[assignments[r]]))) return (points, assignments, scores) def test_weights(self): """Tests the shape of the weights.""" gmm = gmm_lib.GMM(self.num_centers, initial_clusters=self.initial_means, random_seed=4, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=0) weights = gmm.weights() self.assertAllEqual(list(weights.shape), [self.num_centers]) def test_clusters(self): """Tests the shape of the clusters.""" gmm = gmm_lib.GMM(self.num_centers, initial_clusters=self.initial_means, random_seed=4, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=0) clusters = gmm.clusters() self.assertAllEqual(list(clusters.shape), [self.num_centers, self.num_dims]) def test_fit(self): gmm = gmm_lib.GMM(self.num_centers, initial_clusters='random', random_seed=4, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=1) score1 = gmm.score(input_fn=self.input_fn(batch_size=self.num_points), steps=1) gmm.fit(input_fn=self.input_fn(), steps=10) score2 = gmm.score(input_fn=self.input_fn(batch_size=self.num_points), steps=1) self.assertGreater(score1, score2) self.assertNear(self.true_score, score2, self.true_score * 0.15) def test_infer(self): gmm = gmm_lib.GMM(self.num_centers, initial_clusters=self.initial_means, random_seed=4, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=60) clusters = gmm.clusters() # Make a small test set num_points = 40 points, true_assignments, true_offsets = ( self.make_random_points(clusters, num_points)) assignments = [] for item in gmm.predict_assignments( input_fn=self.input_fn(points=points, batch_size=num_points)): assignments.append(item) assignments = np.ravel(assignments) self.assertAllEqual(true_assignments, assignments) # Test score score = gmm.score(input_fn=self.input_fn(points=points, batch_size=num_points), steps=1) self.assertNear(score, np.sum(true_offsets), 4.05) def _compare_with_sklearn(self, cov_type): # sklearn version. iterations = 40 np.random.seed(5) sklearn_assignments = np.asarray([0, 0, 1, 0, 0, 0, 1, 0, 0, 1]) sklearn_means = np.asarray([[144.83417719, 254.20130341], [274.38754816, 353.16074346]]) sklearn_covs = np.asarray([[[395.0081194, -4.50389512], [-4.50389512, 408.27543989]], [[385.17484203, -31.27834935], [-31.27834935, 391.74249925]]]) # skflow version. gmm = gmm_lib.GMM(self.num_centers, initial_clusters=self.initial_means, covariance_type=cov_type, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=iterations) points = self.points[:10, :] skflow_assignments = [] for item in gmm.predict_assignments( input_fn=self.input_fn(points=points, batch_size=10)): skflow_assignments.append(item) self.assertAllClose(sklearn_assignments, np.ravel(skflow_assignments).astype(int)) self.assertAllClose(sklearn_means, gmm.clusters()) if cov_type == 'full': self.assertAllClose(sklearn_covs, gmm.covariances(), rtol=0.01) else: for d in [0, 1]: self.assertAllClose( np.diag(sklearn_covs[d]), gmm.covariances()[d, :], rtol=0.01) def test_compare_full(self): self._compare_with_sklearn('full') def test_compare_diag(self): self._compare_with_sklearn('diag') def test_random_input_large(self): # sklearn version. iterations = 5 # that should be enough to know whether this diverges np.random.seed(5) num_classes = 20 x = np.array([[np.random.random() for _ in range(100)] for _ in range(num_classes)], dtype=np.float32) # skflow version. gmm = gmm_lib.GMM(num_classes, covariance_type='full', config=run_config.RunConfig(tf_random_seed=2)) def get_input_fn(x): def input_fn(): return constant_op.constant(x.astype(np.float32)), None return input_fn gmm.fit(input_fn=get_input_fn(x), steps=iterations) self.assertFalse(np.isnan(gmm.clusters()).any()) class GMMTestQueues(test.TestCase): def input_fn(self): def _fn(): queue = data_flow_ops.FIFOQueue(capacity=10, dtypes=dtypes.float32, shapes=[10, 3]) enqueue_op = queue.enqueue(array_ops.zeros([10, 3], dtype=dtypes.float32)) queue_runner.add_queue_runner(queue_runner.QueueRunner(queue, [enqueue_op])) return queue.dequeue(), None return _fn # This test makes sure that there are no deadlocks when using a QueueRunner. # Note that since cluster initialization is dependendent on inputs, if input # is generated using a QueueRunner, one has to make sure that these runners # are started before the initialization. def test_queues(self): gmm = gmm_lib.GMM(2, covariance_type='diag') gmm.fit(input_fn=self.input_fn(), steps=1) if __name__ == '__main__': test.main()
apache-2.0
toastedcornflakes/scikit-learn
examples/manifold/plot_compare_methods.py
39
4036
""" ========================================= Comparison of Manifold Learning methods ========================================= An illustration of dimensionality reduction on the S-curve dataset with various manifold learning methods. For a discussion and comparison of these algorithms, see the :ref:`manifold module page <manifold>` For a similar example, where the methods are applied to a sphere dataset, see :ref:`example_manifold_plot_manifold_sphere.py` Note that the purpose of the MDS is to find a low-dimensional representation of the data (here 2D) in which the distances respect well the distances in the original high-dimensional space, unlike other manifold-learning algorithms, it does not seeks an isotropic representation of the data in the low-dimensional space. """ # Author: Jake Vanderplas -- <[email protected]> print(__doc__) from time import time import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter from sklearn import manifold, datasets # Next line to silence pyflakes. This import is needed. Axes3D n_points = 1000 X, color = datasets.samples_generator.make_s_curve(n_points, random_state=0) n_neighbors = 10 n_components = 2 fig = plt.figure(figsize=(15, 8)) plt.suptitle("Manifold Learning with %i points, %i neighbors" % (1000, n_neighbors), fontsize=14) try: # compatibility matplotlib < 1.0 ax = fig.add_subplot(251, projection='3d') ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=color, cmap=plt.cm.Spectral) ax.view_init(4, -72) except: ax = fig.add_subplot(251, projection='3d') plt.scatter(X[:, 0], X[:, 2], c=color, cmap=plt.cm.Spectral) methods = ['standard', 'ltsa', 'hessian', 'modified'] labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE'] for i, method in enumerate(methods): t0 = time() Y = manifold.LocallyLinearEmbedding(n_neighbors, n_components, eigen_solver='auto', method=method).fit_transform(X) t1 = time() print("%s: %.2g sec" % (methods[i], t1 - t0)) ax = fig.add_subplot(252 + i) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("%s (%.2g sec)" % (labels[i], t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') t0 = time() Y = manifold.Isomap(n_neighbors, n_components).fit_transform(X) t1 = time() print("Isomap: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(257) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("Isomap (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') t0 = time() mds = manifold.MDS(n_components, max_iter=100, n_init=1) Y = mds.fit_transform(X) t1 = time() print("MDS: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(258) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("MDS (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') t0 = time() se = manifold.SpectralEmbedding(n_components=n_components, n_neighbors=n_neighbors) Y = se.fit_transform(X) t1 = time() print("SpectralEmbedding: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(259) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("SpectralEmbedding (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') t0 = time() tsne = manifold.TSNE(n_components=n_components, init='pca', random_state=0) Y = tsne.fit_transform(X) t1 = time() print("t-SNE: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(2, 5, 10) plt.scatter(Y[:, 0], Y[:, 1], c=color, cmap=plt.cm.Spectral) plt.title("t-SNE (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') plt.show()
bsd-3-clause
JPFrancoia/scikit-learn
sklearn/decomposition/dict_learning.py
13
46149
""" Dictionary learning """ from __future__ import print_function # Author: Vlad Niculae, Gael Varoquaux, Alexandre Gramfort # License: BSD 3 clause import time import sys import itertools from math import sqrt, ceil import numpy as np from scipy import linalg from numpy.lib.stride_tricks import as_strided from ..base import BaseEstimator, TransformerMixin from ..externals.joblib import Parallel, delayed, cpu_count from ..externals.six.moves import zip from ..utils import (check_array, check_random_state, gen_even_slices, gen_batches, _get_n_jobs) from ..utils.extmath import randomized_svd, row_norms from ..utils.validation import check_is_fitted from ..linear_model import Lasso, orthogonal_mp_gram, LassoLars, Lars def _sparse_encode(X, dictionary, gram, cov=None, algorithm='lasso_lars', regularization=None, copy_cov=True, init=None, max_iter=1000, check_input=True, verbose=0): """Generic sparse coding Each column of the result is the solution to a Lasso problem. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix. dictionary: array of shape (n_components, n_features) The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows. gram: None | array, shape=(n_components, n_components) Precomputed Gram matrix, dictionary * dictionary' gram can be None if method is 'threshold'. cov: array, shape=(n_components, n_samples) Precomputed covariance, dictionary * X' algorithm: {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'} lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than regularization from the projection dictionary * data' regularization : int | float The regularization parameter. It corresponds to alpha when algorithm is 'lasso_lars', 'lasso_cd' or 'threshold'. Otherwise it corresponds to n_nonzero_coefs. init: array of shape (n_samples, n_components) Initialization value of the sparse code. Only used if `algorithm='lasso_cd'`. max_iter: int, 1000 by default Maximum number of iterations to perform if `algorithm='lasso_cd'`. copy_cov: boolean, optional Whether to copy the precomputed covariance matrix; if False, it may be overwritten. check_input: boolean, optional If False, the input arrays X and dictionary will not be checked. verbose: int Controls the verbosity; the higher, the more messages. Defaults to 0. Returns ------- code: array of shape (n_components, n_features) The sparse codes See also -------- sklearn.linear_model.lars_path sklearn.linear_model.orthogonal_mp sklearn.linear_model.Lasso SparseCoder """ if X.ndim == 1: X = X[:, np.newaxis] n_samples, n_features = X.shape if cov is None and algorithm != 'lasso_cd': # overwriting cov is safe copy_cov = False cov = np.dot(dictionary, X.T) if algorithm == 'lasso_lars': alpha = float(regularization) / n_features # account for scaling try: err_mgt = np.seterr(all='ignore') # Not passing in verbose=max(0, verbose-1) because Lars.fit already # corrects the verbosity level. lasso_lars = LassoLars(alpha=alpha, fit_intercept=False, verbose=verbose, normalize=False, precompute=gram, fit_path=False) lasso_lars.fit(dictionary.T, X.T, Xy=cov) new_code = lasso_lars.coef_ finally: np.seterr(**err_mgt) elif algorithm == 'lasso_cd': alpha = float(regularization) / n_features # account for scaling # TODO: Make verbosity argument for Lasso? # sklearn.linear_model.coordinate_descent.enet_path has a verbosity # argument that we could pass in from Lasso. clf = Lasso(alpha=alpha, fit_intercept=False, normalize=False, precompute=gram, max_iter=max_iter, warm_start=True) clf.coef_ = init clf.fit(dictionary.T, X.T, check_input=check_input) new_code = clf.coef_ elif algorithm == 'lars': try: err_mgt = np.seterr(all='ignore') # Not passing in verbose=max(0, verbose-1) because Lars.fit already # corrects the verbosity level. lars = Lars(fit_intercept=False, verbose=verbose, normalize=False, precompute=gram, n_nonzero_coefs=int(regularization), fit_path=False) lars.fit(dictionary.T, X.T, Xy=cov) new_code = lars.coef_ finally: np.seterr(**err_mgt) elif algorithm == 'threshold': new_code = ((np.sign(cov) * np.maximum(np.abs(cov) - regularization, 0)).T) elif algorithm == 'omp': # TODO: Should verbose argument be passed to this? new_code = orthogonal_mp_gram( Gram=gram, Xy=cov, n_nonzero_coefs=int(regularization), tol=None, norms_squared=row_norms(X, squared=True), copy_Xy=copy_cov).T else: raise ValueError('Sparse coding method must be "lasso_lars" ' '"lasso_cd", "lasso", "threshold" or "omp", got %s.' % algorithm) return new_code # XXX : could be moved to the linear_model module def sparse_encode(X, dictionary, gram=None, cov=None, algorithm='lasso_lars', n_nonzero_coefs=None, alpha=None, copy_cov=True, init=None, max_iter=1000, n_jobs=1, check_input=True, verbose=0): """Sparse coding Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array `code` such that:: X ~= code * dictionary Read more in the :ref:`User Guide <SparseCoder>`. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix dictionary: array of shape (n_components, n_features) The dictionary matrix against which to solve the sparse coding of the data. Some of the algorithms assume normalized rows for meaningful output. gram: array, shape=(n_components, n_components) Precomputed Gram matrix, dictionary * dictionary' cov: array, shape=(n_components, n_samples) Precomputed covariance, dictionary' * X algorithm: {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'} lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection dictionary * X' n_nonzero_coefs: int, 0.1 * n_features by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. alpha: float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. init: array of shape (n_samples, n_components) Initialization value of the sparse codes. Only used if `algorithm='lasso_cd'`. max_iter: int, 1000 by default Maximum number of iterations to perform if `algorithm='lasso_cd'`. copy_cov: boolean, optional Whether to copy the precomputed covariance matrix; if False, it may be overwritten. n_jobs: int, optional Number of parallel jobs to run. check_input: boolean, optional If False, the input arrays X and dictionary will not be checked. verbose : int, optional Controls the verbosity; the higher, the more messages. Defaults to 0. Returns ------- code: array of shape (n_samples, n_components) The sparse codes See also -------- sklearn.linear_model.lars_path sklearn.linear_model.orthogonal_mp sklearn.linear_model.Lasso SparseCoder """ if check_input: if algorithm == 'lasso_cd': dictionary = check_array(dictionary, order='C', dtype='float64') X = check_array(X, order='C', dtype='float64') else: dictionary = check_array(dictionary) X = check_array(X) n_samples, n_features = X.shape n_components = dictionary.shape[0] if gram is None and algorithm != 'threshold': gram = np.dot(dictionary, dictionary.T) if cov is None and algorithm != 'lasso_cd': copy_cov = False cov = np.dot(dictionary, X.T) if algorithm in ('lars', 'omp'): regularization = n_nonzero_coefs if regularization is None: regularization = min(max(n_features / 10, 1), n_components) else: regularization = alpha if regularization is None: regularization = 1. if n_jobs == 1 or algorithm == 'threshold': code = _sparse_encode(X, dictionary, gram, cov=cov, algorithm=algorithm, regularization=regularization, copy_cov=copy_cov, init=init, max_iter=max_iter, check_input=False, verbose=verbose) # This ensure that dimensionality of code is always 2, # consistant with the case n_jobs > 1 if code.ndim == 1: code = code[np.newaxis, :] return code # Enter parallel code block code = np.empty((n_samples, n_components)) slices = list(gen_even_slices(n_samples, _get_n_jobs(n_jobs))) code_views = Parallel(n_jobs=n_jobs, verbose=verbose)( delayed(_sparse_encode)( X[this_slice], dictionary, gram, cov[:, this_slice] if cov is not None else None, algorithm, regularization=regularization, copy_cov=copy_cov, init=init[this_slice] if init is not None else None, max_iter=max_iter, check_input=False) for this_slice in slices) for this_slice, this_view in zip(slices, code_views): code[this_slice] = this_view return code def _update_dict(dictionary, Y, code, verbose=False, return_r2=False, random_state=None): """Update the dense dictionary factor in place. Parameters ---------- dictionary: array of shape (n_features, n_components) Value of the dictionary at the previous iteration. Y: array of shape (n_features, n_samples) Data matrix. code: array of shape (n_components, n_samples) Sparse coding of the data against which to optimize the dictionary. verbose: Degree of output the procedure will print. return_r2: bool Whether to compute and return the residual sum of squares corresponding to the computed solution. random_state: int or RandomState Pseudo number generator state used for random sampling. Returns ------- dictionary: array of shape (n_features, n_components) Updated dictionary. """ n_components = len(code) n_samples = Y.shape[0] random_state = check_random_state(random_state) # Residuals, computed 'in-place' for efficiency R = -np.dot(dictionary, code) R += Y R = np.asfortranarray(R) ger, = linalg.get_blas_funcs(('ger',), (dictionary, code)) for k in range(n_components): # R <- 1.0 * U_k * V_k^T + R R = ger(1.0, dictionary[:, k], code[k, :], a=R, overwrite_a=True) dictionary[:, k] = np.dot(R, code[k, :].T) # Scale k'th atom atom_norm_square = np.dot(dictionary[:, k], dictionary[:, k]) if atom_norm_square < 1e-20: if verbose == 1: sys.stdout.write("+") sys.stdout.flush() elif verbose: print("Adding new random atom") dictionary[:, k] = random_state.randn(n_samples) # Setting corresponding coefs to 0 code[k, :] = 0.0 dictionary[:, k] /= sqrt(np.dot(dictionary[:, k], dictionary[:, k])) else: dictionary[:, k] /= sqrt(atom_norm_square) # R <- -1.0 * U_k * V_k^T + R R = ger(-1.0, dictionary[:, k], code[k, :], a=R, overwrite_a=True) if return_r2: R **= 2 # R is fortran-ordered. For numpy version < 1.6, sum does not # follow the quick striding first, and is thus inefficient on # fortran ordered data. We take a flat view of the data with no # striding R = as_strided(R, shape=(R.size, ), strides=(R.dtype.itemsize,)) R = np.sum(R) return dictionary, R return dictionary def dict_learning(X, n_components, alpha, max_iter=100, tol=1e-8, method='lars', n_jobs=1, dict_init=None, code_init=None, callback=None, verbose=False, random_state=None, return_n_iter=False): """Solves a dictionary learning matrix factorization problem. Finds the best dictionary and the corresponding sparse code for approximating the data matrix X by solving:: (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components where V is the dictionary and U is the sparse code. Read more in the :ref:`User Guide <DictionaryLearning>`. Parameters ---------- X : array of shape (n_samples, n_features) Data matrix. n_components : int, Number of dictionary atoms to extract. alpha : int, Sparsity controlling parameter. max_iter : int, Maximum number of iterations to perform. tol : float, Tolerance for the stopping condition. method : {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. n_jobs : int, Number of parallel jobs to run, or -1 to autodetect. dict_init : array of shape (n_components, n_features), Initial value for the dictionary for warm restart scenarios. code_init : array of shape (n_samples, n_components), Initial value for the sparse code for warm restart scenarios. callback : Callable that gets invoked every five iterations. verbose : Degree of output the procedure will print. random_state : int or RandomState Pseudo number generator state used for random sampling. return_n_iter : bool Whether or not to return the number of iterations. Returns ------- code : array of shape (n_samples, n_components) The sparse code factor in the matrix factorization. dictionary : array of shape (n_components, n_features), The dictionary factor in the matrix factorization. errors : array Vector of errors at each iteration. n_iter : int Number of iterations run. Returned only if `return_n_iter` is set to True. See also -------- dict_learning_online DictionaryLearning MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA """ if method not in ('lars', 'cd'): raise ValueError('Coding method %r not supported as a fit algorithm.' % method) method = 'lasso_' + method t0 = time.time() # Avoid integer division problems alpha = float(alpha) random_state = check_random_state(random_state) if n_jobs == -1: n_jobs = cpu_count() # Init the code and the dictionary with SVD of Y if code_init is not None and dict_init is not None: code = np.array(code_init, order='F') # Don't copy V, it will happen below dictionary = dict_init else: code, S, dictionary = linalg.svd(X, full_matrices=False) dictionary = S[:, np.newaxis] * dictionary r = len(dictionary) if n_components <= r: # True even if n_components=None code = code[:, :n_components] dictionary = dictionary[:n_components, :] else: code = np.c_[code, np.zeros((len(code), n_components - r))] dictionary = np.r_[dictionary, np.zeros((n_components - r, dictionary.shape[1]))] # Fortran-order dict, as we are going to access its row vectors dictionary = np.array(dictionary, order='F') residuals = 0 errors = [] current_cost = np.nan if verbose == 1: print('[dict_learning]', end=' ') # If max_iter is 0, number of iterations returned should be zero ii = -1 for ii in range(max_iter): dt = (time.time() - t0) if verbose == 1: sys.stdout.write(".") sys.stdout.flush() elif verbose: print("Iteration % 3i " "(elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)" % (ii, dt, dt / 60, current_cost)) # Update code code = sparse_encode(X, dictionary, algorithm=method, alpha=alpha, init=code, n_jobs=n_jobs) # Update dictionary dictionary, residuals = _update_dict(dictionary.T, X.T, code.T, verbose=verbose, return_r2=True, random_state=random_state) dictionary = dictionary.T # Cost function current_cost = 0.5 * residuals + alpha * np.sum(np.abs(code)) errors.append(current_cost) if ii > 0: dE = errors[-2] - errors[-1] # assert(dE >= -tol * errors[-1]) if dE < tol * errors[-1]: if verbose == 1: # A line return print("") elif verbose: print("--- Convergence reached after %d iterations" % ii) break if ii % 5 == 0 and callback is not None: callback(locals()) if return_n_iter: return code, dictionary, errors, ii + 1 else: return code, dictionary, errors def dict_learning_online(X, n_components=2, alpha=1, n_iter=100, return_code=True, dict_init=None, callback=None, batch_size=3, verbose=False, shuffle=True, n_jobs=1, method='lars', iter_offset=0, random_state=None, return_inner_stats=False, inner_stats=None, return_n_iter=False): """Solves a dictionary learning matrix factorization problem online. Finds the best dictionary and the corresponding sparse code for approximating the data matrix X by solving:: (U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components where V is the dictionary and U is the sparse code. This is accomplished by repeatedly iterating over mini-batches by slicing the input data. Read more in the :ref:`User Guide <DictionaryLearning>`. Parameters ---------- X: array of shape (n_samples, n_features) Data matrix. n_components : int, Number of dictionary atoms to extract. alpha : float, Sparsity controlling parameter. n_iter : int, Number of iterations to perform. return_code : boolean, Whether to also return the code U or just the dictionary V. dict_init : array of shape (n_components, n_features), Initial value for the dictionary for warm restart scenarios. callback : Callable that gets invoked every five iterations. batch_size : int, The number of samples to take in each batch. verbose : Degree of output the procedure will print. shuffle : boolean, Whether to shuffle the data before splitting it in batches. n_jobs : int, Number of parallel jobs to run, or -1 to autodetect. method : {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. iter_offset : int, default 0 Number of previous iterations completed on the dictionary used for initialization. random_state : int or RandomState Pseudo number generator state used for random sampling. return_inner_stats : boolean, optional Return the inner statistics A (dictionary covariance) and B (data approximation). Useful to restart the algorithm in an online setting. If return_inner_stats is True, return_code is ignored inner_stats : tuple of (A, B) ndarrays Inner sufficient statistics that are kept by the algorithm. Passing them at initialization is useful in online settings, to avoid loosing the history of the evolution. A (n_components, n_components) is the dictionary covariance matrix. B (n_features, n_components) is the data approximation matrix return_n_iter : bool Whether or not to return the number of iterations. Returns ------- code : array of shape (n_samples, n_components), the sparse code (only returned if `return_code=True`) dictionary : array of shape (n_components, n_features), the solutions to the dictionary learning problem n_iter : int Number of iterations run. Returned only if `return_n_iter` is set to `True`. See also -------- dict_learning DictionaryLearning MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA """ if n_components is None: n_components = X.shape[1] if method not in ('lars', 'cd'): raise ValueError('Coding method not supported as a fit algorithm.') method = 'lasso_' + method t0 = time.time() n_samples, n_features = X.shape # Avoid integer division problems alpha = float(alpha) random_state = check_random_state(random_state) if n_jobs == -1: n_jobs = cpu_count() # Init V with SVD of X if dict_init is not None: dictionary = dict_init else: _, S, dictionary = randomized_svd(X, n_components, random_state=random_state) dictionary = S[:, np.newaxis] * dictionary r = len(dictionary) if n_components <= r: dictionary = dictionary[:n_components, :] else: dictionary = np.r_[dictionary, np.zeros((n_components - r, dictionary.shape[1]))] if verbose == 1: print('[dict_learning]', end=' ') if shuffle: X_train = X.copy() random_state.shuffle(X_train) else: X_train = X dictionary = check_array(dictionary.T, order='F', dtype=np.float64, copy=False) X_train = check_array(X_train, order='C', dtype=np.float64, copy=False) batches = gen_batches(n_samples, batch_size) batches = itertools.cycle(batches) # The covariance of the dictionary if inner_stats is None: A = np.zeros((n_components, n_components)) # The data approximation B = np.zeros((n_features, n_components)) else: A = inner_stats[0].copy() B = inner_stats[1].copy() # If n_iter is zero, we need to return zero. ii = iter_offset - 1 for ii, batch in zip(range(iter_offset, iter_offset + n_iter), batches): this_X = X_train[batch] dt = (time.time() - t0) if verbose == 1: sys.stdout.write(".") sys.stdout.flush() elif verbose: if verbose > 10 or ii % ceil(100. / verbose) == 0: print ("Iteration % 3i (elapsed time: % 3is, % 4.1fmn)" % (ii, dt, dt / 60)) this_code = sparse_encode(this_X, dictionary.T, algorithm=method, alpha=alpha, n_jobs=n_jobs).T # Update the auxiliary variables if ii < batch_size - 1: theta = float((ii + 1) * batch_size) else: theta = float(batch_size ** 2 + ii + 1 - batch_size) beta = (theta + 1 - batch_size) / (theta + 1) A *= beta A += np.dot(this_code, this_code.T) B *= beta B += np.dot(this_X.T, this_code.T) # Update dictionary dictionary = _update_dict(dictionary, B, A, verbose=verbose, random_state=random_state) # XXX: Can the residuals be of any use? # Maybe we need a stopping criteria based on the amount of # modification in the dictionary if callback is not None: callback(locals()) if return_inner_stats: if return_n_iter: return dictionary.T, (A, B), ii - iter_offset + 1 else: return dictionary.T, (A, B) if return_code: if verbose > 1: print('Learning code...', end=' ') elif verbose == 1: print('|', end=' ') code = sparse_encode(X, dictionary.T, algorithm=method, alpha=alpha, n_jobs=n_jobs, check_input=False) if verbose > 1: dt = (time.time() - t0) print('done (total time: % 3is, % 4.1fmn)' % (dt, dt / 60)) if return_n_iter: return code, dictionary.T, ii - iter_offset + 1 else: return code, dictionary.T if return_n_iter: return dictionary.T, ii - iter_offset + 1 else: return dictionary.T class SparseCodingMixin(TransformerMixin): """Sparse coding mixin""" def _set_sparse_coding_params(self, n_components, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, split_sign=False, n_jobs=1): self.n_components = n_components self.transform_algorithm = transform_algorithm self.transform_n_nonzero_coefs = transform_n_nonzero_coefs self.transform_alpha = transform_alpha self.split_sign = split_sign self.n_jobs = n_jobs def transform(self, X, y=None): """Encode the data as a sparse combination of the dictionary atoms. Coding method is determined by the object parameter `transform_algorithm`. Parameters ---------- X : array of shape (n_samples, n_features) Test data to be transformed, must have the same number of features as the data used to train the model. Returns ------- X_new : array, shape (n_samples, n_components) Transformed data """ check_is_fitted(self, 'components_') # XXX : kwargs is not documented X = check_array(X) n_samples, n_features = X.shape code = sparse_encode( X, self.components_, algorithm=self.transform_algorithm, n_nonzero_coefs=self.transform_n_nonzero_coefs, alpha=self.transform_alpha, n_jobs=self.n_jobs) if self.split_sign: # feature vector is split into a positive and negative side n_samples, n_features = code.shape split_code = np.empty((n_samples, 2 * n_features)) split_code[:, :n_features] = np.maximum(code, 0) split_code[:, n_features:] = -np.minimum(code, 0) code = split_code return code class SparseCoder(BaseEstimator, SparseCodingMixin): """Sparse coding Finds a sparse representation of data against a fixed, precomputed dictionary. Each row of the result is the solution to a sparse coding problem. The goal is to find a sparse array `code` such that:: X ~= code * dictionary Read more in the :ref:`User Guide <SparseCoder>`. Parameters ---------- dictionary : array, [n_components, n_features] The dictionary atoms used for sparse coding. Lines are assumed to be normalized to unit norm. transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \ 'threshold'} Algorithm used to transform the data: lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection ``dictionary * X'`` transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. transform_alpha : float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. split_sign : bool, False by default Whether to split the sparse feature vector into the concatenation of its negative part and its positive part. This can improve the performance of downstream classifiers. n_jobs : int, number of parallel jobs to run Attributes ---------- components_ : array, [n_components, n_features] The unchanged dictionary atoms See also -------- DictionaryLearning MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA sparse_encode """ def __init__(self, dictionary, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, split_sign=False, n_jobs=1): self._set_sparse_coding_params(dictionary.shape[0], transform_algorithm, transform_n_nonzero_coefs, transform_alpha, split_sign, n_jobs) self.components_ = dictionary def fit(self, X, y=None): """Do nothing and return the estimator unchanged This method is just there to implement the usual API and hence work in pipelines. """ return self class DictionaryLearning(BaseEstimator, SparseCodingMixin): """Dictionary learning Finds a dictionary (a set of atoms) that can best be used to represent data using a sparse code. Solves the optimization problem:: (U^*,V^*) = argmin 0.5 || Y - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components Read more in the :ref:`User Guide <DictionaryLearning>`. Parameters ---------- n_components : int, number of dictionary elements to extract alpha : float, sparsity controlling parameter max_iter : int, maximum number of iterations to perform tol : float, tolerance for numerical error fit_algorithm : {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. .. versionadded:: 0.17 *cd* coordinate descent method to improve speed. transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \ 'threshold'} Algorithm used to transform the data lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection ``dictionary * X'`` .. versionadded:: 0.17 *lasso_cd* coordinate descent method to improve speed. transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. transform_alpha : float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. split_sign : bool, False by default Whether to split the sparse feature vector into the concatenation of its negative part and its positive part. This can improve the performance of downstream classifiers. n_jobs : int, number of parallel jobs to run code_init : array of shape (n_samples, n_components), initial value for the code, for warm restart dict_init : array of shape (n_components, n_features), initial values for the dictionary, for warm restart verbose : degree of verbosity of the printed output random_state : int or RandomState Pseudo number generator state used for random sampling. Attributes ---------- components_ : array, [n_components, n_features] dictionary atoms extracted from the data error_ : array vector of errors at each iteration n_iter_ : int Number of iterations run. Notes ----- **References:** J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning for sparse coding (http://www.di.ens.fr/sierra/pdfs/icml09.pdf) See also -------- SparseCoder MiniBatchDictionaryLearning SparsePCA MiniBatchSparsePCA """ def __init__(self, n_components=None, alpha=1, max_iter=1000, tol=1e-8, fit_algorithm='lars', transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, n_jobs=1, code_init=None, dict_init=None, verbose=False, split_sign=False, random_state=None): self._set_sparse_coding_params(n_components, transform_algorithm, transform_n_nonzero_coefs, transform_alpha, split_sign, n_jobs) self.alpha = alpha self.max_iter = max_iter self.tol = tol self.fit_algorithm = fit_algorithm self.code_init = code_init self.dict_init = dict_init self.verbose = verbose self.random_state = random_state def fit(self, X, y=None): """Fit the model from data in X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- self: object Returns the object itself """ random_state = check_random_state(self.random_state) X = check_array(X) if self.n_components is None: n_components = X.shape[1] else: n_components = self.n_components V, U, E, self.n_iter_ = dict_learning( X, n_components, self.alpha, tol=self.tol, max_iter=self.max_iter, method=self.fit_algorithm, n_jobs=self.n_jobs, code_init=self.code_init, dict_init=self.dict_init, verbose=self.verbose, random_state=random_state, return_n_iter=True) self.components_ = U self.error_ = E return self class MiniBatchDictionaryLearning(BaseEstimator, SparseCodingMixin): """Mini-batch dictionary learning Finds a dictionary (a set of atoms) that can best be used to represent data using a sparse code. Solves the optimization problem:: (U^*,V^*) = argmin 0.5 || Y - U V ||_2^2 + alpha * || U ||_1 (U,V) with || V_k ||_2 = 1 for all 0 <= k < n_components Read more in the :ref:`User Guide <DictionaryLearning>`. Parameters ---------- n_components : int, number of dictionary elements to extract alpha : float, sparsity controlling parameter n_iter : int, total number of iterations to perform fit_algorithm : {'lars', 'cd'} lars: uses the least angle regression method to solve the lasso problem (linear_model.lars_path) cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). Lars will be faster if the estimated components are sparse. transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \ 'threshold'} Algorithm used to transform the data. lars: uses the least angle regression method (linear_model.lars_path) lasso_lars: uses Lars to compute the Lasso solution lasso_cd: uses the coordinate descent method to compute the Lasso solution (linear_model.Lasso). lasso_lars will be faster if the estimated components are sparse. omp: uses orthogonal matching pursuit to estimate the sparse solution threshold: squashes to zero all coefficients less than alpha from the projection dictionary * X' transform_n_nonzero_coefs : int, ``0.1 * n_features`` by default Number of nonzero coefficients to target in each column of the solution. This is only used by `algorithm='lars'` and `algorithm='omp'` and is overridden by `alpha` in the `omp` case. transform_alpha : float, 1. by default If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the penalty applied to the L1 norm. If `algorithm='threshold'`, `alpha` is the absolute value of the threshold below which coefficients will be squashed to zero. If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of the reconstruction error targeted. In this case, it overrides `n_nonzero_coefs`. split_sign : bool, False by default Whether to split the sparse feature vector into the concatenation of its negative part and its positive part. This can improve the performance of downstream classifiers. n_jobs : int, number of parallel jobs to run dict_init : array of shape (n_components, n_features), initial value of the dictionary for warm restart scenarios verbose : degree of verbosity of the printed output batch_size : int, number of samples in each mini-batch shuffle : bool, whether to shuffle the samples before forming batches random_state : int or RandomState Pseudo number generator state used for random sampling. Attributes ---------- components_ : array, [n_components, n_features] components extracted from the data inner_stats_ : tuple of (A, B) ndarrays Internal sufficient statistics that are kept by the algorithm. Keeping them is useful in online settings, to avoid loosing the history of the evolution, but they shouldn't have any use for the end user. A (n_components, n_components) is the dictionary covariance matrix. B (n_features, n_components) is the data approximation matrix n_iter_ : int Number of iterations run. Notes ----- **References:** J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning for sparse coding (http://www.di.ens.fr/sierra/pdfs/icml09.pdf) See also -------- SparseCoder DictionaryLearning SparsePCA MiniBatchSparsePCA """ def __init__(self, n_components=None, alpha=1, n_iter=1000, fit_algorithm='lars', n_jobs=1, batch_size=3, shuffle=True, dict_init=None, transform_algorithm='omp', transform_n_nonzero_coefs=None, transform_alpha=None, verbose=False, split_sign=False, random_state=None): self._set_sparse_coding_params(n_components, transform_algorithm, transform_n_nonzero_coefs, transform_alpha, split_sign, n_jobs) self.alpha = alpha self.n_iter = n_iter self.fit_algorithm = fit_algorithm self.dict_init = dict_init self.verbose = verbose self.shuffle = shuffle self.batch_size = batch_size self.split_sign = split_sign self.random_state = random_state def fit(self, X, y=None): """Fit the model from data in X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- self : object Returns the instance itself. """ random_state = check_random_state(self.random_state) X = check_array(X) U, (A, B), self.n_iter_ = dict_learning_online( X, self.n_components, self.alpha, n_iter=self.n_iter, return_code=False, method=self.fit_algorithm, n_jobs=self.n_jobs, dict_init=self.dict_init, batch_size=self.batch_size, shuffle=self.shuffle, verbose=self.verbose, random_state=random_state, return_inner_stats=True, return_n_iter=True) self.components_ = U # Keep track of the state of the algorithm to be able to do # some online fitting (partial_fit) self.inner_stats_ = (A, B) self.iter_offset_ = self.n_iter return self def partial_fit(self, X, y=None, iter_offset=None): """Updates the model using the data in X as a mini-batch. Parameters ---------- X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. iter_offset: integer, optional The number of iteration on data batches that has been performed before this call to partial_fit. This is optional: if no number is passed, the memory of the object is used. Returns ------- self : object Returns the instance itself. """ if not hasattr(self, 'random_state_'): self.random_state_ = check_random_state(self.random_state) X = check_array(X) if hasattr(self, 'components_'): dict_init = self.components_ else: dict_init = self.dict_init inner_stats = getattr(self, 'inner_stats_', None) if iter_offset is None: iter_offset = getattr(self, 'iter_offset_', 0) U, (A, B) = dict_learning_online( X, self.n_components, self.alpha, n_iter=self.n_iter, method=self.fit_algorithm, n_jobs=self.n_jobs, dict_init=dict_init, batch_size=len(X), shuffle=False, verbose=self.verbose, return_code=False, iter_offset=iter_offset, random_state=self.random_state_, return_inner_stats=True, inner_stats=inner_stats) self.components_ = U # Keep track of the state of the algorithm to be able to do # some online fitting (partial_fit) self.inner_stats_ = (A, B) self.iter_offset_ = iter_offset + self.n_iter return self
bsd-3-clause
shikhardb/scikit-learn
examples/cluster/plot_digits_linkage.py
369
2959
""" ============================================================================= Various Agglomerative Clustering on a 2D embedding of digits ============================================================================= An illustration of various linkage option for agglomerative clustering on a 2D embedding of the digits dataset. The goal of this example is to show intuitively how the metrics behave, and not to find good clusters for the digits. This is why the example works on a 2D embedding. What this example shows us is the behavior "rich getting richer" of agglomerative clustering that tends to create uneven cluster sizes. This behavior is especially pronounced for the average linkage strategy, that ends up with a couple of singleton clusters. """ # Authors: Gael Varoquaux # License: BSD 3 clause (C) INRIA 2014 print(__doc__) from time import time import numpy as np from scipy import ndimage from matplotlib import pyplot as plt from sklearn import manifold, datasets digits = datasets.load_digits(n_class=10) X = digits.data y = digits.target n_samples, n_features = X.shape np.random.seed(0) def nudge_images(X, y): # Having a larger dataset shows more clearly the behavior of the # methods, but we multiply the size of the dataset only by 2, as the # cost of the hierarchical clustering methods are strongly # super-linear in n_samples shift = lambda x: ndimage.shift(x.reshape((8, 8)), .3 * np.random.normal(size=2), mode='constant', ).ravel() X = np.concatenate([X, np.apply_along_axis(shift, 1, X)]) Y = np.concatenate([y, y], axis=0) return X, Y X, y = nudge_images(X, y) #---------------------------------------------------------------------- # Visualize the clustering def plot_clustering(X_red, X, labels, title=None): x_min, x_max = np.min(X_red, axis=0), np.max(X_red, axis=0) X_red = (X_red - x_min) / (x_max - x_min) plt.figure(figsize=(6, 4)) for i in range(X_red.shape[0]): plt.text(X_red[i, 0], X_red[i, 1], str(y[i]), color=plt.cm.spectral(labels[i] / 10.), fontdict={'weight': 'bold', 'size': 9}) plt.xticks([]) plt.yticks([]) if title is not None: plt.title(title, size=17) plt.axis('off') plt.tight_layout() #---------------------------------------------------------------------- # 2D embedding of the digits dataset print("Computing embedding") X_red = manifold.SpectralEmbedding(n_components=2).fit_transform(X) print("Done.") from sklearn.cluster import AgglomerativeClustering for linkage in ('ward', 'average', 'complete'): clustering = AgglomerativeClustering(linkage=linkage, n_clusters=10) t0 = time() clustering.fit(X_red) print("%s : %.2fs" % (linkage, time() - t0)) plot_clustering(X_red, X, clustering.labels_, "%s linkage" % linkage) plt.show()
bsd-3-clause
dwettstein/pattern-recognition-2016
mlp/model_selection/exceptions.py
35
4329
""" The :mod:`sklearn.exceptions` module includes all custom warnings and error classes used across scikit-learn. """ __all__ = ['NotFittedError', 'ChangedBehaviorWarning', 'ConvergenceWarning', 'DataConversionWarning', 'DataDimensionalityWarning', 'EfficiencyWarning', 'FitFailedWarning', 'NonBLASDotWarning', 'UndefinedMetricWarning'] class NotFittedError(ValueError, AttributeError): """Exception class to raise if estimator is used before fitting. This class inherits from both ValueError and AttributeError to help with exception handling and backward compatibility. Examples -------- >>> from sklearn.svm import LinearSVC >>> from sklearn.exceptions import NotFittedError >>> try: ... LinearSVC().predict([[1, 2], [2, 3], [3, 4]]) ... except NotFittedError as e: ... print(repr(e)) ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS NotFittedError('This LinearSVC instance is not fitted yet',) """ class ChangedBehaviorWarning(UserWarning): """Warning class used to notify the user of any change in the behavior.""" class ConvergenceWarning(UserWarning): """Custom warning to capture convergence problems""" class DataConversionWarning(UserWarning): """Warning used to notify implicit data conversions happening in the code. This warning occurs when some input data needs to be converted or interpreted in a way that may not match the user's expectations. For example, this warning may occur when the user - passes an integer array to a function which expects float input and will convert the input - requests a non-copying operation, but a copy is required to meet the implementation's data-type expectations; - passes an input whose shape can be interpreted ambiguously. """ class DataDimensionalityWarning(UserWarning): """Custom warning to notify potential issues with data dimensionality. For example, in random projection, this warning is raised when the number of components, which quantifies the dimensionality of the target projection space, is higher than the number of features, which quantifies the dimensionality of the original source space, to imply that the dimensionality of the problem will not be reduced. """ class EfficiencyWarning(UserWarning): """Warning used to notify the user of inefficient computation. This warning notifies the user that the efficiency may not be optimal due to some reason which may be included as a part of the warning message. This may be subclassed into a more specific Warning class. """ class FitFailedWarning(RuntimeWarning): """Warning class used if there is an error while fitting the estimator. This Warning is used in meta estimators GridSearchCV and RandomizedSearchCV and the cross-validation helper function cross_val_score to warn when there is an error while fitting the estimator. Examples -------- >>> from sklearn.model_selection import GridSearchCV >>> from sklearn.svm import LinearSVC >>> from sklearn.exceptions import FitFailedWarning >>> import warnings >>> warnings.simplefilter('always', FitFailedWarning) >>> gs = GridSearchCV(LinearSVC(), {'C': [-1, -2]}, error_score=0) >>> X, y = [[1, 2], [3, 4], [5, 6], [7, 8], [8, 9]], [0, 0, 0, 1, 1] >>> with warnings.catch_warnings(record=True) as w: ... try: ... gs.fit(X, y) # This will raise a ValueError since C is < 0 ... except ValueError: ... pass ... print(repr(w[-1].message)) ... # doctest: +NORMALIZE_WHITESPACE FitFailedWarning("Classifier fit failed. The score on this train-test partition for these parameters will be set to 0.000000. Details: \\nValueError('Penalty term must be positive; got (C=-2)',)",) """ class NonBLASDotWarning(EfficiencyWarning): """Warning used when the dot operation does not use BLAS. This warning is used to notify the user that BLAS was not used for dot operation and hence the efficiency may be affected. """ class UndefinedMetricWarning(UserWarning): """Warning used when the metric is invalid"""
mit
hsuantien/scikit-learn
examples/applications/svm_gui.py
287
11161
""" ========== Libsvm GUI ========== A simple graphical frontend for Libsvm mainly intended for didactic purposes. You can create data points by point and click and visualize the decision region induced by different kernels and parameter settings. To create positive examples click the left mouse button; to create negative examples click the right button. If all examples are from the same class, it uses a one-class SVM. """ from __future__ import division, print_function print(__doc__) # Author: Peter Prettenhoer <[email protected]> # # License: BSD 3 clause import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib.contour import ContourSet import Tkinter as Tk import sys import numpy as np from sklearn import svm from sklearn.datasets import dump_svmlight_file from sklearn.externals.six.moves import xrange y_min, y_max = -50, 50 x_min, x_max = -50, 50 class Model(object): """The Model which hold the data. It implements the observable in the observer pattern and notifies the registered observers on change event. """ def __init__(self): self.observers = [] self.surface = None self.data = [] self.cls = None self.surface_type = 0 def changed(self, event): """Notify the observers. """ for observer in self.observers: observer.update(event, self) def add_observer(self, observer): """Register an observer. """ self.observers.append(observer) def set_surface(self, surface): self.surface = surface def dump_svmlight_file(self, file): data = np.array(self.data) X = data[:, 0:2] y = data[:, 2] dump_svmlight_file(X, y, file) class Controller(object): def __init__(self, model): self.model = model self.kernel = Tk.IntVar() self.surface_type = Tk.IntVar() # Whether or not a model has been fitted self.fitted = False def fit(self): print("fit the model") train = np.array(self.model.data) X = train[:, 0:2] y = train[:, 2] C = float(self.complexity.get()) gamma = float(self.gamma.get()) coef0 = float(self.coef0.get()) degree = int(self.degree.get()) kernel_map = {0: "linear", 1: "rbf", 2: "poly"} if len(np.unique(y)) == 1: clf = svm.OneClassSVM(kernel=kernel_map[self.kernel.get()], gamma=gamma, coef0=coef0, degree=degree) clf.fit(X) else: clf = svm.SVC(kernel=kernel_map[self.kernel.get()], C=C, gamma=gamma, coef0=coef0, degree=degree) clf.fit(X, y) if hasattr(clf, 'score'): print("Accuracy:", clf.score(X, y) * 100) X1, X2, Z = self.decision_surface(clf) self.model.clf = clf self.model.set_surface((X1, X2, Z)) self.model.surface_type = self.surface_type.get() self.fitted = True self.model.changed("surface") def decision_surface(self, cls): delta = 1 x = np.arange(x_min, x_max + delta, delta) y = np.arange(y_min, y_max + delta, delta) X1, X2 = np.meshgrid(x, y) Z = cls.decision_function(np.c_[X1.ravel(), X2.ravel()]) Z = Z.reshape(X1.shape) return X1, X2, Z def clear_data(self): self.model.data = [] self.fitted = False self.model.changed("clear") def add_example(self, x, y, label): self.model.data.append((x, y, label)) self.model.changed("example_added") # update decision surface if already fitted. self.refit() def refit(self): """Refit the model if already fitted. """ if self.fitted: self.fit() class View(object): """Test docstring. """ def __init__(self, root, controller): f = Figure() ax = f.add_subplot(111) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim((x_min, x_max)) ax.set_ylim((y_min, y_max)) canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas.mpl_connect('button_press_event', self.onclick) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() self.controllbar = ControllBar(root, controller) self.f = f self.ax = ax self.canvas = canvas self.controller = controller self.contours = [] self.c_labels = None self.plot_kernels() def plot_kernels(self): self.ax.text(-50, -60, "Linear: $u^T v$") self.ax.text(-20, -60, "RBF: $\exp (-\gamma \| u-v \|^2)$") self.ax.text(10, -60, "Poly: $(\gamma \, u^T v + r)^d$") def onclick(self, event): if event.xdata and event.ydata: if event.button == 1: self.controller.add_example(event.xdata, event.ydata, 1) elif event.button == 3: self.controller.add_example(event.xdata, event.ydata, -1) def update_example(self, model, idx): x, y, l = model.data[idx] if l == 1: color = 'w' elif l == -1: color = 'k' self.ax.plot([x], [y], "%so" % color, scalex=0.0, scaley=0.0) def update(self, event, model): if event == "examples_loaded": for i in xrange(len(model.data)): self.update_example(model, i) if event == "example_added": self.update_example(model, -1) if event == "clear": self.ax.clear() self.ax.set_xticks([]) self.ax.set_yticks([]) self.contours = [] self.c_labels = None self.plot_kernels() if event == "surface": self.remove_surface() self.plot_support_vectors(model.clf.support_vectors_) self.plot_decision_surface(model.surface, model.surface_type) self.canvas.draw() def remove_surface(self): """Remove old decision surface.""" if len(self.contours) > 0: for contour in self.contours: if isinstance(contour, ContourSet): for lineset in contour.collections: lineset.remove() else: contour.remove() self.contours = [] def plot_support_vectors(self, support_vectors): """Plot the support vectors by placing circles over the corresponding data points and adds the circle collection to the contours list.""" cs = self.ax.scatter(support_vectors[:, 0], support_vectors[:, 1], s=80, edgecolors="k", facecolors="none") self.contours.append(cs) def plot_decision_surface(self, surface, type): X1, X2, Z = surface if type == 0: levels = [-1.0, 0.0, 1.0] linestyles = ['dashed', 'solid', 'dashed'] colors = 'k' self.contours.append(self.ax.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)) elif type == 1: self.contours.append(self.ax.contourf(X1, X2, Z, 10, cmap=matplotlib.cm.bone, origin='lower', alpha=0.85)) self.contours.append(self.ax.contour(X1, X2, Z, [0.0], colors='k', linestyles=['solid'])) else: raise ValueError("surface type unknown") class ControllBar(object): def __init__(self, root, controller): fm = Tk.Frame(root) kernel_group = Tk.Frame(fm) Tk.Radiobutton(kernel_group, text="Linear", variable=controller.kernel, value=0, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(kernel_group, text="RBF", variable=controller.kernel, value=1, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(kernel_group, text="Poly", variable=controller.kernel, value=2, command=controller.refit).pack(anchor=Tk.W) kernel_group.pack(side=Tk.LEFT) valbox = Tk.Frame(fm) controller.complexity = Tk.StringVar() controller.complexity.set("1.0") c = Tk.Frame(valbox) Tk.Label(c, text="C:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(c, width=6, textvariable=controller.complexity).pack( side=Tk.LEFT) c.pack() controller.gamma = Tk.StringVar() controller.gamma.set("0.01") g = Tk.Frame(valbox) Tk.Label(g, text="gamma:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(g, width=6, textvariable=controller.gamma).pack(side=Tk.LEFT) g.pack() controller.degree = Tk.StringVar() controller.degree.set("3") d = Tk.Frame(valbox) Tk.Label(d, text="degree:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(d, width=6, textvariable=controller.degree).pack(side=Tk.LEFT) d.pack() controller.coef0 = Tk.StringVar() controller.coef0.set("0") r = Tk.Frame(valbox) Tk.Label(r, text="coef0:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(r, width=6, textvariable=controller.coef0).pack(side=Tk.LEFT) r.pack() valbox.pack(side=Tk.LEFT) cmap_group = Tk.Frame(fm) Tk.Radiobutton(cmap_group, text="Hyperplanes", variable=controller.surface_type, value=0, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(cmap_group, text="Surface", variable=controller.surface_type, value=1, command=controller.refit).pack(anchor=Tk.W) cmap_group.pack(side=Tk.LEFT) train_button = Tk.Button(fm, text='Fit', width=5, command=controller.fit) train_button.pack() fm.pack(side=Tk.LEFT) Tk.Button(fm, text='Clear', width=5, command=controller.clear_data).pack(side=Tk.LEFT) def get_parser(): from optparse import OptionParser op = OptionParser() op.add_option("--output", action="store", type="str", dest="output", help="Path where to dump data.") return op def main(argv): op = get_parser() opts, args = op.parse_args(argv[1:]) root = Tk.Tk() model = Model() controller = Controller(model) root.wm_title("Scikit-learn Libsvm GUI") view = View(root, controller) model.add_observer(view) Tk.mainloop() if opts.output: model.dump_svmlight_file(opts.output) if __name__ == "__main__": main(sys.argv)
bsd-3-clause
saiwing-yeung/scikit-learn
examples/cluster/plot_dict_face_patches.py
337
2747
""" Online learning of a dictionary of parts of faces ================================================== This example uses a large dataset of faces to learn a set of 20 x 20 images patches that constitute faces. From the programming standpoint, it is interesting because it shows how to use the online API of the scikit-learn to process a very large dataset by chunks. The way we proceed is that we load an image at a time and extract randomly 50 patches from this image. Once we have accumulated 500 of these patches (using 10 images), we run the `partial_fit` method of the online KMeans object, MiniBatchKMeans. The verbose setting on the MiniBatchKMeans enables us to see that some clusters are reassigned during the successive calls to partial-fit. This is because the number of patches that they represent has become too low, and it is better to choose a random new cluster. """ print(__doc__) import time import matplotlib.pyplot as plt import numpy as np from sklearn import datasets from sklearn.cluster import MiniBatchKMeans from sklearn.feature_extraction.image import extract_patches_2d faces = datasets.fetch_olivetti_faces() ############################################################################### # Learn the dictionary of images print('Learning the dictionary... ') rng = np.random.RandomState(0) kmeans = MiniBatchKMeans(n_clusters=81, random_state=rng, verbose=True) patch_size = (20, 20) buffer = [] index = 1 t0 = time.time() # The online learning part: cycle over the whole dataset 6 times index = 0 for _ in range(6): for img in faces.images: data = extract_patches_2d(img, patch_size, max_patches=50, random_state=rng) data = np.reshape(data, (len(data), -1)) buffer.append(data) index += 1 if index % 10 == 0: data = np.concatenate(buffer, axis=0) data -= np.mean(data, axis=0) data /= np.std(data, axis=0) kmeans.partial_fit(data) buffer = [] if index % 100 == 0: print('Partial fit of %4i out of %i' % (index, 6 * len(faces.images))) dt = time.time() - t0 print('done in %.2fs.' % dt) ############################################################################### # Plot the results plt.figure(figsize=(4.2, 4)) for i, patch in enumerate(kmeans.cluster_centers_): plt.subplot(9, 9, i + 1) plt.imshow(patch.reshape(patch_size), cmap=plt.cm.gray, interpolation='nearest') plt.xticks(()) plt.yticks(()) plt.suptitle('Patches of faces\nTrain time %.1fs on %d patches' % (dt, 8 * len(faces.images)), fontsize=16) plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23) plt.show()
bsd-3-clause
allenlavoie/tensorflow
tensorflow/contrib/learn/python/learn/estimators/kmeans.py
15
11087
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of k-means clustering on top of `Estimator` API (deprecated). This module is deprecated. Please use @{tf.contrib.factorization.KMeansClustering} instead of @{tf.contrib.learn.KMeansClustering}. It has a similar interface, but uses the @{tf.estimator.Estimator} API instead of @{tf.contrib.learn.Estimator}. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy as np from tensorflow.contrib.factorization.python.ops import clustering_ops from tensorflow.python.training import training_util from tensorflow.contrib.learn.python.learn.estimators import estimator from tensorflow.contrib.learn.python.learn.estimators.model_fn import ModelFnOps from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops.control_flow_ops import with_dependencies from tensorflow.python.platform import tf_logging as logging from tensorflow.python.summary import summary from tensorflow.python.training import session_run_hook from tensorflow.python.training.session_run_hook import SessionRunArgs from tensorflow.python.util.deprecation import deprecated _USE_TF_CONTRIB_FACTORIZATION = ( 'Please use tf.contrib.factorization.KMeansClustering instead of' ' tf.contrib.learn.KMeansClustering. It has a similar interface, but uses' ' the tf.estimator.Estimator API instead of tf.contrib.learn.Estimator.') class _LossRelativeChangeHook(session_run_hook.SessionRunHook): """Stops when the change in loss goes below a tolerance.""" def __init__(self, tolerance): """Initializes _LossRelativeChangeHook. Args: tolerance: A relative tolerance of change between iterations. """ self._tolerance = tolerance self._prev_loss = None def begin(self): self._loss_tensor = ops.get_default_graph().get_tensor_by_name( KMeansClustering.LOSS_OP_NAME + ':0') assert self._loss_tensor is not None def before_run(self, run_context): del run_context return SessionRunArgs( fetches={KMeansClustering.LOSS_OP_NAME: self._loss_tensor}) def after_run(self, run_context, run_values): loss = run_values.results[KMeansClustering.LOSS_OP_NAME] assert loss is not None if self._prev_loss is not None: relative_change = (abs(loss - self._prev_loss) / (1 + abs(self._prev_loss))) if relative_change < self._tolerance: run_context.request_stop() self._prev_loss = loss class _InitializeClustersHook(session_run_hook.SessionRunHook): """Initializes clusters or waits for cluster initialization.""" def __init__(self, init_op, is_initialized_op, is_chief): self._init_op = init_op self._is_chief = is_chief self._is_initialized_op = is_initialized_op def after_create_session(self, session, _): assert self._init_op.graph == ops.get_default_graph() assert self._is_initialized_op.graph == self._init_op.graph while True: try: if session.run(self._is_initialized_op): break elif self._is_chief: session.run(self._init_op) else: time.sleep(1) except RuntimeError as e: logging.info(e) def _parse_tensor_or_dict(features): """Helper function to parse features.""" if isinstance(features, dict): keys = sorted(features.keys()) with ops.colocate_with(features[keys[0]]): features = array_ops.concat([features[k] for k in keys], 1) return features def _kmeans_clustering_model_fn(features, labels, mode, params, config): """Model function for KMeansClustering estimator.""" assert labels is None, labels (all_scores, model_predictions, losses, is_initialized, init_op, training_op) = clustering_ops.KMeans( _parse_tensor_or_dict(features), params.get('num_clusters'), initial_clusters=params.get('training_initial_clusters'), distance_metric=params.get('distance_metric'), use_mini_batch=params.get('use_mini_batch'), mini_batch_steps_per_iteration=params.get( 'mini_batch_steps_per_iteration'), random_seed=params.get('random_seed'), kmeans_plus_plus_num_retries=params.get( 'kmeans_plus_plus_num_retries')).training_graph() incr_step = state_ops.assign_add(training_util.get_global_step(), 1) loss = math_ops.reduce_sum(losses, name=KMeansClustering.LOSS_OP_NAME) summary.scalar('loss/raw', loss) training_op = with_dependencies([training_op, incr_step], loss) predictions = { KMeansClustering.ALL_SCORES: all_scores[0], KMeansClustering.CLUSTER_IDX: model_predictions[0], } eval_metric_ops = {KMeansClustering.SCORES: loss} training_hooks = [_InitializeClustersHook( init_op, is_initialized, config.is_chief)] relative_tolerance = params.get('relative_tolerance') if relative_tolerance is not None: training_hooks.append(_LossRelativeChangeHook(relative_tolerance)) return ModelFnOps( mode=mode, predictions=predictions, eval_metric_ops=eval_metric_ops, loss=loss, train_op=training_op, training_hooks=training_hooks) # TODO(agarwal,ands): support sharded input. class KMeansClustering(estimator.Estimator): """An Estimator for K-Means clustering. THIS CLASS IS DEPRECATED. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for general migration instructions. """ SQUARED_EUCLIDEAN_DISTANCE = clustering_ops.SQUARED_EUCLIDEAN_DISTANCE COSINE_DISTANCE = clustering_ops.COSINE_DISTANCE RANDOM_INIT = clustering_ops.RANDOM_INIT KMEANS_PLUS_PLUS_INIT = clustering_ops.KMEANS_PLUS_PLUS_INIT SCORES = 'scores' CLUSTER_IDX = 'cluster_idx' CLUSTERS = 'clusters' ALL_SCORES = 'all_scores' LOSS_OP_NAME = 'kmeans_loss' @deprecated(None, _USE_TF_CONTRIB_FACTORIZATION) def __init__(self, num_clusters, model_dir=None, initial_clusters=RANDOM_INIT, distance_metric=SQUARED_EUCLIDEAN_DISTANCE, random_seed=0, use_mini_batch=True, mini_batch_steps_per_iteration=1, kmeans_plus_plus_num_retries=2, relative_tolerance=None, config=None): """Creates a model for running KMeans training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. initial_clusters: specifies how to initialize the clusters for training. See clustering_ops.kmeans for the possible values. distance_metric: the distance metric used for clustering. See clustering_ops.kmeans for the possible values. random_seed: Python integer. Seed for PRNG used to initialize centers. use_mini_batch: If true, use the mini-batch k-means algorithm. Else assume full batch. mini_batch_steps_per_iteration: number of steps after which the updated cluster centers are synced back to a master copy. See clustering_ops.py for more details. kmeans_plus_plus_num_retries: For each point that is sampled during kmeans++ initialization, this parameter specifies the number of additional points to draw from the current distribution before selecting the best. If a negative value is specified, a heuristic is used to sample O(log(num_to_sample)) additional points. relative_tolerance: A relative tolerance of change in the loss between iterations. Stops learning if the loss changes less than this amount. Note that this may not work correctly if use_mini_batch=True. config: See Estimator """ params = {} params['num_clusters'] = num_clusters params['training_initial_clusters'] = initial_clusters params['distance_metric'] = distance_metric params['random_seed'] = random_seed params['use_mini_batch'] = use_mini_batch params['mini_batch_steps_per_iteration'] = mini_batch_steps_per_iteration params['kmeans_plus_plus_num_retries'] = kmeans_plus_plus_num_retries params['relative_tolerance'] = relative_tolerance super(KMeansClustering, self).__init__( model_fn=_kmeans_clustering_model_fn, params=params, model_dir=model_dir, config=config) @deprecated(None, _USE_TF_CONTRIB_FACTORIZATION) def predict_cluster_idx(self, input_fn=None): """Yields predicted cluster indices.""" key = KMeansClustering.CLUSTER_IDX results = super(KMeansClustering, self).predict( input_fn=input_fn, outputs=[key]) for result in results: yield result[key] @deprecated(None, _USE_TF_CONTRIB_FACTORIZATION) def score(self, input_fn=None, steps=None): """Predict total sum of distances to nearest clusters. Note that this function is different from the corresponding one in sklearn which returns the negative of the sum of distances. Args: input_fn: see predict. steps: see predict. Returns: Total sum of distances to nearest clusters. """ return np.sum( self.evaluate( input_fn=input_fn, steps=steps)[KMeansClustering.SCORES]) @deprecated(None, _USE_TF_CONTRIB_FACTORIZATION) def transform(self, input_fn=None, as_iterable=False): """Transforms each element to distances to cluster centers. Note that this function is different from the corresponding one in sklearn. For SQUARED_EUCLIDEAN distance metric, sklearn transform returns the EUCLIDEAN distance, while this function returns the SQUARED_EUCLIDEAN distance. Args: input_fn: see predict. as_iterable: see predict Returns: Array with same number of rows as x, and num_clusters columns, containing distances to the cluster centers. """ key = KMeansClustering.ALL_SCORES results = super(KMeansClustering, self).predict( input_fn=input_fn, outputs=[key], as_iterable=as_iterable) if not as_iterable: return results[key] else: return results @deprecated(None, _USE_TF_CONTRIB_FACTORIZATION) def clusters(self): """Returns cluster centers.""" return super(KMeansClustering, self).get_variable_value(self.CLUSTERS)
apache-2.0
chrhartm/SORN
common/sorn_stats.py
2
74077
from __future__ import division from pylab import * import utils utils.backup(__file__) from stats import AbstractStat from stats import HistoryStat from stats import _getvar from common.sources import TrialSource from utils.lstsq_reg import lstsq_reg import cPickle as pickle import gzip def load_source(name,c): try: filename = c.logfilepath+name+".pickle" sourcefile = gzip.open(filename,"r") except IOError: # Cluster filename = c.logfilepath+\ name+"_%s_%.3f.pickle"\ %(c.cluster.vary_param,\ c.cluster.current_param) sourcefile = gzip.open(filename,"r") source = pickle.load(sourcefile) if isinstance(source,TrialSource): source = source.source return source class CounterStat(AbstractStat): def __init__(self): self.name = 'num_steps' self.collection = "reduce" def start(self,c,obj): c[self.name] = 0.0 # Everything needs to be a float :-/ def add(self,c,obj): c[self.name] += 1 def report(self,c,obj): return array(c[self.name]) # And an array :-/ # By making CounterStat a little longer we can make ClearCounterStat a # lot shorter class ClearCounterStat(CounterStat): def __init__(self): self.name = 'counter' self.collection = "ignore" (self.clear,self.start) = (self.start,self.clear) class PopulationVariance(AbstractStat): def __init__(self): self.name = 'pop_var' self.collection = 'reduce' def clear(self,c,obj): N = obj.c.N_e c.pop_var = zeros(N+1) def add(self,c,obj): n = sum(obj.x) c.pop_var[n] += 1.0 def report(self,c,obj): return c.pop_var class ActivityStat(AbstractStat): """ Gathers the state of the network at each step If the parameter only_last is set, only the first and last steps are collected """ def __init__(self): self.name = 'activity' self.collection = 'gather' def clear(self,c,sorn): if sorn.c.stats.has_key('only_last'): c.activity = zeros(sorn.c.stats.only_last\ +sorn.c.stats.only_last) else: c.activity = zeros(sorn.c.N_steps) self.step = 0 def add(self,c,sorn): if sorn.c.stats.has_key('only_last'): new_step = self.step - (sorn.c.N_steps\ -sorn.c.stats.only_last) if new_step >= 0: c.activity[new_step+sorn.c.stats.only_last] \ = sum(sorn.x)/sorn.c.N_e elif self.step % (sorn.c.N_steps\ //sorn.c.stats.only_last) == 0: c.activity[self.step//(sorn.c.N_steps\ //sorn.c.stats.only_last)] = sum(sorn.x)/sorn.c.N_e else: c.activity[self.step] = sum(sorn.x)/sorn.c.N_e self.step += 1 def report(self,c,sorn): return c.activity class InputIndexStat(AbstractStat): """ Gathers the index of the input at each step """ def __init__(self): self.name = 'InputIndex' self.collection = 'gather' def clear(self,c,sorn): if sorn.c.stats.has_key('only_last'): c.inputindex = zeros(sorn.c.stats.only_last\ +sorn.c.stats.only_last) else: c.inputindex = zeros(sorn.c.N_steps) self.step = 0 def add(self,c,sorn): if sorn.c.stats.has_key('only_last'): new_step = self.step - (sorn.c.N_steps\ -sorn.c.stats.only_last) if new_step >= 0: c.inputindex[new_step+sorn.c.stats.only_last] \ = sorn.source.global_index() elif self.step % (sorn.c.N_steps\ //sorn.c.stats.only_last) == 0: c.inputindex[self.step//(sorn.c.N_steps\ //sorn.c.stats.only_last)] = sorn.source.global_index() else: c.inputindex[self.step] = sorn.source.global_index() self.step += 1 def report(self,c,sorn): return c.inputindex class WordListStat(AbstractStat): # OLD! use pickle of source instead! def __init__(self): self.name = 'WordList' self.collection = 'gather' def report(self,c,sorn): return sorn.c.words class InputUnitsStat(AbstractStat): def __init__(self): self.name = 'InputUnits' self.collection = 'gather' def report(self,c,sorn): input_units = where(sum(sorn.W_eu.get_synapses(),1)>0)[0] # to make them equal in size tmp = array([z in input_units for z in arange(sorn.c.N_e)]) return tmp+0 # cast as double class NormLastStat(AbstractStat): ''' This is a helper Stat that computes the normalized last spikes and input indices ''' def __init__(self): self.name = 'NormLast' self.collection = 'gather' def report(self,c,sorn): steps_plastic = sorn.c.steps_plastic steps_noplastic_train = sorn.c.steps_noplastic_train steps_noplastic_test = sorn.c.steps_noplastic_test plastic_train = steps_plastic+steps_noplastic_train input_spikes = c.spikes[:,steps_plastic:plastic_train] input_index = c.inputindex[steps_plastic:plastic_train] # Filter out empty states input_spikes = input_spikes[:,input_index != -1] input_index = input_index[input_index != -1] if sorn.c.stats.has_key('only_last'): N_comparison = sorn.c.stats.only_last else: N_comparison = 2500 assert(N_comparison > 0) assert(N_comparison <= steps_noplastic_test \ and N_comparison <= steps_noplastic_train) maxindex = int(max(input_index)) # Only use spikes that occured at the end of learning and spont last_input_spikes = input_spikes[:,-N_comparison:] last_input_index = input_index[-N_comparison:] # Get the minimal occurence of an index in the last steps min_letter_count = inf for i in range(maxindex+1): tmp = sum(last_input_index == i) if min_letter_count > tmp: min_letter_count = tmp # For each index, take the same number of states from the # end phase of learning to avoid a bias in comparing states norm_last_input_spikes = np.zeros((shape(last_input_spikes)[0],\ min_letter_count*(maxindex+1))) norm_last_input_index = np.zeros(min_letter_count*(maxindex+1)) for i in range(maxindex+1): indices = find(last_input_index == i) norm_last_input_spikes[:,min_letter_count*i\ : min_letter_count*(i+1)]\ = last_input_spikes[:, indices[-min_letter_count:]] norm_last_input_index[min_letter_count*i\ : min_letter_count*(i+1)]\ = last_input_index[indices[-min_letter_count:]] # Shuffle to avoid argmin-problem of selecting only first match indices = arange(shape(norm_last_input_index)[0]) shuffle(indices) norm_last_input_index = norm_last_input_index[indices] norm_last_input_spikes = norm_last_input_spikes[:,indices] c.norm_last_input_index = norm_last_input_index c.norm_last_input_spikes = norm_last_input_spikes c.maxindex = maxindex c.N_comparison = N_comparison to_return = array([float(N_comparison)]) return to_return class SpontPatternStat(AbstractStat): """ Computes the frequency of each pattern in the spontaneous activity """ def __init__(self): self.name = 'SpontPattern' self.collection = 'gather' def report(self,c,sorn): source_plastic = load_source("source_plastic",sorn.c) steps_noplastic_test = sorn.c.steps_noplastic_test spont_spikes = c.spikes[:,-steps_noplastic_test:] norm_last_input_index = c.norm_last_input_index norm_last_input_spikes = c.norm_last_input_spikes maxindex = c.maxindex N_comparison = c.N_comparison last_spont_spikes = spont_spikes[:,-N_comparison:] # Remove silent periods from spontspikes last_spont_spikes = last_spont_spikes[:,sum(last_spont_spikes,0)>0] N_comp_spont = shape(last_spont_spikes)[1] # Find for each spontaneous state the evoked state with the # smallest hamming distance and store the corresponding index similar_input = zeros(N_comp_spont) for i in xrange(N_comp_spont): most_similar = argmin(sum(abs(norm_last_input_spikes.T\ -last_spont_spikes[:,i]),axis=1)) similar_input[i] = norm_last_input_index[most_similar] # Count the number of spontaneous states for each index and plot index = range(maxindex+1) if self.collection == 'gatherv': adding = 2 else: adding = 1 pattern_freqs = zeros((2,maxindex+adding)) barcolor = [] for i in index: pattern_freqs[0,i] = sum(similar_input==index[i]) # Compare patterns # Forward patterns ([0,1,2,3],[4,5,6,7],...) patterns = array([arange(len(w))+source_plastic.glob_ind[i] \ for (i,w) in enumerate(source_plastic.words)]) rev_patterns = array([x[::-1] for x in patterns]) maxlen = max([len(x) for x in patterns]) # Also get the reversed patterns if maxlen>1: # Single letters can't be reversed allpatterns = array(patterns.tolist()+rev_patterns.tolist()) else: allpatterns = array(patterns.tolist()) for (i,p) in enumerate(allpatterns): patternlen = len(p) for j in xrange(N_comp_spont-maxlen): if all(similar_input[j:j+patternlen] == p): pattern_freqs[1,i] += 1 # Marker for end of freqs if self.collection == 'gatherv': pattern_freqs[:,-1] = -1 c.similar_input = similar_input return(pattern_freqs) class SpontTransitionStat(AbstractStat): def __init__(self): self.name = 'SpontTransition' self.collection = 'gather' def report(self,c,sorn): similar_input = c.similar_input # from SpontPatternStat maxindex = c.maxindex transitions = np.zeros((maxindex+1,maxindex+1)) for (i_from, i_to) in zip(similar_input[:-1],similar_input[1:]): transitions[i_to,i_from] += 1 return transitions class SpontIndexStat(AbstractStat): def __init__(self): self.name = 'SpontIndex' self.collection = 'gather' def report (self,c,sorn): return c.similar_input class BayesStat(AbstractStat): def __init__(self,pred_pos = 0): self.name = 'Bayes' self.collection = 'gather' self.pred_pos = pred_pos # steps before M/N def clear(self,c,sorn): pass # If raw_prediction is input to M/N neurons, this is needed #~ self.M_neurons = where(sorn.W_eu.W[:, #~ sorn.source.source.lookup['M']]==1)[0] #~ self.N_neurons = where(sorn.W_eu.W[:, #~ sorn.source.source.lookup['N']]==1)[0] def report(self,c,sorn): ### Prepare spike train matrices for training and testing # Separate training and test data according to steps source_plastic = load_source("source_plastic",sorn.c) steps_plastic = sorn.c.steps_plastic N_train_steps = sorn.c.steps_noplastic_train N_inputtrain_steps = steps_plastic + N_train_steps N_test_steps = sorn.c.steps_noplastic_test burnin = 3000 # Transpose because this is the way they are in test_bayes.py Xtrain = c.spikes[:,steps_plastic+burnin:N_inputtrain_steps].T Xtest = c.spikes[:,N_inputtrain_steps:].T assert(shape(Xtest)[0] == N_test_steps) inputi_train = c.inputindex[steps_plastic+burnin :N_inputtrain_steps] assert(shape(Xtrain)[0] == shape(inputi_train)[0]) inputi_test = c.inputindex[N_inputtrain_steps:] assert(shape(inputi_test)[0]== N_test_steps) N_fracs = len(sorn.c.frac_A) # Filter out empty states if isinstance(sorn.source,TrialSource): # if TrialSource source = sorn.source.source else: source = sorn.source Xtrain = Xtrain[inputi_train != -1,:] inputi_train = inputi_train[inputi_train != -1] Xtest = Xtest[inputi_test != -1,:] inputi_test = inputi_test[inputi_test != -1] # Following snipplet modified from sorn_stats spont_stat # Get the minimal occurence of an index in the last steps maxindex = int(max(inputi_train)) min_letter_count = inf for i in range(maxindex+1): tmp = sum(inputi_train == i) if min_letter_count > tmp: min_letter_count = tmp # For each index, take the same number of states from the # end phase of learning to avoid a bias in comparing states norm_Xtrain = np.zeros((min_letter_count*(maxindex+1), shape(Xtrain)[1])) norm_inputi_train = np.zeros(min_letter_count*(maxindex+1)) for i in range(maxindex+1): indices = find(inputi_train == i) norm_Xtrain[min_letter_count*i : min_letter_count*(i+1), :]\ = Xtrain[indices[-min_letter_count:],:] norm_inputi_train[min_letter_count*i : min_letter_count*(i+1)]\ = inputi_train[indices[-min_letter_count:]] Xtrain = norm_Xtrain inputi_train = norm_inputi_train noinput_units = where(sum(sorn.W_eu.W,1)==0)[0] if sorn.c.stats.bayes_noinput: Xtrain_noinput = Xtrain[:,noinput_units] Xtest_noinput = Xtest[:,noinput_units] else: Xtrain_noinput = Xtrain Xtest_noinput = Xtest assert(source_plastic.words[0][0]=="A" and source_plastic.words[1][0]=="B") A_index = source_plastic.glob_ind[0] # start of first word B_index = source_plastic.glob_ind[1] # start of second word # position from which to predict end of word pred_pos = len(source_plastic.words[0])-1-self.pred_pos assert(pred_pos>=0 and pred_pos <= source_plastic.global_range()) R = np.zeros((2,shape(inputi_train)[0])) R[0,:] = inputi_train == A_index+pred_pos R[1,:] = inputi_train == B_index+pred_pos if sorn.c.stats.relevant_readout: Xtrain_relevant = Xtrain_noinput[((inputi_train == A_index+pred_pos) + (inputi_train == B_index+pred_pos))>0,:] R_relevant = R[:,((inputi_train == A_index+pred_pos) + (inputi_train == B_index+pred_pos))>0] classifier = lstsq_reg(Xtrain_relevant,R_relevant.T, sorn.c.stats.lstsq_mue) else: classifier = lstsq_reg(Xtrain_noinput,R.T, sorn.c.stats.lstsq_mue) #~ # No real difference between LogReg, BayesRidge and my thing #~ # If you do this, comment out raw_predictions further down #~ from sklearn import linear_model #~ clf0 = linear_model.LogisticRegression(C=1)#BayesianRidge() #~ clf1 = linear_model.LogisticRegression(C=1)#BayesianRidge() #~ clf0.fit(Xtrain_noinput,R.T[:,0]) #~ clf1.fit(Xtrain_noinput,R.T[:,1]) #~ raw_predictions = vstack((clf0.predict_proba(Xtest_noinput)[:,1] #~ ,clf1.predict_proba(Xtest_noinput)[:,1])).T # predict #~ raw_predictions = Xtest.dot(classifier) #~ # comment this out if you use sklearn raw_predictions = Xtest_noinput.dot(classifier) #~ # Historical stuff #~ # Raw predictions = total synaptic input to M/N neurons #~ raw_predictions[1:,0] = sum((sorn.W_ee*Xtest[:-1].T)[ #~ self.M_neurons],0) #~ raw_predictions[1:,1] = sum((sorn.W_ee*Xtest[:-1].T)[ #~ self.N_neurons],0) #~ # Raw predictions = total activation of M/N neurons #~ raw_predictions[:,0] = sum(Xtest.T[self.M_neurons],0) #~ raw_predictions[:,1] = sum(Xtest.T[self.N_neurons],0) #~ # for testing: sum(raw_predictions[indices,0])>indices+-1,2,3 letters_for_frac = ['B'] # Because alphabet is sorted alphabetically, this list will # have the letters corresponding to the list frac_A for l in source.alphabet: if not ((l=='A') or (l=='B') or (l=='M') or (l=='N') or (l=='X') or (l=='_')): letters_for_frac.append(l) letters_for_frac.append('A') output_drive = np.zeros((N_fracs,2)) output_std = np.zeros((N_fracs,2)) decisions = np.zeros((N_fracs,2)) denom = np.zeros(N_fracs) for (s_word,s_index) in zip(source.words,source.glob_ind): i = ''.join(letters_for_frac).find(s_word[0]) indices = find(inputi_test==s_index+pred_pos) # A predicted output_drive[i,0] += mean(raw_predictions[indices,0]) # B predicted output_drive[i,1] += mean(raw_predictions[indices,1]) decisions[i,0] += mean(raw_predictions[indices,0]>\ raw_predictions[indices,1]) decisions[i,1] += mean(raw_predictions[indices,1]>=\ raw_predictions[indices,0]) output_std[i,0] += std(raw_predictions[indices,0]) output_std[i,1] += std(raw_predictions[indices,1]) denom[i] += 1 # Some words occur more than once output_drive[:,0] /= denom output_drive[:,1] /= denom output_std[:,0] /= denom output_std[:,1] /= denom decisions[:,0] /= denom decisions[:,1] /= denom # for other stats (e.g. SpontBayesStat) c.pred_pos = pred_pos c.Xtest = Xtest c.raw_predictions = raw_predictions c.inputi_test = inputi_test c.letters_for_frac = letters_for_frac c.classifier = classifier c.noinput_units = noinput_units to_return = hstack((output_drive,output_std,decisions)) return to_return class AttractorDynamicsStat(AbstractStat): """ This stat tracks the distance between output gains during the input presentation to determine whether the decision is based on attractor dynamics """ def __init__(self): self.name = 'AttractorDynamics' self.collection = 'gather' def report(self,c,sorn): # Read stuff in letters_for_frac = c.letters_for_frac if isinstance(sorn.source,TrialSource): # if TrialSource source = sorn.source.source else: source = sorn.source word_length = min([len(x) for x in source.words]) N_words = len(source.words) N_fracs = len(sorn.c.frac_A) bayes_stat = None for stat in sorn.stats.methods: if stat.name is 'Bayes': bayes_stat = stat break assert(bayes_stat is not None) pred_pos_old = bayes_stat.pred_pos #output_dist = np.zeros((word_length-1,N_fracs)) output_dist = np.zeros((word_length,N_fracs)) min_trials = inf for i in range(int(max(c.inputi_test))+1): tmp = sum(c.inputi_test == i) if min_trials > tmp: min_trials = tmp decisions = np.zeros((N_words,word_length,min_trials),\ dtype=np.bool) seq_count = np.zeros((N_words,4)) for (p,pp) in enumerate(arange(0,word_length)): bayes_stat.pred_pos = pp bayes_stat.report(c,sorn) pred_pos = c.pred_pos raw_predictions = c.raw_predictions inputi_test = c.inputi_test #~ summed = abs(raw_predictions[:,0])+abs(raw_predictions[:,1]) #~ summed[summed<1e-10] = 1 # if predicted 0, leave at 0 #~ raw_predictions[:,0] /= summed #~ raw_predictions[:,1] /= summed denom = np.zeros((N_fracs)) for (w,(s_word,s_index)) in enumerate(zip(source.words, source.glob_ind)): i = ''.join(letters_for_frac).find(s_word[0]) indices = find(inputi_test==s_index+pred_pos) tmp = abs(raw_predictions[indices,0]- raw_predictions[indices,1]) output_dist[p,i] += mean(tmp) decisions[w,p,:] = raw_predictions[ indices[-min_trials:],0]>\ raw_predictions[indices[-min_trials:],1] denom[i] += 1 output_dist[p,:] /= denom for i in range(N_words): # Full-length 1s to be expected seq_count[i,0] = ((sum(decisions[i])/(1.*min_trials* word_length))**(word_length))*min_trials # Actual 1-series seq_count[i,1] = sum(sum(decisions[i],0)==word_length) # Same for 0-series seq_count[i,2] = ((1-(sum(decisions[i])/(1.*min_trials* word_length)))**(word_length))*min_trials seq_count[i,3] = sum(sum(decisions[i],0)==0) bayes_stat.pred_pos = pred_pos_old bayes_stat.report(c,sorn) return output_dist class OutputDistStat(AbstractStat): """ This stat reports the distance between output gains as an indicator for whether the decision is based on chance or on attractor dynamics """ def __init__(self): self.name = 'OutputDist' self.collection = 'gather' def report(self,c,sorn): # Read stuff in letters_for_frac = c.letters_for_frac raw_predictions = c.raw_predictions inputi_test = c.inputi_test pred_pos = c.pred_pos if isinstance(sorn.source,TrialSource): # if TrialSource source = sorn.source.source else: source = sorn.source N_fracs = len(sorn.c.frac_A) summed = abs(raw_predictions[:,0])+abs(raw_predictions[:,1]) summed[summed<1e-10] = 1 # if predicted 0, leave at 0 raw_predictions[:,0] /= summed raw_predictions[:,1] /= summed output_dist = np.zeros((N_fracs)) output_std = np.zeros((N_fracs)) denom = np.zeros((N_fracs)) for (s_word,s_index) in zip(source.words,source.glob_ind): i = ''.join(letters_for_frac).find(s_word[0]) indices = find(inputi_test==s_index+pred_pos) tmp = abs(raw_predictions[indices,0]- raw_predictions[indices,1]) output_dist[i] += mean(tmp) output_std[i] += std(tmp) denom[i] += 1 output_dist /= denom output_std /= denom to_return = vstack((output_dist,output_std)) return to_return class TrialBayesStat(AbstractStat): """ This stat looks at the interaction of spontaneous activity before stimulus onset with the final prediction index: int Word index (global) for which prediction is done """ def __init__(self): self.name = 'TrialBayes' self.collection = 'gather' def report(self,c,sorn): # Read stuff in STA_window = 50 pred_pos = c.pred_pos classifier_old = c.classifier noinput_units = c.noinput_units steps_plastic = sorn.c.steps_plastic N_train_steps = sorn.c.steps_noplastic_train N_inputtrain_steps = steps_plastic + N_train_steps N_test_steps = sorn.c.steps_noplastic_test # Transpose because this is the way they are in test_bayes.py # Use all neurons because we're predicting from spont activity Xtest = c.spikes[:,N_inputtrain_steps:].T inputi_test = c.inputindex[N_inputtrain_steps:] N_exc = shape(Xtest)[1] if isinstance(sorn.source,TrialSource): # if TrialSource source = sorn.source.source else: raise NotImplementedError # select middle word index = source.glob_ind[1+(shape(source.glob_ind)[0]-3)//2] forward_pred = sorn.c.stats.forward_pred start_indices = find(inputi_test==index) # * is element-wise AND start_indices = start_indices[(start_indices>STA_window) * ((start_indices+pred_pos+forward_pred)<shape(inputi_test)[0])] N_samples = shape(start_indices)[0] pred_indices = find(inputi_test==(index+pred_pos)) pred_indices = pred_indices[(pred_indices>=start_indices[0])* ((pred_indices+forward_pred)<shape(inputi_test)[0])] assert(N_samples == shape(pred_indices)[0]) if sorn.c.stats.bayes_noinput: raw_predictions = Xtest[:,noinput_units].dot(classifier_old) else: raw_predictions = Xtest.dot(classifier_old) predictions = raw_predictions[pred_indices,:] # Two different baselines #~ test_base = ones((shape(Xtest)[0],1)) test_base = Xtest.copy() shuffle(test_base) # without shuffle, identical predictions test_base = hstack((test_base,ones((shape(Xtest)[0],1)))) # Add bias term to exclude effects of varability N_exc += 1 Xtest = hstack((Xtest,ones((shape(Xtest)[0],1)))) # Divide into train and test set predictions_train = predictions[:N_samples//2] predictions_test = predictions[N_samples//2:] train_A = predictions_train[:,0]>predictions_train[:,1] train_B = train_A==False train_A = find(train_A==True) train_B = find(train_B==True) # This case is filtered out during plotting if not(shape(train_A)[0]>0 and shape(train_B)[0]>0): return np.ones((2,STA_window))*-1 agreement_lstsq = np.zeros(STA_window) agreement_base = np.zeros(STA_window) # This maps 0/1 spikes to -1/1 spikes for later * comparison predtrain_lstsq = (predictions_train[:,0]>\ predictions_train[:,1])*2-1 predtest_lstsq = (predictions_test[:,0]>\ predictions_test[:,1])*2-1 # Prediction with spontaneous activity for i in range(-STA_window,0): classifier_lstsq = lstsq_reg(Xtest[\ start_indices[:N_samples//2]+i+forward_pred,:],\ predtrain_lstsq,sorn.c.stats.lstsq_mue) predictions_lstsq = (Xtest[start_indices[N_samples//2:]+i\ +forward_pred,:]).dot(classifier_lstsq) # this is where the -1/1 comes in agreement_lstsq[i] = sum((predictions_lstsq*predtest_lstsq)\ >0)/(1.*N_samples//2) # Baseline prediction (loop is unnecessary and for similarity) for i in range(-STA_window,0): classifier_base = lstsq_reg(test_base[\ start_indices[:N_samples//2]+i+forward_pred,:],\ predtrain_lstsq,sorn.c.stats.lstsq_mue) predictions_base = (test_base[start_indices[N_samples//2:]+i\ +forward_pred,:]).dot(classifier_base) agreement_base[i] = sum((predictions_base*predtest_lstsq)\ >0)/(1.*N_samples//2) # STA - not used trials = np.zeros((N_samples,STA_window,N_exc)) for i in range(N_samples): trials[i,:,:] = Xtest[start_indices[i]-STA_window\ +forward_pred:start_indices[i]+forward_pred,:] STA_A = mean(trials[train_A,:,:],0) STA_B = mean(trials[train_B,:,:],0) N_test = N_samples-N_samples//2 overlap_A = np.zeros((N_test,STA_window,N_exc)) overlap_B = np.zeros((N_test,STA_window,N_exc)) for i in range(N_samples//2,N_samples): overlap_A[i-N_samples//2] = trials[i]*STA_A overlap_B[i-N_samples//2] = trials[i]*STA_B agreement = np.zeros(STA_window) pred_gain_A = predictions_test[:,0]>predictions_test[:,1] for i in range(STA_window): pred_STA_A = sum(overlap_A[:,i,:],1)>sum(overlap_B[:,i,:],1) agreement[i] = sum(pred_gain_A == pred_STA_A) agreement /= float(shape(pred_gain_A)[0]) return vstack((agreement_base, agreement_lstsq)) class SpontBayesStat(AbstractStat): def __init__(self): self.name = 'SpontBayes' self.collection = 'gather' def report(self,c,sorn): # Read stuff in pred_pos = c.pred_pos inputi_test = c.inputi_test raw_predictions = c.raw_predictions Xtest = c.Xtest # Filter out empty states if isinstance(sorn.source,TrialSource): # if TrialSource source = sorn.source.source else: source = sorn.source Xtest = Xtest[inputi_test != -1,:] inputi_test = inputi_test[inputi_test != -1] letters_for_frac = c.letters_for_frac # Results will first be saved in dict for simplicity and later # subsampled to an array cue_act = {} pred_gain = {} minlen = inf for (s_word,s_index) in zip(source.words,source.glob_ind): i = ''.join(letters_for_frac).find(s_word[0]) # Indices that point to the presentation of the cue relative # to the readout cue_indices = find(inputi_test==s_index) pred_indices = cue_indices+pred_pos pred_indices = pred_indices[pred_indices <shape(inputi_test)[0]] # Get x-states at cue_indices and figure out the number of # active input units for A and B tmp_cue = Xtest[cue_indices] tmp_cue = vstack(( sum(tmp_cue[:,1==sorn.W_eu.W[:, source.lookup['A']]],1), sum(tmp_cue[:,1==sorn.W_eu.W[:, source.lookup['B']]],1))).T tmp_gain = raw_predictions[pred_indices,:] if cue_act.has_key(i): cue_act[i] = np.append(cue_act[i],tmp_cue,axis=0) pred_gain[i] = np.append(pred_gain[i],tmp_gain,axis=0) else: cue_act[i] = tmp_cue pred_gain[i] = tmp_gain if shape(cue_act[i])[0]<minlen: minlen = shape(cue_act[i])[0] # TODO super ugly - try to make prettier minlen = 18 # hack for cluster - otherwise variable minlen # subsample to make suitable for array n_conditions = max(cue_act.keys())+1 to_return = np.zeros((n_conditions,minlen,4)) for i in range(n_conditions): to_return[i,:,:2] = cue_act[i][-minlen:] to_return[i,:,2:] = pred_gain[i][-minlen:] return to_return class EvokedPredStat(AbstractStat): """ This stat predicts evoked activity from spontaneous activity traintimes is an interval of training data testtimes is an interval of testing data """ def __init__(self,traintimes,testtimes,traintest): self.name = 'EvokedPred' self.collection = 'gather' self.traintimes = traintimes self.testtimes = testtimes self.traintest = traintest def report(self,c,sorn): # Read data traintimes = self.traintimes testtimes = self.testtimes Xtrain = c.spikes[:,traintimes[0]:traintimes[1]].T Xtest = c.spikes[:,testtimes[0]:testtimes[1]].T inputi_train = c.inputindex[traintimes[0]:traintimes[1]] inputi_test = c.inputindex[testtimes[0]:testtimes[1]] # Determine word length source = load_source("source_%s"%self.traintest,sorn.c) N_words = len(source.words) max_word_length = int(max([len(x) for x in source.words])) max_spont_length = int(sorn.c['wait_min_%s'%self.traintest] +sorn.c['wait_var_%s'%self.traintest]) pred_window = max_word_length + max_spont_length+max_word_length correlations = zeros((N_words,pred_window,2)) import scipy.stats as stats # Convert 0/1 spike trains to -1/1 spike trains if needed if sorn.c.stats.match: Xtrain *= 2 Xtrain -= 1 Xtest *= 2 Xtest -= 1 word_length = 0 for (w,word) in enumerate(source.words): word_starts_train = find(inputi_train==(word_length)) word_starts_train = word_starts_train[(word_starts_train>0)\ *(word_starts_train<(shape(Xtrain)[0]-pred_window))] word_starts_test = find(inputi_test==(word_length)) word_starts_test = word_starts_test[word_starts_test<\ (shape(Xtest)[0]-pred_window)] bias_train = ones((shape(word_starts_train)[0],1)) bias_test = ones((shape(word_starts_test)[0],1)) base_train = Xtrain[word_starts_train-1,:].copy() base_test = Xtest[word_starts_test-1,:].copy() shuffle(base_train) shuffle(base_test) base_train = hstack((bias_train,base_train)) base_test = hstack((bias_test,base_test)) sp_train = hstack((bias_train,Xtrain[word_starts_train-1,:])) sp_test = hstack((bias_test,Xtest[word_starts_test-1,:])) #~ sp_train = bias_train <-- this is a STA! #~ sp_test = bias_test for t in range(pred_window): # First do a least-squares fit Xt_train = Xtrain[word_starts_train+t,:] Xt_test = Xtest[word_starts_test+t,:] # regularize with mue to avoid problems when #samples < # #neurons classifier = lstsq_reg(sp_train,Xt_train, sorn.c.stats.lstsq_mue) classifier_base = lstsq_reg(base_train,Xt_train, sorn.c.stats.lstsq_mue) Xt_pred = sp_test.dot(classifier) base_pred = base_test.dot(classifier) # Baseline = STA #~ base = mean(Xt_train,0) #~ base_pred = array([base,]*shape(Xt_test)[0]) # Don't use this because the paper uses correlation # Don't use this because of lower bound for zeros # instead of pearsonr - lower bound = 1-h.ip # -> spont pred always better def match(x,y): assert(shape(x) == shape(y)) x = x>0 y = y>0 return sum(x==y)/(1.0*shape(x)[0]) if not sorn.c.stats.match: correlations[w,t,0] = stats.pearsonr( Xt_pred.flatten(),Xt_test.flatten())[0] correlations[w,t,1] = stats.pearsonr( base_pred.flatten(),Xt_test.flatten())[0] else: correlations[w,t,0] = match(Xt_pred.flatten(), Xt_test.flatten()) correlations[w,t,1] = match(base_pred.flatten(), Xt_test.flatten()) word_length += len(word) # Correlations are sorted like the words: # A B C D E ... B = 0*A C = 0.1*A, D=0.2*A ... return correlations class SpikesStat(AbstractStat): def __init__(self,inhibitory = False): if inhibitory: self.name = 'SpikesInh' self.sattr = 'spikes_inh' else: self.name = 'Spikes' self.sattr = 'spikes' self.collection = 'gather' self.inh = inhibitory def clear(self,c,sorn): if self.inh: self.neurons = sorn.c.N_i else: self.neurons = sorn.c.N_e if sorn.c.stats.has_key('only_last'): steps = sorn.c.stats.only_last+sorn.c.stats.only_last c[self.sattr] = zeros((self.neurons,steps)) else: c[self.sattr] = zeros((self.neurons,sorn.c.N_steps)) self.step = 0 def add(self,c,sorn): if self.inh: spikes = sorn.y else: spikes = sorn.x if sorn.c.stats.has_key('only_last'): new_step = self.step - (sorn.c.N_steps\ -sorn.c.stats.only_last) if new_step >= 0: c[self.sattr][:,new_step+sorn.c.stats.only_last] \ = spikes elif self.step % (sorn.c.N_steps\ //sorn.c.stats.only_last) == 0: c[self.sattr][:,self.step//(sorn.c.N_steps\ //sorn.c.stats.only_last)] = spikes else: c[self.sattr][:,self.step] = spikes self.step += 1 def report(self,c,sorn): if sorn.c.stats.save_spikes: return c[self.sattr] else: return zeros(0) class CondProbStat(AbstractStat): def __init__(self): self.name='CondProb' self.collection='gather' def clear(self,c,sorn): pass def add(self,c,sorn): pass def report(self,c,sorn): # return a marix with M_ij = frequency of a spike in i following # a spike in j # Look at test instead of training to get more diverse data steps = sorn.c.steps_noplastic_test spikes = c.spikes[:,-steps:] N = shape(spikes)[0] # number of neurons condspikes = np.zeros((N,N)) for t in xrange(1,steps): condspikes[spikes[:,t]==1,:] += spikes[:,t-1] spike_sum = sum(spikes,1) for i in xrange(N): condspikes[i,:] /= spike_sum return condspikes class BalancedStat(AbstractStat): """ This stat records the excitatory and inhibitory input and thresholds to determine how balanced the network operates """ def __init__(self): self.name='Balanced' self.collection='gather' def clear(self,c,sorn): c.balanced = zeros((sorn.c.N_e*3,sorn.c.N_steps)) self.step = 0 self.N_e = sorn.c.N_e def add(self,c,sorn): c.balanced[:self.N_e,self.step] = sorn.W_ee*sorn.x c.balanced[self.N_e:2*self.N_e,self.step] = sorn.W_ei*sorn.y c.balanced[2*self.N_e:,self.step] = sorn.T_e self.step += 1 def report(self,c,sorn): return c.balanced class RateStat(AbstractStat): """ This stat returns a matrix of firing rates of each presynaptic neuron """ def __init__(self): self.name = 'Rate' self.collection='gather' def clear(self,c,sorn): pass def add(self,c,sorn): pass def report(self,c,sorn): # same interval as for condprob steps = sorn.c.steps_noplastic_test spikes = c.spikes[:,-steps:] N = shape(spikes)[0] # number of neurons rates = mean(spikes,1) return array([rates,]*N) class InputStat(AbstractStat): def __init__(self): self.name = 'Input' self.collection = 'gather' def clear(self,c,sorn): c.inputs = zeros((sorn.c.N_e,sorn.c.N_steps)) self.step = 0 def add(self,c,sorn): c.inputs[:,self.step] = sorn.W_eu*sorn.u self.step += 1 def report(self,c,sorn): return c.inputs class FullEndWeightStat(AbstractStat): def __init__(self): self.name = 'FullEndWeight' self.collection = 'gather' def clear(self,c,sorn): pass def add(self,c,sorn): pass def report(self,c,sorn): tmp1 = np.vstack((sorn.W_ee.get_synapses(),\ sorn.W_ie.get_synapses())) tmp2 = np.vstack((sorn.W_ei.get_synapses(),\ np.zeros((sorn.c.N_i,sorn.c.N_i)))) return np.array(hstack((tmp1,tmp2))) class EndWeightStat(AbstractStat): def __init__(self): self.name = 'endweight' self.collection = 'gather' def clear(self,c,sorn): pass def add(self,c,sorn): pass def report(self,c,sorn): if sorn.c.W_ee.use_sparse: return np.array(sorn.W_ee.W.todense()) else: return sorn.W_ee.W*(sorn.W_ee.M==1) class ISIsStat(AbstractStat): def __init__(self,interval=[]): self.name = 'ISIs' self.collection = 'gather' self.interval = interval def clear(self,c,sorn): self.mask = sum(sorn.W_eu.get_synapses(),1)==0 self.N_noinput = sum(self.mask) self.ISIs = zeros((self.N_noinput,100)) self.isis = zeros(self.N_noinput) self.step = 0 if self.interval == []: self.interval = [0,sorn.c.N_steps] def add(self,c,sorn): if ((self.step > self.interval[0] and self.step < self.interval[1]) and ((not sorn.c.stats.has_key('only_last')) \ or (self.step > sorn.c.stats.only_last))): spikes = sorn.x[self.mask] self.isis[spikes==0] += 1 isis_tmp = self.isis[spikes==1] isis_tmp = isis_tmp[isis_tmp<100] tmp = zip(where(spikes==1)[0],isis_tmp.astype(int)) for pair in tmp: self.ISIs[pair] += 1 self.isis[spikes==1] = 0 self.step += 1 def report(self,c,sorn): return self.ISIs class SynapseFractionStat(AbstractStat): def __init__(self): self.name = 'SynapseFraction' self.collection = 'reduce' def report(self,c,sorn): if sorn.c.W_ee.use_sparse: return array(sum((sorn.W_ee.W.data>0)+0.0)\ /(sorn.c.N_e*sorn.c.N_e)) else: return array(sum(sorn.W_ee.M)/(sorn.c.N_e*sorn.c.N_e)) class ConnectionFractionStat(AbstractStat): def __init__(self): self.name = 'ConnectionFraction' self.collection = 'gather' def clear(self,c,sorn): self.step = 0 if sorn.c.stats.has_key('only_last'): self.cf = zeros(sorn.c.stats.only_last\ +sorn.c.stats.only_last) else: self.cf = zeros(sorn.c.N_steps) def add(self,c,sorn): if sorn.c.stats.has_key('only_last'): new_step = self.step \ - (sorn.c.N_steps-sorn.c.stats.only_last) if new_step >= 0: if sorn.c.W_ee.use_sparse: self.cf[new_step+sorn.c.stats.only_last] = sum(\ (sorn.W_ee.W.data>0)+0)/(sorn.c.N_e*sorn.c.N_e) else: self.cf[new_step+sorn.c.stats.only_last] = sum(\ sorn.W_ee.M)/(sorn.c.N_e*sorn.c.N_e) elif self.step%(sorn.c.N_steps\ //sorn.c.stats.only_last) == 0: if sorn.c.W_ee.use_sparse: self.cf[self.step//(sorn.c.N_steps\ //sorn.c.stats.only_last)] = sum(\ (sorn.W_ee.W.data>0)+0)/(sorn.c.N_e*sorn.c.N_e) else: self.cf[self.step//(sorn.c.N_steps\ //sorn.c.stats.only_last)] = sum(\ sorn.W_ee.M)/(sorn.c.N_e*sorn.c.N_e) else: if sorn.c.W_ee.use_sparse: self.cf[self.step] = sum((sorn.W_ee.W.data>0)+0)\ /(sorn.c.N_e*sorn.c.N_e) else: self.cf[self.step] = sum(sorn.W_ee.M)\ /(sorn.c.N_e*sorn.c.N_e) self.step += 1 def report(self,c,sorn): return self.cf class WeightLifetimeStat(AbstractStat): def __init__(self): self.name = 'WeightLifetime' self.collection = 'gather' def clear(self,c,sorn): if sorn.c.W_ee.use_sparse: self.last_M_ee = np.array(sorn.W_ee.W.todense())>0 else: self.last_M_ee = sorn.W_ee.M.copy() self.lifetimes = zeros((sorn.c.N_e,sorn.c.N_e)) self.diedat = np.zeros((1,0)) def add(self,c,sorn): if sorn.c.W_ee.use_sparse: new_M_ee = np.array(sorn.W_ee.W.todense())>0 else: new_M_ee = sorn.W_ee.M self.diedat = append(self.diedat, \ self.lifetimes[(new_M_ee+0-self.last_M_ee+0)==-1]) # remove dead synapses self.lifetimes *= new_M_ee+0 #increase lifetime of existing ones self.lifetimes += (self.lifetimes>0)+0 #add new ones self.lifetimes += ((new_M_ee+0-self.last_M_ee+0)==1)+0 self.last_M_ee = new_M_ee.copy() def report(self,c,sorn): padding = (-1)*np.ones(2*sorn.c.N_steps\ +shape(self.last_M_ee)[0]**2-self.diedat.size) return np.append(self.diedat,padding) class WeightChangeStat(AbstractStat): def __init__(self): self.name = 'WeightChange' self.collection = 'gather' def clear(self,c,sorn): self.step = 0 self.start = 2999 self.end = 5999 self.save_W_ee = [] self.abschange = [] self.relchange = [] self.weights = [] def add(self,c,sorn): if(self.step == self.start): if sorn.c.W_ee.use_sparse: self.save_W_ee = np.array(sorn.W_ee.W.todense()) else: self.save_W_ee = sorn.W_ee.W.copy() if(self.step == self.end): if sorn.c.W_ee.use_sparse: diff = np.array(sorn.W_ee.W.todense())-self.save_W_ee else: diff = sorn.W_ee.W-self.save_W_ee self.weights = self.save_W_ee[diff!=0] self.abschange = (diff[diff!=0]) seterr(divide='ignore') # Some weights become 0 and thereby elicit division by 0 # and try except RuntimeWarning didn't work self.relchange = self.abschange/self.weights*100 seterr(divide='warn') # append zeros to always have the same size tmp_zeros = np.zeros(shape(self.save_W_ee)[0]**2\ -self.weights.size) self.weights = np.append(self.weights,tmp_zeros) self.abschange = np.append(self.abschange,tmp_zeros) self.relchange = np.append(self.relchange,tmp_zeros) self.step += 1 def report(self,c,sorn): stacked = np.vstack((self.weights, self.abschange,\ self.relchange)) return stacked class WeightChangeRumpelStat(AbstractStat): def __init__(self): self.name = 'WeightChangeRumpel' self.collection = 'gather' def clear(self,c,sorn): self.step = 0 self.interval = 0 self.start = 50001 self.started = False self.imaging_interval = 50000 self.N_intervals = (sorn.c.N_steps-self.start)\ //self.imaging_interval+1 self.save_W_ees = np.zeros((self.N_intervals,sorn.c.N_e,\ sorn.c.N_e)) self.constant_weights = [] self.abschange = [] self.relchange = [] self.weights = [] def add(self,c,sorn): if(self.step%self.imaging_interval == 0 and self.started): self.save_W_ees[self.interval,:,:] \ = sorn.W_ee.get_synapses() self.constant_weights *= (self.save_W_ees[self.interval,\ :,:]>0) self.interval += 1 if(self.step == self.start): self.save_W_ees[self.interval,:,:] \ = sorn.W_ee.get_synapses() self.constant_weights \ = (self.save_W_ees[self.interval,:,:].copy()>0) self.interval = 1 self.started = True self.step += 1 def report(self,c,sorn): # compute diffs and multiply with const import pdb pdb.set_trace() diffs = self.save_W_ees[1:,:,:] - self.save_W_ees[:-1,:,:] diffs *= self.constant_weights self.abschange = (diffs[diffs!=0]) self.weights = self.save_W_ees[:-1,:,:][diffs!=0] self.relchange = self.abschange/self.weights*100 # append zeros to always have the same size tmp_zeros = np.zeros((self.N_intervals-1)\ *shape(self.save_W_ees)[1]**2-self.weights.size) self.weights = np.append(self.weights,tmp_zeros) self.abschange = np.append(self.abschange,tmp_zeros) self.relchange = np.append(self.relchange,tmp_zeros) stacked = np.vstack((self.weights, self.abschange,\ self.relchange)) return stacked class SmallWorldStat(AbstractStat): def __init__(self): self.name = 'smallworld' self.collection = 'gather' def clear(self,c,sorn): pass def add(self,c,sorn): pass def report(self,c,sorn): if sorn.c.stats.rand_networks <= 0: return np.array([]) if sorn.c.W_ee.use_sparse: weights = np.array(sorn.W_ee.W.todense()) else: weights = sorn.W_ee.W*(sorn.W_ee.M==1) tmp = weights>0.0+0.0 binary_connections = tmp+0.0 def all_pairs_shortest_path(graph_matrix): # adapted Floyd-Warshall Algorithm N = shape(graph_matrix)[0] distances = graph_matrix.copy() #Set missing connections to max length distances[distances==0] += N*N for k in range(N): for i in range(N): for j in range(N): if i==j: distances[i,j] = 0 else: distances[i,j] = min(distances[i,j], distances[i,k] +distances[k,j]) return distances def characteristic_path_length(graph_matrix): N = shape(graph_matrix)[0] distances = all_pairs_shortest_path(graph_matrix.T) if any(distances == N*N): print 'Disconnected elements in char. path len calc.' # ignore disconnected elements distances[distances==N*N] = 0 average_length = sum(distances[distances>0]*1.0)\ /sum(graph_matrix[distances>0]*1.0) return average_length def cluster_coefficient(graph_matrix): # From Fagiolo, 2007 and Gerhard, 2011 N = shape(graph_matrix)[0] in_degree = sum(graph_matrix,1) out_degree = sum(graph_matrix,0) k = in_degree+out_degree A = graph_matrix A_T = A.transpose() A_A_T = A + A_T A_2 = np.dot(A,A) nominator = np.dot(A_A_T,np.dot(A_A_T,A_A_T)) single_coeff = np.zeros(N) for i in range(N): single_coeff[i] = nominator[i,i]/(2.0*(k[i]*(k[i]-1)\ -2.0*(A_2[i,i]))) if(np.isnan(single_coeff[i])): # if total degree <= 1, the formula divides by 0 single_coeff[i] = 0 return 1.0*sum(single_coeff)/(N*1.0) L = characteristic_path_length(binary_connections) C = cluster_coefficient(binary_connections) # Average over some random networks N = shape(binary_connections)[0] edge_density = sum(binary_connections)/(1.0*N*N-N) num_rand = sorn.c.stats.rand_networks L_rand = np.zeros(num_rand) C_rand = np.zeros(num_rand) delete_diagonal = np.ones((N,N)) for i in range(N): delete_diagonal[i,i] = 0 for i in range(num_rand): sys.stdout.write('\rRand Graph No.%3i of %3i'%(i+1,\ num_rand)) sys.stdout.flush() tmp = np.random.rand(N,N)<edge_density rand_graph = tmp*delete_diagonal L_rand[i] = characteristic_path_length(rand_graph) C_rand[i] = cluster_coefficient(rand_graph) sys.stdout.write('\rAll %i Graphs Done '%num_rand) sys.stdout.flush() L_r = sum(L_rand)*1.0/(num_rand*1.0) C_r = sum(C_rand)*1.0/(num_rand*1.0) gamma = C/C_r lam = L/L_r S_w = gamma/lam return np.array([gamma, lam, S_w]) class ParamTrackerStat(AbstractStat): def __init__(self): self.name = 'paramtracker' self.collection = 'gather' def clear(self,c,sorn): pass def add(self,c,sorn): pass def report(self,c,sorn): tmp = sorn.c for item in sorn.c.cluster.vary_param.split('.'): tmp = tmp[item] return np.array([tmp*1.0]) class InputWeightStat(AbstractStat): def __init__(self): self.name = 'InputWeight' self.collection = 'gather' def clear(self,c,sorn): self.step = 0 self.weights = np.zeros((sorn.c.N_e,sorn.c.N_u_e,\ sorn.c.stats.only_last*2)) def add(self,c,sorn): if self.step % (sorn.c.N_steps//sorn.c.stats.only_last) == 0: self.weights[:,:,self.step//(sorn.c.N_steps\ //sorn.c.stats.only_last)] = sorn.W_eu.get_synapses() self.step += 1 def report(self,c,sorn): return self.weights class SVDStat(AbstractStat): def __init__(self,nth = 200): self.name = 'SVD' self.collection = 'gather' self.nth = nth def clear(self,c,sorn): self.step = 0 # Quick hack - there must be a prettier solution if sorn.c.steps_plastic % self.nth == 0: add1 = 0 else: add1 = 1 c.SVD_singulars = np.zeros((sorn.c.steps_plastic//self.nth+add1 ,sorn.c.N_e)) c.SVD_U = np.zeros((sorn.c.steps_plastic//self.nth+add1, sorn.c.N_e,sorn.c.N_e)) c.SVD_V = np.zeros((sorn.c.steps_plastic//self.nth+add1, sorn.c.N_e,sorn.c.N_e)) def add(self,c,sorn): if self.step < sorn.c.steps_plastic and self.step%self.nth == 0: # Time intensive! synapses = sorn.W_ee.get_synapses() U,s,V = linalg.svd(synapses) c.SVD_singulars[self.step//self.nth,:] = s step = self.step//self.nth c.SVD_U[step] = U # this returns the real V # see http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html c.SVD_V[step] = V.T # Resolve sign ambiguity # from http://www.models.life.ku.dk/signflipsvd # http://prod.sandia.gov/techlib/access-control.cgi/2007/076422.pdf for i in range(sorn.c.N_e): tmp = synapses.T.dot(c.SVD_U[step,:,i]) tmp = np.squeeze(asarray(tmp)) s_left = sum(sign(tmp)*tmp**2) tmp = synapses.T.dot(c.SVD_V[step,:,i]) tmp = np.squeeze(asarray(tmp)) s_right = sum(sign(tmp)*tmp**2) if s_right*s_left < 0: if s_left < s_right: s_left = -s_left else: s_right = -s_right c.SVD_U[step,:,i] *= sign(s_left) c.SVD_V[step,:,i] *= sign(s_right) self.step += 1 def report(self,c,sorn): #~ figure() # combine same submatrices! #~ imshow(c.SVD_U[-1][:,0].dot(c.SVD_V[-1][:,0].T)\ #~ *c.SVD_singulars[-1,0], interpolation='none') return c.SVD_singulars class SVDStat_U(AbstractStat): def __init__(self): self.name = 'SVD_U' self.collection = 'gather' def report(self,c,sorn): rec_steps = shape(c.SVD_U)[0] similar_input = zeros((rec_steps,sorn.c.N_e)) N_indices = max(c.norm_last_input_index)+1 indices = [where(c.norm_last_input_index==i)[0] for i in range(int(N_indices))] for s in xrange(rec_steps): for i in xrange(sorn.c.N_e): # U transforms back to "spike space" # Check for best similarities # Convolution works best: #~ overlaps = c.norm_last_input_spikes.T.dot( #~ c.SVD_U[s,:,i]) #~ index_overlap = np.zeros(N_indices) #~ for j in range(int(N_indices)): #~ index_overlap[j] = mean(overlaps[indices[j]]) #~ similar_input[s,i] = argmax(index_overlap) # No big difference to this, but probably more robust max_overlap = argmax(c.norm_last_input_spikes.T.dot( c.SVD_U[s,:,i])) similar_input[s,i] = c.norm_last_input_index[ max_overlap] c.SVD_U_sim = similar_input # for debugging return similar_input class SVDStat_V(AbstractStat): def __init__(self): self.name = 'SVD_V' self.collection = 'gather' def report(self,c,sorn): rec_steps = shape(c.SVD_V)[0] similar_input = zeros((rec_steps,sorn.c.N_e)) N_indices = max(c.norm_last_input_index)+1 indices = [where(c.norm_last_input_index==i)[0] for i in range(int(N_indices))] for s in xrange(rec_steps): for i in xrange(sorn.c.N_e): # V transforms input by taking product # Do same here and look which spike vector works best #~ overlaps = c.norm_last_input_spikes.T.dot( #~ c.SVD_V[s,:,i]) #~ index_overlap = np.zeros(N_indices) #~ for j in range(int(N_indices)): #~ index_overlap[j] = mean(overlaps[indices[j]]) #~ similar_input[s,i] = argmax(index_overlap) # No big difference to this, but probably more robust max_overlap = argmax(c.norm_last_input_spikes.T.dot( c.SVD_V[s,:,i])) # euclidean norm w/o sqrt similar_input[s,i] = c.norm_last_input_index[ max_overlap] ''' # For testing purposes command line !i = 30 !similar_input[:,i] !c.SVD_U_sim[:,i] !figure() !plot(c.SVD_V[-1,:,i]) !max_overlap = argmax(c.norm_last_input_spikes.T.dot(c.SVD_V[s,:,i])) !plot(c.norm_last_input_spikes[:,max_overlap]) !figure() !plot(c.SVD_U[-1,:,i]) !max_overlap = argmax(c.norm_last_input_spikes.T.dot(c.SVD_U[s,:,i])) !plot(c.norm_last_input_spikes[:,max_overlap]) !show() ''' return similar_input class MeanActivityStat(AbstractStat): """ This stat returns the mean activity for each inputindex """ def __init__(self,start,stop,N_indices,LFP=False): self._start = start self._stop = stop self._N_indices = N_indices self.name = 'meanactivity' self.collection = 'gather' self.LFP = LFP self.tmp = -1 def clear(self,c,sorn): self.means = zeros(self._N_indices) self.counter = zeros(self._N_indices) self.step = 0 self.index = None def add(self,c,sorn): if self.step > self._start and self.step < self._stop\ and self.step>0: # for proper assignment, blank(-1)->0, 0->1... self.index = sorn.source.global_index()+1 if self.index is not None: if self.tmp >= 0: self.counter[self.index] += 1. if self.LFP: # save input at current step, but can only compute # input for next step! if self.tmp >= 0: self.means[self.index] += self.tmp+sum(sorn.W_eu *sorn.u) self.tmp = sum(sorn.W_ee*sorn.x) else: if self.tmp >= 0: self.means[self.index] += sum(sorn.x) self.tmp = 0 # dummy value never used #~ # +1 due to -1 for blank trials #~ self.index = sorn.source.global_index()+1 self.step += 1 def report(self,c,sorn): return self.means/self.counter class MeanPatternStat(AbstractStat): """ This stat returns the mean activity for each inputindex """ def __init__(self,start,stop,N_indices): self._start = start self._stop = stop self._N_indices = N_indices self.name = 'meanpattern' self.collection = 'gather' def clear(self,c,sorn): self.means = zeros((self._N_indices,sorn.c.N_e)) self.counter = zeros(self._N_indices) self.step = 0 self.index = None def add(self,c,sorn): if self.step > self._start and self.step < self._stop\ and self.step>0: # for proper assignment, blank(-1)->0, 0->1... self.index = sorn.source.global_index()+1 if self.index is not None: self.counter[self.index] += 1. self.means[self.index] += sorn.x self.step += 1 def report(self,c,sorn): return self.means/self.counter[:,None] class PatternProbabilityStat(AbstractStat): """ This stat estimates the probability distribution of patterns for different time intervals Intervals: List of 2-entry lists [[start1,stop1],...,[startn,stopn]] zero_correction: Bool Correct estimates by adding one observation to each pattern subset: 1-D array List of neuron indices that create the pattern """ def __init__(self,intervals,subset,zero_correction=True): self.N_intervals = len(intervals) self.intervals = intervals self.zero_correction = zero_correction self.N_nodes = len(subset) self.subset = subset self.name = 'patternprobability' self.collection = 'gather' self.conversion_array = [2**x for x in range(self.N_nodes)][::-1] def convert(x): return np.dot(x,self.conversion_array) self.convert = convert def clear(self,c,sorn): self.patterns = zeros((self.N_intervals,2**self.N_nodes)) self.step = 0 def add(self,c,sorn): for (i,(start,stop)) in enumerate(self.intervals): if self.step > start and self.step < stop: # Convert spiking pattern to integer by taking the # pattern as a binary number self.patterns[i,self.convert(sorn.x[self.subset])] += 1 self.step += 1 def report(self,c,sorn): if self.zero_correction: self.patterns += 1 # Normalize to probabilities self.patterns /= self.patterns.sum(1)[:,None] return self.patterns class WeeFailureStat(AbstractStat): def __init__(self): self.name = 'weefail' self.collection = 'gather' def clear(self,c,sorn): c.weefail = zeros(sorn.c.N_steps) self.step = 0 def add(self,c,sorn): if sorn.c.W_ee.use_sparse: N_weights = sorn.W_ee.W.data.shape[0] N_fail = N_weights-sum(sorn.W_ee.mask) else: N_weights = sum(sorn.W_ee.get_synapses()>0) N_fail = N_weights-sum(sorn.W_ee.masked>0) c.weefail[self.step] = N_fail/N_weights self.step += 1 def report(self,c,sorn): return c.weefail class WeeFailureFuncStat(AbstractStat): def __init__(self): self.name = 'weefailfunc' self.collection = 'gather' def clear(self,c,sorn): self.x = np.linspace(0,1,1000) self.y = sorn.W_ee.fail_f(self.x) def add(self,c,sorn): pass def report(self,c,sorn): return np.array([self.x,self.y]) # From Philip class XClassifierStat(AbstractStat): def __init__(self,steps=None, classify_x=True, \ classify_r=False,detailed=False,**args): '''Steps is a list with the step sizes over which to predict. e.g. - a step of +1 means predict the next state - a step of 0 means identify the current state - a step of -1 means identify the previous state ''' if steps is None: steps = [0] self.steps = steps self.classify_x = classify_x self.classify_r = classify_r self.detailed = detailed @property def name(self): ans = [] if self.classify_x: ans.append('xclassifier') if self.classify_r: ans.append('rclassifier') return ans def build_classifier(self,inp,out,offset): # Use the input to build a classifier of the output with an # offset N = inp.shape[0] inp_aug = hstack([inp, ones((N,1))]) (ib,ie) = (max(-offset,0),min(N-offset,N)) (ob,oe) = (max(+offset,0),min(N+offset,N)) try: ans = linalg.lstsq(inp_aug[ib:ie,:],out[ob:oe,:])[0] except LinAlgError: ans = zeros( (inp.shape[1]+1,out.shape[1]) ) return ans def use_classifier(self,inp,classifier,offset,correct): N = inp.shape[0] L = classifier.shape[1] inp_aug = hstack([inp, ones((N,1))]) (ib,ie) = (max(-offset,0),min(N-offset,N)) (ob,oe) = (max(+offset,0),min(N+offset,N)) ind = argmax(inp_aug[ib:ie,:].dot(classifier),1) actual = argmax(correct,1)[ob:oe] num = zeros(L) den = zeros(L) for l in range(L): l_ind = actual==l num[l] = sum(actual[l_ind]==ind[l_ind]) den[l] = sum(l_ind) return (num,den) def report(self,_,sorn): c = sorn.c #Disable plasticity when measuring network sorn.update = False #Don't track statistics when measuring either self.parent.disable = True #Build classifiers Nr = c.test_num_train Nt = c.test_num_test #~ (Xr,Rr,Ur) = sorn.simulation(Nr) dic = sorn.simulation(Nr,['X','R_x','U']) Xr = dic['X'] Rr = dic['R_x'] Ur = dic['U'] #~ (Xt,Rt,Ut) = sorn.simulation(Nt) dic = sorn.simulation(Nt,['X','R_x','U']) Xt = dic['X'] Rt = dic['R_x'] Ut = dic['U'] L = Ur.shape[1] Rr = (Rr >= 0.0)+0 Rt = (Rt >= 0.0)+0 r = [] x = [] detail_r=[] detail_x=[] for step in self.steps: if self.classify_x: classifier = self.build_classifier(Xr,Ur,step) (num,den) = self.use_classifier(Xt,classifier,step,Ut) ans = sum(num)/sum(den) x.append(ans) if self.detailed: detail_x.append(num/(den+1e-20)) if self.classify_r: classifier = self.build_classifier(Rr,Ur,step) (num,den) = self.use_classifier(Rt,classifier,step,Ut) ans = sum(num)/sum(den) r.append(ans) if self.detailed: detail_r.append(num/(den+1e-20)) ans = [] if self.classify_x: ans.append( ('xclassifier', 'reduce', array(x)) ) if self.detailed: ans.append( ('x_detail_classifier%d'%L,'reduce',\ array(detail_x)) ) if self.classify_r: ans.append( ('rclassifier', 'reduce', array(r)) ) if self.detailed: ans.append( ('r_detail_classifier%d'%L,'reduce',\ array(detail_r)) ) sorn.update = True self.parent.disable = False return ans # From Philip class XTotalsStat(AbstractStat): def __init__(self): self.name = 'x_tot' self.collection = 'gather' def clear(self,c,obj): N = obj.c.N_e c.x_tot = zeros(N) def add(self,c,obj): c.x_tot += obj.x def report(self,c,obj): return c.x_tot # From Philip class YTotalsStat(AbstractStat): def __init__(self): self.name = 'y_tot' self.collection = 'gather' def clear(self,c,obj): N = obj.c.N_i c.y_tot = zeros(N) def add(self,c,obj): c.y_tot += obj.y def report(self,c,obj): return c.y_tot # From Philip class SynapticDistributionStat(AbstractStat): def __init__(self,collection='gatherv'): self.name = 'synaptic_strength' self.collection = collection def report(self,_,sorn): W = sorn.W_ee.T Mask = sorn.M_ee.T # This code might be a little fragile but fast # (note transposes rely on memory laid out in particular order) #~ N = sorn.c.N_e #~ M = sorn.c.lamb #This relies on a fixed # of non-zero synapses per neuron #~ ans = (W[Mask]).reshape(N,M).T.copy() ans = W[Mask] return ans # From Philip class SuccessiveStat(AbstractStat): def __init__(self): self.name = 'successive' self.collection = 'reduce' def clear(self,c,sorn): N = sorn.c.N_e c.successive = zeros( (N+1,N+1) ) c.successive_prev = sum(sorn.x) def add(self, c, sorn): curr = sum(sorn.x) c.successive[c.successive_prev,curr] += 1.0 c.successive_prev = curr def report(self,c,sorn): return c.successive # From Philip class RClassifierStat(AbstractStat): def __init__(self,select=None): if select is None: select = [True,True,True] self.name = 'classifier' self.collection = 'reduce' self.select = select def report(self,_,sorn): c = sorn.c sorn.update = False self.parent.disable = True #Build classifiers N = c.test_num_train #~ (X,R,U) = sorn.simulation(N) dic = sorn.simulation(N,['X','R_x','U']) X = dic['X'] R = dic['R_x'] U = dic['U'] R = hstack([R>=0,ones((N,1))]) if self.select[0]: classifier0 = linalg.lstsq(R,U)[0] if self.select[1]: classifier1 = dot(linalg.pinv(R),U) if self.select[2]: X_aug = hstack([X, ones((N,1))]) classifier2 = linalg.lstsq(X_aug[:-1,:],U[1:,:])[0] #Now test classifiers N = c.test_num_test #~ (X,R,U) = sorn.simulation(N) dic = sorn.simulation(N,['X','R_x','U']) X = dic['X'] R = dic['R_x'] U = dic['U'] R = hstack([R>=0,ones((N,1))]) if self.select[0]: ind0 = argmax(dot(R,classifier0),1) if self.select[1]: ind1 = argmax(dot(R,classifier1),1) if self.select[2]: X_aug = hstack([X, ones((N,1))]) ind2 = argmax(dot(X_aug[:-1,:],classifier2),1) actual = argmax(U,1) ans = [] if self.select[0]: ans.append(mean(actual==ind0)) if self.select[1]: ans.append(mean(actual==ind1)) if self.select[2]: ans.append(mean(actual[1:]==ind2)) sorn.update = True self.parent.disable = False return array(ans) class WeightHistoryStat(HistoryStat): def add(self,c,obj): if not (c.history[self.counter] % self.record_every_nth): c.history[self.name].append(np.copy( _getvar(obj,self.var).get_synapses())) c.history[self.counter] += 1
mit
AnasGhrab/scikit-learn
examples/model_selection/plot_roc_crossval.py
247
3253
""" ============================================================= Receiver Operating Characteristic (ROC) with cross validation ============================================================= Example of Receiver Operating Characteristic (ROC) metric to evaluate classifier output quality using cross-validation. ROC curves typically feature true positive rate on the Y axis, and false positive rate on the X axis. This means that the top left corner of the plot is the "ideal" point - a false positive rate of zero, and a true positive rate of one. This is not very realistic, but it does mean that a larger area under the curve (AUC) is usually better. The "steepness" of ROC curves is also important, since it is ideal to maximize the true positive rate while minimizing the false positive rate. This example shows the ROC response of different datasets, created from K-fold cross-validation. Taking all of these curves, it is possible to calculate the mean area under curve, and see the variance of the curve when the training set is split into different subsets. This roughly shows how the classifier output is affected by changes in the training data, and how different the splits generated by K-fold cross-validation are from one another. .. note:: See also :func:`sklearn.metrics.auc_score`, :func:`sklearn.cross_validation.cross_val_score`, :ref:`example_model_selection_plot_roc.py`, """ print(__doc__) import numpy as np from scipy import interp import matplotlib.pyplot as plt from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.cross_validation import StratifiedKFold ############################################################################### # Data IO and generation # import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target X, y = X[y != 2], y[y != 2] n_samples, n_features = X.shape # Add noisy features random_state = np.random.RandomState(0) X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] ############################################################################### # Classification and ROC analysis # Run classifier with cross-validation and plot ROC curves cv = StratifiedKFold(y, n_folds=6) classifier = svm.SVC(kernel='linear', probability=True, random_state=random_state) mean_tpr = 0.0 mean_fpr = np.linspace(0, 1, 100) all_tpr = [] for i, (train, test) in enumerate(cv): probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) # Compute ROC curve and area the curve fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) mean_tpr += interp(mean_fpr, fpr, tpr) mean_tpr[0] = 0.0 roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc)) plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') mean_tpr /= len(cv) mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) plt.plot(mean_fpr, mean_tpr, 'k--', label='Mean ROC (area = %0.2f)' % mean_auc, lw=2) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show()
bsd-3-clause
Aasmi/scikit-learn
examples/ensemble/plot_adaboost_hastie_10_2.py
355
3576
""" ============================= Discrete versus Real AdaBoost ============================= This example is based on Figure 10.2 from Hastie et al 2009 [1] and illustrates the difference in performance between the discrete SAMME [2] boosting algorithm and real SAMME.R boosting algorithm. Both algorithms are evaluated on a binary classification task where the target Y is a non-linear function of 10 input features. Discrete SAMME AdaBoost adapts based on errors in predicted class labels whereas real SAMME.R uses the predicted class probabilities. .. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", Springer, 2009. .. [2] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009. """ print(__doc__) # Author: Peter Prettenhofer <[email protected]>, # Noel Dawe <[email protected]> # # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import zero_one_loss from sklearn.ensemble import AdaBoostClassifier n_estimators = 400 # A learning rate of 1. may not be optimal for both SAMME and SAMME.R learning_rate = 1. X, y = datasets.make_hastie_10_2(n_samples=12000, random_state=1) X_test, y_test = X[2000:], y[2000:] X_train, y_train = X[:2000], y[:2000] dt_stump = DecisionTreeClassifier(max_depth=1, min_samples_leaf=1) dt_stump.fit(X_train, y_train) dt_stump_err = 1.0 - dt_stump.score(X_test, y_test) dt = DecisionTreeClassifier(max_depth=9, min_samples_leaf=1) dt.fit(X_train, y_train) dt_err = 1.0 - dt.score(X_test, y_test) ada_discrete = AdaBoostClassifier( base_estimator=dt_stump, learning_rate=learning_rate, n_estimators=n_estimators, algorithm="SAMME") ada_discrete.fit(X_train, y_train) ada_real = AdaBoostClassifier( base_estimator=dt_stump, learning_rate=learning_rate, n_estimators=n_estimators, algorithm="SAMME.R") ada_real.fit(X_train, y_train) fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1, n_estimators], [dt_stump_err] * 2, 'k-', label='Decision Stump Error') ax.plot([1, n_estimators], [dt_err] * 2, 'k--', label='Decision Tree Error') ada_discrete_err = np.zeros((n_estimators,)) for i, y_pred in enumerate(ada_discrete.staged_predict(X_test)): ada_discrete_err[i] = zero_one_loss(y_pred, y_test) ada_discrete_err_train = np.zeros((n_estimators,)) for i, y_pred in enumerate(ada_discrete.staged_predict(X_train)): ada_discrete_err_train[i] = zero_one_loss(y_pred, y_train) ada_real_err = np.zeros((n_estimators,)) for i, y_pred in enumerate(ada_real.staged_predict(X_test)): ada_real_err[i] = zero_one_loss(y_pred, y_test) ada_real_err_train = np.zeros((n_estimators,)) for i, y_pred in enumerate(ada_real.staged_predict(X_train)): ada_real_err_train[i] = zero_one_loss(y_pred, y_train) ax.plot(np.arange(n_estimators) + 1, ada_discrete_err, label='Discrete AdaBoost Test Error', color='red') ax.plot(np.arange(n_estimators) + 1, ada_discrete_err_train, label='Discrete AdaBoost Train Error', color='blue') ax.plot(np.arange(n_estimators) + 1, ada_real_err, label='Real AdaBoost Test Error', color='orange') ax.plot(np.arange(n_estimators) + 1, ada_real_err_train, label='Real AdaBoost Train Error', color='green') ax.set_ylim((0.0, 0.5)) ax.set_xlabel('n_estimators') ax.set_ylabel('error rate') leg = ax.legend(loc='upper right', fancybox=True) leg.get_frame().set_alpha(0.7) plt.show()
bsd-3-clause
marcocaccin/scikit-learn
examples/model_selection/plot_roc_crossval.py
247
3253
""" ============================================================= Receiver Operating Characteristic (ROC) with cross validation ============================================================= Example of Receiver Operating Characteristic (ROC) metric to evaluate classifier output quality using cross-validation. ROC curves typically feature true positive rate on the Y axis, and false positive rate on the X axis. This means that the top left corner of the plot is the "ideal" point - a false positive rate of zero, and a true positive rate of one. This is not very realistic, but it does mean that a larger area under the curve (AUC) is usually better. The "steepness" of ROC curves is also important, since it is ideal to maximize the true positive rate while minimizing the false positive rate. This example shows the ROC response of different datasets, created from K-fold cross-validation. Taking all of these curves, it is possible to calculate the mean area under curve, and see the variance of the curve when the training set is split into different subsets. This roughly shows how the classifier output is affected by changes in the training data, and how different the splits generated by K-fold cross-validation are from one another. .. note:: See also :func:`sklearn.metrics.auc_score`, :func:`sklearn.cross_validation.cross_val_score`, :ref:`example_model_selection_plot_roc.py`, """ print(__doc__) import numpy as np from scipy import interp import matplotlib.pyplot as plt from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.cross_validation import StratifiedKFold ############################################################################### # Data IO and generation # import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target X, y = X[y != 2], y[y != 2] n_samples, n_features = X.shape # Add noisy features random_state = np.random.RandomState(0) X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] ############################################################################### # Classification and ROC analysis # Run classifier with cross-validation and plot ROC curves cv = StratifiedKFold(y, n_folds=6) classifier = svm.SVC(kernel='linear', probability=True, random_state=random_state) mean_tpr = 0.0 mean_fpr = np.linspace(0, 1, 100) all_tpr = [] for i, (train, test) in enumerate(cv): probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) # Compute ROC curve and area the curve fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) mean_tpr += interp(mean_fpr, fpr, tpr) mean_tpr[0] = 0.0 roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc)) plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') mean_tpr /= len(cv) mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) plt.plot(mean_fpr, mean_tpr, 'k--', label='Mean ROC (area = %0.2f)' % mean_auc, lw=2) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show()
bsd-3-clause
jwlawson/tensorflow
tensorflow/examples/tutorials/word2vec/word2vec_basic.py
6
10430
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Basic word2vec example.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import math import os import random from tempfile import gettempdir import zipfile import numpy as np from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf # Step 1: Download the data. url = 'http://mattmahoney.net/dc/' # pylint: disable=redefined-outer-name def maybe_download(filename, expected_bytes): """Download a file if not present, and make sure it's the right size.""" local_filename = os.path.join(gettempdir(), filename) if not os.path.exists(local_filename): local_filename, _ = urllib.request.urlretrieve(url + filename, local_filename) statinfo = os.stat(local_filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename) else: print(statinfo.st_size) raise Exception('Failed to verify ' + local_filename + '. Can you get to it with a browser?') return local_filename filename = maybe_download('text8.zip', 31344016) # Read the data into a list of strings. def read_data(filename): """Extract the first file enclosed in a zip file as a list of words.""" with zipfile.ZipFile(filename) as f: data = tf.compat.as_str(f.read(f.namelist()[0])).split() return data vocabulary = read_data(filename) print('Data size', len(vocabulary)) # Step 2: Build the dictionary and replace rare words with UNK token. vocabulary_size = 50000 def build_dataset(words, n_words): """Process raw inputs into a dataset.""" count = [['UNK', -1]] count.extend(collections.Counter(words).most_common(n_words - 1)) dictionary = dict() for word, _ in count: dictionary[word] = len(dictionary) data = list() unk_count = 0 for word in words: index = dictionary.get(word, 0) if index == 0: # dictionary['UNK'] unk_count += 1 data.append(index) count[0][1] = unk_count reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys())) return data, count, dictionary, reversed_dictionary # Filling 4 global variables: # data - list of codes (integers from 0 to vocabulary_size-1). # This is the original text but words are replaced by their codes # count - map of words(strings) to count of occurrences # dictionary - map of words(strings) to their codes(integers) # reverse_dictionary - maps codes(integers) to words(strings) data, count, dictionary, reverse_dictionary = build_dataset(vocabulary, vocabulary_size) del vocabulary # Hint to reduce memory. print('Most common words (+UNK)', count[:5]) print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]]) data_index = 0 # Step 3: Function to generate a training batch for the skip-gram model. def generate_batch(batch_size, num_skips, skip_window): global data_index assert batch_size % num_skips == 0 assert num_skips <= 2 * skip_window batch = np.ndarray(shape=(batch_size), dtype=np.int32) labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32) span = 2 * skip_window + 1 # [ skip_window target skip_window ] buffer = collections.deque(maxlen=span) if data_index + span > len(data): data_index = 0 buffer.extend(data[data_index:data_index + span]) data_index += span for i in range(batch_size // num_skips): context_words = [w for w in range(span) if w != skip_window] words_to_use = random.sample(context_words, num_skips) for j, context_word in enumerate(words_to_use): batch[i * num_skips + j] = buffer[skip_window] labels[i * num_skips + j, 0] = buffer[context_word] if data_index == len(data): buffer.extend(data[0:span]) data_index = span else: buffer.append(data[data_index]) data_index += 1 # Backtrack a little bit to avoid skipping words in the end of a batch data_index = (data_index + len(data) - span) % len(data) return batch, labels batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1) for i in range(8): print(batch[i], reverse_dictionary[batch[i]], '->', labels[i, 0], reverse_dictionary[labels[i, 0]]) # Step 4: Build and train a skip-gram model. batch_size = 128 embedding_size = 128 # Dimension of the embedding vector. skip_window = 1 # How many words to consider left and right. num_skips = 2 # How many times to reuse an input to generate a label. num_sampled = 64 # Number of negative examples to sample. # We pick a random validation set to sample nearest neighbors. Here we limit the # validation samples to the words that have a low numeric ID, which by # construction are also the most frequent. These 3 variables are used only for # displaying model accuracy, they don't affect calculation. valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # Only pick dev samples in the head of the distribution. valid_examples = np.random.choice(valid_window, valid_size, replace=False) graph = tf.Graph() with graph.as_default(): # Input data. train_inputs = tf.placeholder(tf.int32, shape=[batch_size]) train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1]) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # Ops and variables pinned to the CPU because of missing GPU implementation with tf.device('/cpu:0'): # Look up embeddings for inputs. embeddings = tf.Variable( tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) embed = tf.nn.embedding_lookup(embeddings, train_inputs) # Construct the variables for the NCE loss nce_weights = tf.Variable( tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) nce_biases = tf.Variable(tf.zeros([vocabulary_size])) # Compute the average NCE loss for the batch. # tf.nce_loss automatically draws a new sample of the negative labels each # time we evaluate the loss. # Explanation of the meaning of NCE loss: # http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/ loss = tf.reduce_mean( tf.nn.nce_loss(weights=nce_weights, biases=nce_biases, labels=train_labels, inputs=embed, num_sampled=num_sampled, num_classes=vocabulary_size)) # Construct the SGD optimizer using a learning rate of 1.0. optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss) # Compute the cosine similarity between minibatch examples and all embeddings. norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True)) normalized_embeddings = embeddings / norm valid_embeddings = tf.nn.embedding_lookup( normalized_embeddings, valid_dataset) similarity = tf.matmul( valid_embeddings, normalized_embeddings, transpose_b=True) # Add variable initializer. init = tf.global_variables_initializer() # Step 5: Begin training. num_steps = 100001 with tf.Session(graph=graph) as session: # We must initialize all variables before we use them. init.run() print('Initialized') average_loss = 0 for step in xrange(num_steps): batch_inputs, batch_labels = generate_batch( batch_size, num_skips, skip_window) feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels} # We perform one update step by evaluating the optimizer op (including it # in the list of returned values for session.run() _, loss_val = session.run([optimizer, loss], feed_dict=feed_dict) average_loss += loss_val if step % 2000 == 0: if step > 0: average_loss /= 2000 # The average loss is an estimate of the loss over the last 2000 batches. print('Average loss at step ', step, ': ', average_loss) average_loss = 0 # Note that this is expensive (~20% slowdown if computed every 500 steps) if step % 10000 == 0: sim = similarity.eval() for i in xrange(valid_size): valid_word = reverse_dictionary[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k + 1] log_str = 'Nearest to %s:' % valid_word for k in xrange(top_k): close_word = reverse_dictionary[nearest[k]] log_str = '%s %s,' % (log_str, close_word) print(log_str) final_embeddings = normalized_embeddings.eval() # Step 6: Visualize the embeddings. # pylint: disable=missing-docstring # Function to draw visualization of distance between embeddings. def plot_with_labels(low_dim_embs, labels, filename): assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings' plt.figure(figsize=(18, 18)) # in inches for i, label in enumerate(labels): x, y = low_dim_embs[i, :] plt.scatter(x, y) plt.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom') plt.savefig(filename) try: # pylint: disable=g-import-not-at-top from sklearn.manifold import TSNE import matplotlib.pyplot as plt tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000, method='exact') plot_only = 500 low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :]) labels = [reverse_dictionary[i] for i in xrange(plot_only)] plot_with_labels(low_dim_embs, labels, os.path.join(gettempdir(), 'tsne.png')) except ImportError as ex: print('Please install sklearn, matplotlib, and scipy to show embeddings.') print(ex)
apache-2.0
stylianos-kampakis/scikit-learn
examples/applications/svm_gui.py
287
11161
""" ========== Libsvm GUI ========== A simple graphical frontend for Libsvm mainly intended for didactic purposes. You can create data points by point and click and visualize the decision region induced by different kernels and parameter settings. To create positive examples click the left mouse button; to create negative examples click the right button. If all examples are from the same class, it uses a one-class SVM. """ from __future__ import division, print_function print(__doc__) # Author: Peter Prettenhoer <[email protected]> # # License: BSD 3 clause import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib.contour import ContourSet import Tkinter as Tk import sys import numpy as np from sklearn import svm from sklearn.datasets import dump_svmlight_file from sklearn.externals.six.moves import xrange y_min, y_max = -50, 50 x_min, x_max = -50, 50 class Model(object): """The Model which hold the data. It implements the observable in the observer pattern and notifies the registered observers on change event. """ def __init__(self): self.observers = [] self.surface = None self.data = [] self.cls = None self.surface_type = 0 def changed(self, event): """Notify the observers. """ for observer in self.observers: observer.update(event, self) def add_observer(self, observer): """Register an observer. """ self.observers.append(observer) def set_surface(self, surface): self.surface = surface def dump_svmlight_file(self, file): data = np.array(self.data) X = data[:, 0:2] y = data[:, 2] dump_svmlight_file(X, y, file) class Controller(object): def __init__(self, model): self.model = model self.kernel = Tk.IntVar() self.surface_type = Tk.IntVar() # Whether or not a model has been fitted self.fitted = False def fit(self): print("fit the model") train = np.array(self.model.data) X = train[:, 0:2] y = train[:, 2] C = float(self.complexity.get()) gamma = float(self.gamma.get()) coef0 = float(self.coef0.get()) degree = int(self.degree.get()) kernel_map = {0: "linear", 1: "rbf", 2: "poly"} if len(np.unique(y)) == 1: clf = svm.OneClassSVM(kernel=kernel_map[self.kernel.get()], gamma=gamma, coef0=coef0, degree=degree) clf.fit(X) else: clf = svm.SVC(kernel=kernel_map[self.kernel.get()], C=C, gamma=gamma, coef0=coef0, degree=degree) clf.fit(X, y) if hasattr(clf, 'score'): print("Accuracy:", clf.score(X, y) * 100) X1, X2, Z = self.decision_surface(clf) self.model.clf = clf self.model.set_surface((X1, X2, Z)) self.model.surface_type = self.surface_type.get() self.fitted = True self.model.changed("surface") def decision_surface(self, cls): delta = 1 x = np.arange(x_min, x_max + delta, delta) y = np.arange(y_min, y_max + delta, delta) X1, X2 = np.meshgrid(x, y) Z = cls.decision_function(np.c_[X1.ravel(), X2.ravel()]) Z = Z.reshape(X1.shape) return X1, X2, Z def clear_data(self): self.model.data = [] self.fitted = False self.model.changed("clear") def add_example(self, x, y, label): self.model.data.append((x, y, label)) self.model.changed("example_added") # update decision surface if already fitted. self.refit() def refit(self): """Refit the model if already fitted. """ if self.fitted: self.fit() class View(object): """Test docstring. """ def __init__(self, root, controller): f = Figure() ax = f.add_subplot(111) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim((x_min, x_max)) ax.set_ylim((y_min, y_max)) canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas.mpl_connect('button_press_event', self.onclick) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() self.controllbar = ControllBar(root, controller) self.f = f self.ax = ax self.canvas = canvas self.controller = controller self.contours = [] self.c_labels = None self.plot_kernels() def plot_kernels(self): self.ax.text(-50, -60, "Linear: $u^T v$") self.ax.text(-20, -60, "RBF: $\exp (-\gamma \| u-v \|^2)$") self.ax.text(10, -60, "Poly: $(\gamma \, u^T v + r)^d$") def onclick(self, event): if event.xdata and event.ydata: if event.button == 1: self.controller.add_example(event.xdata, event.ydata, 1) elif event.button == 3: self.controller.add_example(event.xdata, event.ydata, -1) def update_example(self, model, idx): x, y, l = model.data[idx] if l == 1: color = 'w' elif l == -1: color = 'k' self.ax.plot([x], [y], "%so" % color, scalex=0.0, scaley=0.0) def update(self, event, model): if event == "examples_loaded": for i in xrange(len(model.data)): self.update_example(model, i) if event == "example_added": self.update_example(model, -1) if event == "clear": self.ax.clear() self.ax.set_xticks([]) self.ax.set_yticks([]) self.contours = [] self.c_labels = None self.plot_kernels() if event == "surface": self.remove_surface() self.plot_support_vectors(model.clf.support_vectors_) self.plot_decision_surface(model.surface, model.surface_type) self.canvas.draw() def remove_surface(self): """Remove old decision surface.""" if len(self.contours) > 0: for contour in self.contours: if isinstance(contour, ContourSet): for lineset in contour.collections: lineset.remove() else: contour.remove() self.contours = [] def plot_support_vectors(self, support_vectors): """Plot the support vectors by placing circles over the corresponding data points and adds the circle collection to the contours list.""" cs = self.ax.scatter(support_vectors[:, 0], support_vectors[:, 1], s=80, edgecolors="k", facecolors="none") self.contours.append(cs) def plot_decision_surface(self, surface, type): X1, X2, Z = surface if type == 0: levels = [-1.0, 0.0, 1.0] linestyles = ['dashed', 'solid', 'dashed'] colors = 'k' self.contours.append(self.ax.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)) elif type == 1: self.contours.append(self.ax.contourf(X1, X2, Z, 10, cmap=matplotlib.cm.bone, origin='lower', alpha=0.85)) self.contours.append(self.ax.contour(X1, X2, Z, [0.0], colors='k', linestyles=['solid'])) else: raise ValueError("surface type unknown") class ControllBar(object): def __init__(self, root, controller): fm = Tk.Frame(root) kernel_group = Tk.Frame(fm) Tk.Radiobutton(kernel_group, text="Linear", variable=controller.kernel, value=0, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(kernel_group, text="RBF", variable=controller.kernel, value=1, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(kernel_group, text="Poly", variable=controller.kernel, value=2, command=controller.refit).pack(anchor=Tk.W) kernel_group.pack(side=Tk.LEFT) valbox = Tk.Frame(fm) controller.complexity = Tk.StringVar() controller.complexity.set("1.0") c = Tk.Frame(valbox) Tk.Label(c, text="C:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(c, width=6, textvariable=controller.complexity).pack( side=Tk.LEFT) c.pack() controller.gamma = Tk.StringVar() controller.gamma.set("0.01") g = Tk.Frame(valbox) Tk.Label(g, text="gamma:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(g, width=6, textvariable=controller.gamma).pack(side=Tk.LEFT) g.pack() controller.degree = Tk.StringVar() controller.degree.set("3") d = Tk.Frame(valbox) Tk.Label(d, text="degree:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(d, width=6, textvariable=controller.degree).pack(side=Tk.LEFT) d.pack() controller.coef0 = Tk.StringVar() controller.coef0.set("0") r = Tk.Frame(valbox) Tk.Label(r, text="coef0:", anchor="e", width=7).pack(side=Tk.LEFT) Tk.Entry(r, width=6, textvariable=controller.coef0).pack(side=Tk.LEFT) r.pack() valbox.pack(side=Tk.LEFT) cmap_group = Tk.Frame(fm) Tk.Radiobutton(cmap_group, text="Hyperplanes", variable=controller.surface_type, value=0, command=controller.refit).pack(anchor=Tk.W) Tk.Radiobutton(cmap_group, text="Surface", variable=controller.surface_type, value=1, command=controller.refit).pack(anchor=Tk.W) cmap_group.pack(side=Tk.LEFT) train_button = Tk.Button(fm, text='Fit', width=5, command=controller.fit) train_button.pack() fm.pack(side=Tk.LEFT) Tk.Button(fm, text='Clear', width=5, command=controller.clear_data).pack(side=Tk.LEFT) def get_parser(): from optparse import OptionParser op = OptionParser() op.add_option("--output", action="store", type="str", dest="output", help="Path where to dump data.") return op def main(argv): op = get_parser() opts, args = op.parse_args(argv[1:]) root = Tk.Tk() model = Model() controller = Controller(model) root.wm_title("Scikit-learn Libsvm GUI") view = View(root, controller) model.add_observer(view) Tk.mainloop() if opts.output: model.dump_svmlight_file(opts.output) if __name__ == "__main__": main(sys.argv)
bsd-3-clause
zihua/scikit-learn
sklearn/cluster/__init__.py
364
1228
""" The :mod:`sklearn.cluster` module gathers popular unsupervised clustering algorithms. """ from .spectral import spectral_clustering, SpectralClustering from .mean_shift_ import (mean_shift, MeanShift, estimate_bandwidth, get_bin_seeds) from .affinity_propagation_ import affinity_propagation, AffinityPropagation from .hierarchical import (ward_tree, AgglomerativeClustering, linkage_tree, FeatureAgglomeration) from .k_means_ import k_means, KMeans, MiniBatchKMeans from .dbscan_ import dbscan, DBSCAN from .bicluster import SpectralBiclustering, SpectralCoclustering from .birch import Birch __all__ = ['AffinityPropagation', 'AgglomerativeClustering', 'Birch', 'DBSCAN', 'KMeans', 'FeatureAgglomeration', 'MeanShift', 'MiniBatchKMeans', 'SpectralClustering', 'affinity_propagation', 'dbscan', 'estimate_bandwidth', 'get_bin_seeds', 'k_means', 'linkage_tree', 'mean_shift', 'spectral_clustering', 'ward_tree', 'SpectralBiclustering', 'SpectralCoclustering']
bsd-3-clause
imaculate/scikit-learn
sklearn/ensemble/tests/test_iforest.py
9
6928
""" Testing for Isolation Forest algorithm (sklearn.ensemble.iforest). """ # Authors: Nicolas Goix <[email protected]> # Alexandre Gramfort <[email protected]> # License: BSD 3 clause import numpy as np from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_warns_message from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_no_warnings from sklearn.utils.testing import assert_greater from sklearn.utils.testing import ignore_warnings from sklearn.grid_search import ParameterGrid from sklearn.ensemble import IsolationForest from sklearn.model_selection import train_test_split from sklearn.datasets import load_boston, load_iris from sklearn.utils import check_random_state from sklearn.metrics import roc_auc_score from scipy.sparse import csc_matrix, csr_matrix rng = check_random_state(0) # load the iris dataset # and randomly permute it iris = load_iris() perm = rng.permutation(iris.target.size) iris.data = iris.data[perm] iris.target = iris.target[perm] # also load the boston dataset # and randomly permute it boston = load_boston() perm = rng.permutation(boston.target.size) boston.data = boston.data[perm] boston.target = boston.target[perm] def test_iforest(): """Check Isolation Forest for various parameter settings.""" X_train = np.array([[0, 1], [1, 2]]) X_test = np.array([[2, 1], [1, 1]]) grid = ParameterGrid({"n_estimators": [3], "max_samples": [0.5, 1.0, 3], "bootstrap": [True, False]}) with ignore_warnings(): for params in grid: IsolationForest(random_state=rng, **params).fit(X_train).predict(X_test) def test_iforest_sparse(): """Check IForest for various parameter settings on sparse input.""" rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data[:50], boston.target[:50], random_state=rng) grid = ParameterGrid({"max_samples": [0.5, 1.0], "bootstrap": [True, False]}) for sparse_format in [csc_matrix, csr_matrix]: X_train_sparse = sparse_format(X_train) X_test_sparse = sparse_format(X_test) for params in grid: # Trained on sparse format sparse_classifier = IsolationForest( n_estimators=10, random_state=1, **params).fit(X_train_sparse) sparse_results = sparse_classifier.predict(X_test_sparse) # Trained on dense format dense_classifier = IsolationForest( n_estimators=10, random_state=1, **params).fit(X_train) dense_results = dense_classifier.predict(X_test) assert_array_equal(sparse_results, dense_results) assert_array_equal(sparse_results, dense_results) def test_iforest_error(): """Test that it gives proper exception on deficient input.""" X = iris.data # Test max_samples assert_raises(ValueError, IsolationForest(max_samples=-1).fit, X) assert_raises(ValueError, IsolationForest(max_samples=0.0).fit, X) assert_raises(ValueError, IsolationForest(max_samples=2.0).fit, X) # The dataset has less than 256 samples, explicitly setting # max_samples > n_samples should result in a warning. If not set # explicitly there should be no warning assert_warns_message(UserWarning, "max_samples will be set to n_samples for estimation", IsolationForest(max_samples=1000).fit, X) assert_no_warnings(IsolationForest(max_samples='auto').fit, X) assert_no_warnings(IsolationForest(max_samples=np.int64(2)).fit, X) assert_raises(ValueError, IsolationForest(max_samples='foobar').fit, X) assert_raises(ValueError, IsolationForest(max_samples=1.5).fit, X) def test_recalculate_max_depth(): """Check max_depth recalculation when max_samples is reset to n_samples""" X = iris.data clf = IsolationForest().fit(X) for est in clf.estimators_: assert_equal(est.max_depth, int(np.ceil(np.log2(X.shape[0])))) def test_max_samples_attribute(): X = iris.data clf = IsolationForest().fit(X) assert_equal(clf.max_samples_, X.shape[0]) clf = IsolationForest(max_samples=500) assert_warns_message(UserWarning, "max_samples will be set to n_samples for estimation", clf.fit, X) assert_equal(clf.max_samples_, X.shape[0]) clf = IsolationForest(max_samples=0.4).fit(X) assert_equal(clf.max_samples_, 0.4*X.shape[0]) def test_iforest_parallel_regression(): """Check parallel regression.""" rng = check_random_state(0) X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=rng) ensemble = IsolationForest(n_jobs=3, random_state=0).fit(X_train) ensemble.set_params(n_jobs=1) y1 = ensemble.predict(X_test) ensemble.set_params(n_jobs=2) y2 = ensemble.predict(X_test) assert_array_almost_equal(y1, y2) ensemble = IsolationForest(n_jobs=1, random_state=0).fit(X_train) y3 = ensemble.predict(X_test) assert_array_almost_equal(y1, y3) def test_iforest_performance(): """Test Isolation Forest performs well""" # Generate train/test data rng = check_random_state(2) X = 0.3 * rng.randn(120, 2) X_train = np.r_[X + 2, X - 2] X_train = X[:100] # Generate some abnormal novel observations X_outliers = rng.uniform(low=-4, high=4, size=(20, 2)) X_test = np.r_[X[100:], X_outliers] y_test = np.array([0] * 20 + [1] * 20) # fit the model clf = IsolationForest(max_samples=100, random_state=rng).fit(X_train) # predict scores (the lower, the more normal) y_pred = - clf.decision_function(X_test) # check that there is at most 6 errors (false positive or false negative) assert_greater(roc_auc_score(y_test, y_pred), 0.98) def test_iforest_works(): # toy sample (the last two samples are outliers) X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [6, 3], [-4, 7]] # Test LOF clf = IsolationForest(random_state=rng, contamination=0.25) clf.fit(X) decision_func = - clf.decision_function(X) pred = clf.predict(X) # assert detect outliers: assert_greater(np.min(decision_func[-2:]), np.max(decision_func[:-2])) assert_array_equal(pred, 6 * [1] + 2 * [-1])
bsd-3-clause
siutanwong/scikit-learn
examples/manifold/plot_manifold_sphere.py
258
5101
#!/usr/bin/python # -*- coding: utf-8 -*- """ ============================================= Manifold Learning methods on a severed sphere ============================================= An application of the different :ref:`manifold` techniques on a spherical data-set. Here one can see the use of dimensionality reduction in order to gain some intuition regarding the manifold learning methods. Regarding the dataset, the poles are cut from the sphere, as well as a thin slice down its side. This enables the manifold learning techniques to 'spread it open' whilst projecting it onto two dimensions. For a similar example, where the methods are applied to the S-curve dataset, see :ref:`example_manifold_plot_compare_methods.py` Note that the purpose of the :ref:`MDS <multidimensional_scaling>` is to find a low-dimensional representation of the data (here 2D) in which the distances respect well the distances in the original high-dimensional space, unlike other manifold-learning algorithms, it does not seeks an isotropic representation of the data in the low-dimensional space. Here the manifold problem matches fairly that of representing a flat map of the Earth, as with `map projection <http://en.wikipedia.org/wiki/Map_projection>`_ """ # Author: Jaques Grobler <[email protected]> # License: BSD 3 clause print(__doc__) from time import time import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter from sklearn import manifold from sklearn.utils import check_random_state # Next line to silence pyflakes. Axes3D # Variables for manifold learning. n_neighbors = 10 n_samples = 1000 # Create our sphere. random_state = check_random_state(0) p = random_state.rand(n_samples) * (2 * np.pi - 0.55) t = random_state.rand(n_samples) * np.pi # Sever the poles from the sphere. indices = ((t < (np.pi - (np.pi / 8))) & (t > ((np.pi / 8)))) colors = p[indices] x, y, z = np.sin(t[indices]) * np.cos(p[indices]), \ np.sin(t[indices]) * np.sin(p[indices]), \ np.cos(t[indices]) # Plot our dataset. fig = plt.figure(figsize=(15, 8)) plt.suptitle("Manifold Learning with %i points, %i neighbors" % (1000, n_neighbors), fontsize=14) ax = fig.add_subplot(251, projection='3d') ax.scatter(x, y, z, c=p[indices], cmap=plt.cm.rainbow) try: # compatibility matplotlib < 1.0 ax.view_init(40, -10) except: pass sphere_data = np.array([x, y, z]).T # Perform Locally Linear Embedding Manifold learning methods = ['standard', 'ltsa', 'hessian', 'modified'] labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE'] for i, method in enumerate(methods): t0 = time() trans_data = manifold\ .LocallyLinearEmbedding(n_neighbors, 2, method=method).fit_transform(sphere_data).T t1 = time() print("%s: %.2g sec" % (methods[i], t1 - t0)) ax = fig.add_subplot(252 + i) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("%s (%.2g sec)" % (labels[i], t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') # Perform Isomap Manifold learning. t0 = time() trans_data = manifold.Isomap(n_neighbors, n_components=2)\ .fit_transform(sphere_data).T t1 = time() print("%s: %.2g sec" % ('ISO', t1 - t0)) ax = fig.add_subplot(257) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("%s (%.2g sec)" % ('Isomap', t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') # Perform Multi-dimensional scaling. t0 = time() mds = manifold.MDS(2, max_iter=100, n_init=1) trans_data = mds.fit_transform(sphere_data).T t1 = time() print("MDS: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(258) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("MDS (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') # Perform Spectral Embedding. t0 = time() se = manifold.SpectralEmbedding(n_components=2, n_neighbors=n_neighbors) trans_data = se.fit_transform(sphere_data).T t1 = time() print("Spectral Embedding: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(259) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("Spectral Embedding (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') # Perform t-distributed stochastic neighbor embedding. t0 = time() tsne = manifold.TSNE(n_components=2, init='pca', random_state=0) trans_data = tsne.fit_transform(sphere_data).T t1 = time() print("t-SNE: %.2g sec" % (t1 - t0)) ax = fig.add_subplot(250) plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow) plt.title("t-SNE (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') plt.show()
bsd-3-clause
mehdidc/scikit-learn
sklearn/svm/classes.py
3
36924
import warnings import numpy as np from .base import _fit_liblinear, BaseSVC, BaseLibSVM from ..base import BaseEstimator, RegressorMixin from ..linear_model.base import LinearClassifierMixin, SparseCoefMixin, \ LinearModel from ..feature_selection.from_model import _LearntSelectorMixin from ..utils import check_X_y class LinearSVC(BaseEstimator, LinearClassifierMixin, _LearntSelectorMixin, SparseCoefMixin): """Linear Support Vector Classification. Similar to SVC with parameter kernel='linear', but implemented in terms of liblinear rather than libsvm, so it has more flexibility in the choice of penalties and loss functions and should scale better (to large numbers of samples). This class supports both dense and sparse input and the multiclass support is handled according to a one-vs-the-rest scheme. Parameters ---------- C : float, optional (default=1.0) Penalty parameter C of the error term. loss : string, 'hinge' or 'squared_hinge' (default='squared_hinge') Specifies the loss function. 'hinge' is the standard SVM loss (used e.g. by the SVC class) while 'squared_hinge' is the square of the hinge loss. penalty : string, 'l1' or 'l2' (default='l2') Specifies the norm used in the penalization. The 'l2' penalty is the standard used in SVC. The 'l1' leads to `coef_` vectors that are sparse. dual : bool, (default=True) Select the algorithm to either solve the dual or primal optimization problem. Prefer dual=False when n_samples > n_features. tol : float, optional (default=1e-4) Tolerance for stopping criteria. multi_class: string, 'ovr' or 'crammer_singer' (default='ovr') Determines the multi-class strategy if `y` contains more than two classes. `ovr` trains n_classes one-vs-rest classifiers, while `crammer_singer` optimizes a joint objective over all classes. While `crammer_singer` is interesting from an theoretical perspective as it is consistent it is seldom used in practice and rarely leads to better accuracy and is more expensive to compute. If `crammer_singer` is chosen, the options loss, penalty and dual will be ignored. fit_intercept : boolean, optional (default=True) Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). intercept_scaling : float, optional (default=1) When self.fit_intercept is True, instance vector x becomes [x, self.intercept_scaling], i.e. a "synthetic" feature with constant value equals to intercept_scaling is appended to the instance vector. The intercept becomes intercept_scaling * synthetic feature weight Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased class_weight : {dict, 'auto'}, optional Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. The 'auto' mode uses the values of y to automatically adjust weights inversely proportional to class frequencies. verbose : int, (default=0) Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in liblinear that, if enabled, may not work properly in a multithreaded context. random_state : int seed, RandomState instance, or None (default=None) The seed of the pseudo random number generator to use when shuffling the data. max_iter : int, (default=1000) The maximum number of iterations to be run. Attributes ---------- coef_ : array, shape = [n_features] if n_classes == 2 \ else [n_classes, n_features] Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is a readonly property derived from `raw_coef_` that \ follows the internal memory layout of liblinear. intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] Constants in decision function. Notes ----- The underlying C implementation uses a random number generator to select features when fitting the model. It is thus not uncommon, to have slightly different results for the same input data. If that happens, try with a smaller tol parameter. The underlying implementation (liblinear) uses a sparse internal representation for the data that will incur a memory copy. Predict output may not match that of standalone liblinear in certain cases. See :ref:`differences from liblinear <liblinear_differences>` in the narrative documentation. **References:** `LIBLINEAR: A Library for Large Linear Classification <http://www.csie.ntu.edu.tw/~cjlin/liblinear/>`__ See also -------- SVC Implementation of Support Vector Machine classifier using libsvm: the kernel can be non-linear but its SMO algorithm does not scale to large number of samples as LinearSVC does. Furthermore SVC multi-class mode is implemented using one vs one scheme while LinearSVC uses one vs the rest. It is possible to implement one vs the rest with SVC by using the :class:`sklearn.multiclass.OneVsRestClassifier` wrapper. Finally SVC can fit dense data without memory copy if the input is C-contiguous. Sparse data will still incur memory copy though. sklearn.linear_model.SGDClassifier SGDClassifier can optimize the same cost function as LinearSVC by adjusting the penalty and loss parameters. In addition it requires less memory, allows incremental (online) learning, and implements various loss functions and regularization regimes. """ def __init__(self, penalty='l2', loss='squared_hinge', dual=True, tol=1e-4, C=1.0, multi_class='ovr', fit_intercept=True, intercept_scaling=1, class_weight=None, verbose=0, random_state=None, max_iter=1000): self.dual = dual self.tol = tol self.C = C self.multi_class = multi_class self.fit_intercept = fit_intercept self.intercept_scaling = intercept_scaling self.class_weight = class_weight self.verbose = verbose self.random_state = random_state self.max_iter = max_iter self.penalty = penalty self.loss = loss def fit(self, X, y): """Fit the model according to the given training data. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vector, where n_samples in the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] Target vector relative to X Returns ------- self : object Returns self. """ # FIXME Remove l1/l2 support in 1.0 ----------------------------------- loss_l = self.loss.lower() msg = ("loss='%s' has been deprecated in favor of " "loss='%s' as of 0.16. Backward compatibility" " for the loss='%s' will be removed in %s") # FIXME change loss_l --> self.loss after 0.18 if loss_l in ('l1', 'l2'): old_loss = self.loss self.loss = {'l1': 'hinge', 'l2': 'squared_hinge'}.get(loss_l) warnings.warn(msg % (old_loss, self.loss, old_loss, '1.0'), DeprecationWarning) # --------------------------------------------------------------------- if self.C < 0: raise ValueError("Penalty term must be positive; got (C=%r)" % self.C) X, y = check_X_y(X, y, accept_sparse='csr', dtype=np.float64, order="C") self.classes_ = np.unique(y) self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear( X, y, self.C, self.fit_intercept, self.intercept_scaling, self.class_weight, self.penalty, self.dual, self.verbose, self.max_iter, self.tol, self.random_state, self.multi_class, self.loss ) if self.multi_class == "crammer_singer" and len(self.classes_) == 2: self.coef_ = (self.coef_[1] - self.coef_[0]).reshape(1, -1) if self.fit_intercept: intercept = self.intercept_[1] - self.intercept_[0] self.intercept_ = np.array([intercept]) return self class LinearSVR(LinearModel, RegressorMixin): """Linear Support Vector Regression. Similar to SVR with parameter kernel='linear', but implemented in terms of liblinear rather than libsvm, so it has more flexibility in the choice of penalties and loss functions and should scale better (to large numbers of samples). This class supports both dense and sparse input. Parameters ---------- C : float, optional (default=1.0) Penalty parameter C of the error term. The penalty is a squared l2 penalty. The bigger this parameter, the less regularization is used. loss : string, 'epsilon_insensitive' or 'squared_epsilon_insensitive' (default='epsilon_insensitive') Specifies the loss function. 'l1' is the epsilon-insensitive loss (standard SVR) while 'l2' is the squared epsilon-insensitive loss. epsilon : float, optional (default=0.1) Epsilon parameter in the epsilon-insensitive loss function. Note that the value of this parameter depends on the scale of the target variable y. If unsure, set epsilon=0. dual : bool, (default=True) Select the algorithm to either solve the dual or primal optimization problem. Prefer dual=False when n_samples > n_features. tol : float, optional (default=1e-4) Tolerance for stopping criteria. fit_intercept : boolean, optional (default=True) Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). intercept_scaling : float, optional (default=1) When self.fit_intercept is True, instance vector x becomes [x, self.intercept_scaling], i.e. a "synthetic" feature with constant value equals to intercept_scaling is appended to the instance vector. The intercept becomes intercept_scaling * synthetic feature weight Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased. verbose : int, (default=0) Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in liblinear that, if enabled, may not work properly in a multithreaded context. random_state : int seed, RandomState instance, or None (default=None) The seed of the pseudo random number generator to use when shuffling the data. max_iter : int, (default=1000) The maximum number of iterations to be run. Attributes ---------- coef_ : array, shape = [n_features] if n_classes == 2 \ else [n_classes, n_features] Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is a readonly property derived from `raw_coef_` that \ follows the internal memory layout of liblinear. intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] Constants in decision function. See also -------- LinearSVC Implementation of Support Vector Machine classifier using the same library as this class (liblinear). SVR Implementation of Support Vector Machine regression using libsvm: the kernel can be non-linear but its SMO algorithm does not scale to large number of samples as LinearSVC does. sklearn.linear_model.SGDRegressor SGDRegressor can optimize the same cost function as LinearSVR by adjusting the penalty and loss parameters. In addition it requires less memory, allows incremental (online) learning, and implements various loss functions and regularization regimes. """ def __init__(self, epsilon=0.0, tol=1e-4, C=1.0, loss='epsilon_insensitive', fit_intercept=True, intercept_scaling=1., dual=True, verbose=0, random_state=None, max_iter=1000): self.tol = tol self.C = C self.epsilon = epsilon self.fit_intercept = fit_intercept self.intercept_scaling = intercept_scaling self.verbose = verbose self.random_state = random_state self.max_iter = max_iter self.dual = dual self.loss = loss def fit(self, X, y): """Fit the model according to the given training data. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vector, where n_samples in the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] Target vector relative to X Returns ------- self : object Returns self. """ # FIXME Remove l1/l2 support in 1.0 ----------------------------------- loss_l = self.loss.lower() msg = ("loss='%s' has been deprecated in favor of " "loss='%s' as of 0.16. Backward compatibility" " for the loss='%s' will be removed in %s") # FIXME change loss_l --> self.loss after 0.18 if loss_l in ('l1', 'l2'): old_loss = self.loss self.loss = {'l1': 'epsilon_insensitive', 'l2': 'squared_epsilon_insensitive' }.get(loss_l) warnings.warn(msg % (old_loss, self.loss, old_loss, '1.0'), DeprecationWarning) # --------------------------------------------------------------------- if self.C < 0: raise ValueError("Penalty term must be positive; got (C=%r)" % self.C) X, y = check_X_y(X, y, accept_sparse='csr', dtype=np.float64, order="C") penalty = 'l2' # SVR only accepts l2 penalty self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear( X, y, self.C, self.fit_intercept, self.intercept_scaling, None, penalty, self.dual, self.verbose, self.max_iter, self.tol, self.random_state, loss=self.loss, epsilon=self.epsilon) self.coef_ = self.coef_.ravel() return self class SVC(BaseSVC): """C-Support Vector Classification. The implementation is based on libsvm. The fit time complexity is more than quadratic with the number of samples which makes it hard to scale to dataset with more than a couple of 10000 samples. The multiclass support is handled according to a one-vs-one scheme. For details on the precise mathematical formulation of the provided kernel functions and how `gamma`, `coef0` and `degree` affect each other, see the corresponding section in the narrative documentation: :ref:`svm_kernels`. .. The narrative documentation is available at http://scikit-learn.org/ Parameters ---------- C : float, optional (default=1.0) Penalty parameter C of the error term. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. degree : int, optional (default=3) Degree of the polynomial kernel function ('poly'). Ignored by all other kernels. gamma : float, optional (default=0.0) Kernel coefficient for 'rbf', 'poly' and 'sigmoid'. If gamma is 0.0 then 1/n_features will be used instead. coef0 : float, optional (default=0.0) Independent term in kernel function. It is only significant in 'poly' and 'sigmoid'. probability: boolean, optional (default=False) Whether to enable probability estimates. This must be enabled prior to calling `fit`, and will slow down that method. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. tol : float, optional (default=1e-3) Tolerance for stopping criterion. cache_size : float, optional Specify the size of the kernel cache (in MB). class_weight : {dict, 'auto'}, optional Set the parameter C of class i to class_weight[i]*C for SVC. If not given, all classes are supposed to have weight one. The 'auto' mode uses the values of y to automatically adjust weights inversely proportional to class frequencies. verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data for probability estimation. Attributes ---------- support_ : array-like, shape = [n_SV] Indices of support vectors. support_vectors_ : array-like, shape = [n_SV, n_features] Support vectors. n_support_ : array-like, dtype=int32, shape = [n_class] Number of support vectors for each class. dual_coef_ : array, shape = [n_class-1, n_SV] Coefficients of the support vector in the decision function. \ For multiclass, coefficient for all 1-vs-1 classifiers. \ The layout of the coefficients in the multiclass case is somewhat \ non-trivial. See the section about multi-class classification in the \ SVM section of the User Guide for details. coef_ : array, shape = [n_class-1, n_features] Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is a readonly property derived from `dual_coef_` and `support_vectors_`. intercept_ : array, shape = [n_class * (n_class-1) / 2] Constants in decision function. Examples -------- >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) >>> y = np.array([1, 1, 2, 2]) >>> from sklearn.svm import SVC >>> clf = SVC() >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) >>> print(clf.predict([[-0.8, -1]])) [1] See also -------- SVR Support Vector Machine for Regression implemented using libsvm. LinearSVC Scalable Linear Support Vector Machine for classification implemented using liblinear. Check the See also section of LinearSVC for more comparison element. """ def __init__(self, C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False, tol=1e-3, cache_size=200, class_weight=None, verbose=False, max_iter=-1, random_state=None): super(SVC, self).__init__( 'c_svc', kernel, degree, gamma, coef0, tol, C, 0., 0., shrinking, probability, cache_size, class_weight, verbose, max_iter, random_state) class NuSVC(BaseSVC): """Nu-Support Vector Classification. Similar to SVC but uses a parameter to control the number of support vectors. The implementation is based on libsvm. Parameters ---------- nu : float, optional (default=0.5) An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. degree : int, optional (default=3) Degree of kernel function is significant only in poly, rbf, sigmoid. gamma : float, optional (default=0.0) Kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) Independent term in kernel function. It is only significant in poly/sigmoid. probability: boolean, optional (default=False) Whether to enable probability estimates. This must be enabled prior to calling `fit`, and will slow down that method. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. tol : float, optional (default=1e-3) Tolerance for stopping criterion. cache_size : float, optional Specify the size of the kernel cache (in MB). verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data for probability estimation. Attributes ---------- support_ : array-like, shape = [n_SV] Indices of support vectors. support_vectors_ : array-like, shape = [n_SV, n_features] Support vectors. n_support_ : array-like, dtype=int32, shape = [n_class] Number of support vector for each class. dual_coef_ : array, shape = [n_class-1, n_SV] Coefficients of the support vector in the decision function. \ For multiclass, coefficient for all 1-vs-1 classifiers. \ The layout of the coefficients in the multiclass case is somewhat \ non-trivial. See the section about multi-class classification in \ the SVM section of the User Guide for details. coef_ : array, shape = [n_class-1, n_features] Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_`. intercept_ : array, shape = [n_class * (n_class-1) / 2] Constants in decision function. Examples -------- >>> import numpy as np >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) >>> y = np.array([1, 1, 2, 2]) >>> from sklearn.svm import NuSVC >>> clf = NuSVC() >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE NuSVC(cache_size=200, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, nu=0.5, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) >>> print(clf.predict([[-0.8, -1]])) [1] See also -------- SVC Support Vector Machine for classification using libsvm. LinearSVC Scalable linear Support Vector Machine for classification using liblinear. """ def __init__(self, nu=0.5, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, probability=False, tol=1e-3, cache_size=200, verbose=False, max_iter=-1, random_state=None): super(NuSVC, self).__init__( 'nu_svc', kernel, degree, gamma, coef0, tol, 0., nu, 0., shrinking, probability, cache_size, None, verbose, max_iter, random_state) class SVR(BaseLibSVM, RegressorMixin): """Epsilon-Support Vector Regression. The free parameters in the model are C and epsilon. The implementation is based on libsvm. Parameters ---------- C : float, optional (default=1.0) Penalty parameter C of the error term. epsilon : float, optional (default=0.1) Epsilon in the epsilon-SVR model. It specifies the epsilon-tube within which no penalty is associated in the training loss function with points predicted within a distance epsilon from the actual value. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. degree : int, optional (default=3) Degree of kernel function is significant only in poly, rbf, sigmoid. gamma : float, optional (default=0.0) Kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) independent term in kernel function. It is only significant in poly/sigmoid. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. tol : float, optional (default=1e-3) Tolerance for stopping criterion. cache_size : float, optional Specify the size of the kernel cache (in MB). verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. Attributes ---------- support_ : array-like, shape = [n_SV] Indices of support vectors. support_vectors_ : array-like, shape = [nSV, n_features] Support vectors. dual_coef_ : array, shape = [1, n_SV] Coefficients of the support vector in the decision function. coef_ : array, shape = [1, n_features] Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_`. intercept_ : array, shape = [1] Constants in decision function. Examples -------- >>> from sklearn.svm import SVR >>> import numpy as np >>> n_samples, n_features = 10, 5 >>> np.random.seed(0) >>> y = np.random.randn(n_samples) >>> X = np.random.randn(n_samples, n_features) >>> clf = SVR(C=1.0, epsilon=0.2) >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.2, gamma=0.0, kernel='rbf', max_iter=-1, shrinking=True, tol=0.001, verbose=False) See also -------- NuSVR Support Vector Machine for regression implemented using libsvm using a parameter to control the number of support vectors. LinearSVR Scalable Linear Support Vector Machine for regression implemented using liblinear. """ def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, C=1.0, epsilon=0.1, shrinking=True, cache_size=200, verbose=False, max_iter=-1): super(SVR, self).__init__( 'epsilon_svr', kernel=kernel, degree=degree, gamma=gamma, coef0=coef0, tol=tol, C=C, nu=0., epsilon=epsilon, verbose=verbose, shrinking=shrinking, probability=False, cache_size=cache_size, class_weight=None, max_iter=max_iter, random_state=None) class NuSVR(BaseLibSVM, RegressorMixin): """Nu Support Vector Regression. Similar to NuSVC, for regression, uses a parameter nu to control the number of support vectors. However, unlike NuSVC, where nu replaces C, here nu replaces the parameter epsilon of epsilon-SVR. The implementation is based on libsvm. Parameters ---------- C : float, optional (default=1.0) Penalty parameter C of the error term. nu : float, optional An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By default 0.5 will be taken. kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. degree : int, optional (default=3) Degree of kernel function is significant only in poly, rbf, sigmoid. gamma : float, optional (default=0.0) Kernel coefficient for rbf and poly, if gamma is 0.0 then 1/n_features will be taken. coef0 : float, optional (default=0.0) Independent term in kernel function. It is only significant in poly/sigmoid. shrinking: boolean, optional (default=True) Whether to use the shrinking heuristic. tol : float, optional (default=1e-3) Tolerance for stopping criterion. cache_size : float, optional Specify the size of the kernel cache (in MB). verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. Attributes ---------- support_ : array-like, shape = [n_SV] Indices of support vectors. support_vectors_ : array-like, shape = [nSV, n_features] Support vectors. dual_coef_ : array, shape = [1, n_SV] Coefficients of the support vector in the decision function. coef_ : array, shape = [1, n_features] Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_`. intercept_ : array, shape = [1] Constants in decision function. Examples -------- >>> from sklearn.svm import NuSVR >>> import numpy as np >>> n_samples, n_features = 10, 5 >>> np.random.seed(0) >>> y = np.random.randn(n_samples) >>> X = np.random.randn(n_samples, n_features) >>> clf = NuSVR(C=1.0, nu=0.1) >>> clf.fit(X, y) #doctest: +NORMALIZE_WHITESPACE NuSVR(C=1.0, cache_size=200, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', max_iter=-1, nu=0.1, shrinking=True, tol=0.001, verbose=False) See also -------- NuSVC Support Vector Machine for classification implemented with libsvm with a parameter to control the number of support vectors. SVR epsilon Support Vector Machine for regression implemented with libsvm. """ def __init__(self, nu=0.5, C=1.0, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, shrinking=True, tol=1e-3, cache_size=200, verbose=False, max_iter=-1): super(NuSVR, self).__init__( 'nu_svr', kernel=kernel, degree=degree, gamma=gamma, coef0=coef0, tol=tol, C=C, nu=nu, epsilon=0., shrinking=shrinking, probability=False, cache_size=cache_size, class_weight=None, verbose=verbose, max_iter=max_iter, random_state=None) class OneClassSVM(BaseLibSVM): """Unsupervised Outlier Detection. Estimate the support of a high-dimensional distribution. The implementation is based on libsvm. Parameters ---------- kernel : string, optional (default='rbf') Specifies the kernel type to be used in the algorithm. It must be one of 'linear', 'poly', 'rbf', 'sigmoid', 'precomputed' or a callable. If none is given, 'rbf' will be used. If a callable is given it is used to precompute the kernel matrix. nu : float, optional An upper bound on the fraction of training errors and a lower bound of the fraction of support vectors. Should be in the interval (0, 1]. By default 0.5 will be taken. degree : int, optional (default=3) Degree of the polynomial kernel function ('poly'). Ignored by all other kernels. gamma : float, optional (default=0.0) Kernel coefficient for 'rbf', 'poly' and 'sigmoid'. If gamma is 0.0 then 1/n_features will be used instead. coef0 : float, optional (default=0.0) Independent term in kernel function. It is only significant in 'poly' and 'sigmoid'. tol : float, optional Tolerance for stopping criterion. shrinking: boolean, optional Whether to use the shrinking heuristic. cache_size : float, optional Specify the size of the kernel cache (in MB). verbose : bool, default: False Enable verbose output. Note that this setting takes advantage of a per-process runtime setting in libsvm that, if enabled, may not work properly in a multithreaded context. max_iter : int, optional (default=-1) Hard limit on iterations within solver, or -1 for no limit. random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data for probability estimation. Attributes ---------- support_ : array-like, shape = [n_SV] Indices of support vectors. support_vectors_ : array-like, shape = [nSV, n_features] Support vectors. dual_coef_ : array, shape = [n_classes-1, n_SV] Coefficients of the support vectors in the decision function. coef_ : array, shape = [n_classes-1, n_features] Weights assigned to the features (coefficients in the primal problem). This is only available in the case of linear kernel. `coef_` is readonly property derived from `dual_coef_` and `support_vectors_` intercept_ : array, shape = [n_classes-1] Constants in decision function. """ def __init__(self, kernel='rbf', degree=3, gamma=0.0, coef0=0.0, tol=1e-3, nu=0.5, shrinking=True, cache_size=200, verbose=False, max_iter=-1, random_state=None): super(OneClassSVM, self).__init__( 'one_class', kernel, degree, gamma, coef0, tol, 0., nu, 0., shrinking, False, cache_size, None, verbose, max_iter, random_state) def fit(self, X, y=None, sample_weight=None, **params): """ Detects the soft boundary of the set of samples X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Set of samples, where n_samples is the number of samples and n_features is the number of features. sample_weight : array-like, shape (n_samples,) Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points. Returns ------- self : object Returns self. Notes ----- If X is not a C-ordered contiguous array it is copied. """ super(OneClassSVM, self).fit(X, [], sample_weight=sample_weight, **params) return self
bsd-3-clause
CforED/Machine-Learning
examples/exercises/plot_iris_exercise.py
323
1602
""" ================================ SVM Exercise ================================ A tutorial exercise for using different SVM kernels. This exercise is used in the :ref:`using_kernels_tut` part of the :ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, svm iris = datasets.load_iris() X = iris.data y = iris.target X = X[y != 0, :2] y = y[y != 0] n_sample = len(X) np.random.seed(0) order = np.random.permutation(n_sample) X = X[order] y = y[order].astype(np.float) X_train = X[:.9 * n_sample] y_train = y[:.9 * n_sample] X_test = X[.9 * n_sample:] y_test = y[.9 * n_sample:] # fit the model for fig_num, kernel in enumerate(('linear', 'rbf', 'poly')): clf = svm.SVC(kernel=kernel, gamma=10) clf.fit(X_train, y_train) plt.figure(fig_num) plt.clf() plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired) # Circle out the test data plt.scatter(X_test[:, 0], X_test[:, 1], s=80, facecolors='none', zorder=10) plt.axis('tight') x_min = X[:, 0].min() x_max = X[:, 0].max() y_min = X[:, 1].min() y_max = X[:, 1].max() XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]) # Put the result into a color plot Z = Z.reshape(XX.shape) plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired) plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'], levels=[-.5, 0, .5]) plt.title(kernel) plt.show()
bsd-3-clause
DSLituiev/scikit-learn
examples/tree/unveil_tree_structure.py
67
4824
""" ========================================= Understanding the decision tree structure ========================================= The decision tree structure can be analysed to gain further insight on the relation between the features and the target to predict. In this example, we show how to retrieve: - the binary tree structure; - the depth of each node and whether or not it's a leaf; - the nodes that were reached by a sample using the ``decision_path`` method; - the leaf that was reached by a sample using the apply method; - the rules that were used to predict a sample; - the decision path shared by a group of samples. """ import numpy as np from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris from sklearn.tree import DecisionTreeClassifier iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) estimator = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0) estimator.fit(X_train, y_train) # The decision estimator has an attribute called tree_ which stores the entire # tree structure and allows access to low level attributes. The binary tree # tree_ is represented as a number of parallel arrays. The i-th element of each # array holds information about the node `i`. Node 0 is the tree's root. NOTE: # Some of the arrays only apply to either leaves or split nodes, resp. In this # case the values of nodes of the other type are arbitrary! # # Among those arrays, we have: # - left_child, id of the left child of the node # - right_child, id of the right child of the node # - feature, feature used for splitting the node # - threshold, threshold value at the node # # Using those arrays, we can parse the tree structure: n_nodes = estimator.tree_.node_count children_left = estimator.tree_.children_left children_right = estimator.tree_.children_right feature = estimator.tree_.feature threshold = estimator.tree_.threshold # The tree structure can be traversed to compute various properties such # as the depth of each node and whether or not it is a leaf. node_depth = np.zeros(shape=n_nodes) is_leaves = np.zeros(shape=n_nodes, dtype=bool) stack = [(0, -1)] # seed is the root node id and its parent depth while len(stack) > 0: node_id, parent_depth = stack.pop() node_depth[node_id] = parent_depth + 1 # If we have a test node if (children_left[node_id] != children_right[node_id]): stack.append((children_left[node_id], parent_depth + 1)) stack.append((children_right[node_id], parent_depth + 1)) else: is_leaves[node_id] = True print("The binary tree structure has %s nodes and has " "the following tree structure:" % n_nodes) for i in range(n_nodes): if is_leaves[i]: print("%snode=%s leaf node." % (node_depth[i] * "\t", i)) else: print("%snode=%s test node: go to node %s if X[:, %s] <= %ss else to " "node %s." % (node_depth[i] * "\t", i, children_left[i], feature[i], threshold[i], children_right[i], )) print() # First let's retrieve the decision path of each sample. The decision_path # method allows to retrieve the node indicator functions. A non zero element of # indicator matrix at the position (i, j) indicates that the sample i goes # through the node j. node_indicator = estimator.decision_path(X_test) # Similarly, we can also have the leaves ids reached by each sample. leave_id = estimator.apply(X_test) # Now, it's possible to get the tests that were used to predict a sample or # a group of samples. First, let's make it for the sample. sample_id = 0 node_index = node_indicator.indices[node_indicator.indptr[sample_id]: node_indicator.indptr[sample_id + 1]] print('Rules used to predict sample %s: ' % sample_id) for node_id in node_index: if leave_id[sample_id] != node_id: continue if (X_test[sample_id, feature[node_id]] <= threshold[node_id]): threshold_sign = "<=" else: threshold_sign = ">" print("decision id node %s : (X[%s, %s] (= %s) %s %s)" % (node_id, sample_id, feature[node_id], X_test[i, feature[node_id]], threshold_sign, threshold[node_id])) # For a group of samples, we have the following common node. sample_ids = [0, 1] common_nodes = (node_indicator.toarray()[sample_ids].sum(axis=0) == len(sample_ids)) common_node_id = np.arange(n_nodes)[common_nodes] print("\nThe following samples %s share the node %s in the tree" % (sample_ids, common_node_id)) print("It is %s %% of all nodes." % (100 * len(common_node_id) / n_nodes,))
bsd-3-clause
trankmichael/scikit-learn
sklearn/utils/tests/test_testing.py
144
4121
import warnings import unittest import sys from nose.tools import assert_raises from sklearn.utils.testing import ( _assert_less, _assert_greater, assert_less_equal, assert_greater_equal, assert_warns, assert_no_warnings, assert_equal, set_random_state, assert_raise_message) from sklearn.tree import DecisionTreeClassifier from sklearn.lda import LDA try: from nose.tools import assert_less def test_assert_less(): # Check that the nose implementation of assert_less gives the # same thing as the scikit's assert_less(0, 1) _assert_less(0, 1) assert_raises(AssertionError, assert_less, 1, 0) assert_raises(AssertionError, _assert_less, 1, 0) except ImportError: pass try: from nose.tools import assert_greater def test_assert_greater(): # Check that the nose implementation of assert_less gives the # same thing as the scikit's assert_greater(1, 0) _assert_greater(1, 0) assert_raises(AssertionError, assert_greater, 0, 1) assert_raises(AssertionError, _assert_greater, 0, 1) except ImportError: pass def test_assert_less_equal(): assert_less_equal(0, 1) assert_less_equal(1, 1) assert_raises(AssertionError, assert_less_equal, 1, 0) def test_assert_greater_equal(): assert_greater_equal(1, 0) assert_greater_equal(1, 1) assert_raises(AssertionError, assert_greater_equal, 0, 1) def test_set_random_state(): lda = LDA() tree = DecisionTreeClassifier() # LDA doesn't have random state: smoke test set_random_state(lda, 3) set_random_state(tree, 3) assert_equal(tree.random_state, 3) def test_assert_raise_message(): def _raise_ValueError(message): raise ValueError(message) def _no_raise(): pass assert_raise_message(ValueError, "test", _raise_ValueError, "test") assert_raises(AssertionError, assert_raise_message, ValueError, "something else", _raise_ValueError, "test") assert_raises(ValueError, assert_raise_message, TypeError, "something else", _raise_ValueError, "test") assert_raises(AssertionError, assert_raise_message, ValueError, "test", _no_raise) # multiple exceptions in a tuple assert_raises(AssertionError, assert_raise_message, (ValueError, AttributeError), "test", _no_raise) # This class is inspired from numpy 1.7 with an alteration to check # the reset warning filters after calls to assert_warns. # This assert_warns behavior is specific to scikit-learn because #`clean_warning_registry()` is called internally by assert_warns # and clears all previous filters. class TestWarns(unittest.TestCase): def test_warn(self): def f(): warnings.warn("yo") return 3 # Test that assert_warns is not impacted by externally set # filters and is reset internally. # This is because `clean_warning_registry()` is called internally by # assert_warns and clears all previous filters. warnings.simplefilter("ignore", UserWarning) assert_equal(assert_warns(UserWarning, f), 3) # Test that the warning registry is empty after assert_warns assert_equal(sys.modules['warnings'].filters, []) assert_raises(AssertionError, assert_no_warnings, f) assert_equal(assert_no_warnings(lambda x: x, 1), 1) def test_warn_wrong_warning(self): def f(): warnings.warn("yo", DeprecationWarning) failed = False filters = sys.modules['warnings'].filters[:] try: try: # Should raise an AssertionError assert_warns(UserWarning, f) failed = True except AssertionError: pass finally: sys.modules['warnings'].filters = filters if failed: raise AssertionError("wrong warning caught by assert_warn")
bsd-3-clause
allanino/nupic
nupic/math/roc_utils.py
49
8308
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ Utility functions to compute ROC (Receiver Operator Characteristic) curves and AUC (Area Under the Curve). The ROCCurve() and AreaUnderCurve() functions are based on the roc_curve() and auc() functions found in metrics.py module of scikit-learn (http://scikit-learn.org/stable/). Scikit-learn has a BSD license (3 clause). Following is the original license/credits statement from the top of the metrics.py file: # Authors: Alexandre Gramfort <[email protected]> # Mathieu Blondel <[email protected]> # Olivier Grisel <[email protected]> # License: BSD Style. """ import numpy as np def ROCCurve(y_true, y_score): """compute Receiver operating characteristic (ROC) Note: this implementation is restricted to the binary classification task. Parameters ---------- y_true : array, shape = [n_samples] true binary labels y_score : array, shape = [n_samples] target scores, can either be probability estimates of the positive class, confidence values, or binary decisions. Returns ------- fpr : array, shape = [>2] False Positive Rates tpr : array, shape = [>2] True Positive Rates thresholds : array, shape = [>2] Thresholds on y_score used to compute fpr and tpr Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y = np.array([1, 1, 2, 2]) >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores) >>> fpr array([ 0. , 0.5, 0.5, 1. ]) References ---------- http://en.wikipedia.org/wiki/Receiver_operating_characteristic """ y_true = np.ravel(y_true) classes = np.unique(y_true) # ROC only for binary classification if classes.shape[0] != 2: raise ValueError("ROC is defined for binary classification only") y_score = np.ravel(y_score) n_pos = float(np.sum(y_true == classes[1])) # nb of true positive n_neg = float(np.sum(y_true == classes[0])) # nb of true negative thresholds = np.unique(y_score) neg_value, pos_value = classes[0], classes[1] tpr = np.empty(thresholds.size, dtype=np.float) # True positive rate fpr = np.empty(thresholds.size, dtype=np.float) # False positive rate # Build tpr/fpr vector current_pos_count = current_neg_count = sum_pos = sum_neg = idx = 0 signal = np.c_[y_score, y_true] sorted_signal = signal[signal[:, 0].argsort(), :][::-1] last_score = sorted_signal[0][0] for score, value in sorted_signal: if score == last_score: if value == pos_value: current_pos_count += 1 else: current_neg_count += 1 else: tpr[idx] = (sum_pos + current_pos_count) / n_pos fpr[idx] = (sum_neg + current_neg_count) / n_neg sum_pos += current_pos_count sum_neg += current_neg_count current_pos_count = 1 if value == pos_value else 0 current_neg_count = 1 if value == neg_value else 0 idx += 1 last_score = score else: tpr[-1] = (sum_pos + current_pos_count) / n_pos fpr[-1] = (sum_neg + current_neg_count) / n_neg # hard decisions, add (0,0) if fpr.shape[0] == 2: fpr = np.array([0.0, fpr[0], fpr[1]]) tpr = np.array([0.0, tpr[0], tpr[1]]) # trivial decisions, add (0,0) and (1,1) elif fpr.shape[0] == 1: fpr = np.array([0.0, fpr[0], 1.0]) tpr = np.array([0.0, tpr[0], 1.0]) return fpr, tpr, thresholds def AreaUnderCurve(x, y): """Compute Area Under the Curve (AUC) using the trapezoidal rule Parameters ---------- x : array, shape = [n] x coordinates y : array, shape = [n] y coordinates Returns ------- auc : float Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y = np.array([1, 1, 2, 2]) >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred) >>> metrics.auc(fpr, tpr) 0.75 """ #x, y = check_arrays(x, y) if x.shape[0] != y.shape[0]: raise ValueError('x and y should have the same shape' ' to compute area under curve,' ' but x.shape = %s and y.shape = %s.' % (x.shape, y.shape)) if x.shape[0] < 2: raise ValueError('At least 2 points are needed to compute' ' area under curve, but x.shape = %s' % x.shape) # reorder the data points according to the x axis order = np.argsort(x) x = x[order] y = y[order] h = np.diff(x) area = np.sum(h * (y[1:] + y[:-1])) / 2.0 return area def _printNPArray(x, precision=2): format = "%%.%df" % (precision) for elem in x: print format % (elem), print def _test(): """ This is a toy example, to show the basic functionality: The dataset is: actual prediction ------------------------- 0 0.1 0 0.4 1 0.5 1 0.3 1 0.45 Some ROC terminology: A True Positive (TP) is when we predict TRUE and the actual value is 1. A False Positive (FP) is when we predict TRUE, but the actual value is 0. The True Positive Rate (TPR) is TP/P, where P is the total number of actual positives (3 in this example, the last 3 samples). The False Positive Rate (FPR) is FP/N, where N is the total number of actual negatives (2 in this example, the first 2 samples) Here are the classifications at various choices for the threshold. The prediction is TRUE if the predicted value is >= threshold and FALSE otherwise. actual pred 0.50 0.45 0.40 0.30 0.10 --------------------------------------------------------- 0 0.1 0 0 0 0 1 0 0.4 0 0 1 1 1 1 0.5 1 1 1 1 1 1 0.3 0 0 0 1 1 1 0.45 0 1 1 1 1 TruePos(TP) 1 2 2 3 3 FalsePos(FP) 0 0 1 1 2 TruePosRate(TPR) 1/3 2/3 2/3 3/3 3/3 FalsePosRate(FPR) 0/2 0/2 1/2 1/2 2/2 The ROC curve is a plot of FPR on the x-axis and TPR on the y-axis. Basically, one can pick any operating point along this curve to run, the operating point determined by which threshold you want to use. By changing the threshold, you tradeoff TP's for FPs. The more area under this curve, the better the classification algorithm is. The AreaUnderCurve() function can be used to compute the area under this curve. """ yTrue = np.array([0, 0, 1, 1, 1]) yScore = np.array([0.1, 0.4, 0.5, 0.3, 0.45]) (fpr, tpr, thresholds) = ROCCurve(yTrue, yScore) print "Actual: ", _printNPArray(yTrue) print "Predicted: ", _printNPArray(yScore) print print "Thresholds:", _printNPArray(thresholds[::-1]) print "FPR(x): ", _printNPArray(fpr) print "TPR(y): ", _printNPArray(tpr) print area = AreaUnderCurve(fpr, tpr) print "AUC: ", area if __name__=='__main__': _test()
agpl-3.0
mjirik/lisa
lisa/classification.py
1
2243
# ! /usr/bin/python # -*- coding: utf-8 -*- from loguru import logger # logger = logging.getLogger() import numpy as np class GMMClassifier(): def __init__(self, each_class_params=None, **same_params): """ same_params: classifier params for each class are same each_class_params: is list of dictionary of params for each class classifier. For example: [{'covariance_type': 'full'}, {'n_components': 2}]) """ self.same_params = same_params self.each_class_params = each_class_params self.models = [] def fit(self, X_train, y_train): X_train = np.asarray(X_train) y_train = np.asarray(y_train) # from sklearn.mixture import GMM as GaussianMixture from sklearn.mixture import GaussianMixture unlabels = range(0, np.max(y_train) + 1) for lab in unlabels: if self.each_class_params is not None: # print 'eacl' # print self.each_class_params[lab] model = GaussianMixture(**self.each_class_params[lab]) # print 'po gmm ', model elif len(self.same_params) > 0: model = GaussianMixture(**self.same_params) # print 'ewe ', model else: model = GaussianMixture() X_train_lab = X_train[y_train == lab] # logger.debug('xtr lab shape ' + str(X_train_lab)) model.fit(X_train_lab) self.models.insert(lab, model) def __str__(self): if self.each_class_params is not None: return "GMMClassificator(" + str(self.each_class_params) + ')' else: return "GMMClassificator(" + str(self.same_params) + ')' def predict(self, X_test): X_test = np.asarray(X_test) logger.debug(str(X_test.shape)) logger.debug(str(X_test)) scores = np.zeros([X_test.shape[0], len(self.models)]) for lab in range(0, len(self.models)): logger.debug('means shape' + str(self.models[lab].means_.shape)) sc = self.models[lab].score_samples(X_test) scores[:, lab] = sc pred = np.argmax(scores, 1) return pred
bsd-3-clause
EuropeanSocialInnovationDatabase/ESID-main
TextMining/Classifiers/Trainers/NaiveBayesOutputs.py
1
16411
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn import metrics from sklearn.pipeline import Pipeline import numpy as np import pandas as pd import re from os import listdir from os.path import join,isdir from sklearn.utils import resample from sklearn.model_selection import cross_val_score import pickle from sklearn.utils import resample class DataSet: Annotators = [] def __init__(self): self.Annotators = [] class Annotator: files = [] documents = [] Name = "" def __init__(self): self.files = [] self.documents = [] self.Name = "" class Document: Lines = [] DocumentName = "" DatabaseID = "" Annotations = [] Text = "" isSpam = False Project_Mark_Objective_1A = 0 Project_Mark_Objective_1B = 0 Project_Mark_Objective_1C = 0 Project_Mark_Actors_2A = 0 Project_Mark_Actors_2B = 0 Project_Mark_Actors_2C = 0 Project_Mark_Outputs_3A = 0 Project_Mark_Innovativeness_3A = 0 isProjectObjectiveSatisfied = False isProjectActorSatisfied = False isProjectOutputSatisfied = False isProjectInnovativenessSatisfied = False isProjectObjectiveSatisfied_predicted = False isProjectActorSatisfied_predicted = False isProjectOutputSatisfied_predicted = False isProjectInnovativenessSatisfied_predicted = False def __init__(self): self.Text = "" self.Lines = [] self.DocumentName = "" self.DatabaseID = "" self.Annotations = [] self.isSpam = False self.Project_Mark_Objective_1A = 0 self.Project_Mark_Objective_1B = 0 self.Project_Mark_Objective_1C = 0 self.Project_Mark_Actors_2A = 0 self.Project_Mark_Actors_2B = 0 self.Project_Mark_Actors_2C = 0 self.Project_Mark_Outputs_3A = 0 self.Project_Mark_Innovativeness_3A = 0 self.Project_Mark_Innovativeness_3A = 0 self.isProjectObjectiveSatisfied = False self.isProjectActorSatisfied = False self.isProjectOutputSatisfied = False self.isProjectInnovativenessSatisfied = False self.isProjectObjectiveSatisfied_predicted = False self.isProjectActorSatisfied_predicted = False self.isProjectOutputSatisfied_predicted = False self.isProjectInnovativenessSatisfied_predicted = False class Line: StartSpan = 0 EndSpan = 0 Text = "" Sentences = [] Tokens = [] Annotations = [] def __init__(self): self.StartSpan = 0 self.EndSpan = 0 self.Text = "" self.Sentences = [] self.Tokens = [] self.Annotations = [] class Sentence: SentenceText = "" StartSpan = -1 EndSpan = -1 Annotations = [] def __init__(self): self.SentenceText = "" self.StartSpan = -1 self.EndSpan = -1 self.Annotations = [] class Annotation: FromFile = "" FromAnnotator = "" AnnotationText = "" StartSpan = -1 EndSpan = -1 HighLevelClass = "" LowLevelClass = "" data_folder = "../../../Helpers/FullDataset_Alina/" ds = DataSet() total_num_spam = 0 sentences = [] total_num_files = 0 # job = aetros.backend.start_job('nikolamilosevic86/GloveModel') annotators = [f for f in listdir(data_folder) if isdir(join(data_folder, f))] for ann in annotators: folder = data_folder + "/" + ann Annot = Annotator() Annot.Name = ann ds.Annotators.append(Annot) onlyfiles = [f for f in listdir(folder) if (f.endswith(".txt"))] for file in onlyfiles: Annot.files.append(data_folder + "/" + ann + '/' + file) doc = Document() total_num_files = total_num_files + 1 doc.Lines = [] # doc.Annotations = [] doc.DocumentName = file Annot.documents.append(doc) if (file.startswith('a') or file.startswith('t')): continue print file doc.DatabaseID = file.split("_")[1].split(".")[0] fl = open(data_folder + "/" + ann + '/' + file, 'r') content = fl.read() doc.Text = content lines = content.split('\n') line_index = 0 for line in lines: l = Line() l.StartSpan = line_index l.EndSpan = line_index + len(line) l.Text = line line_index = line_index + len(line) + 1 sentences.append(line) doc.Lines.append(l) an = open(data_folder + "/" + ann + '/' + file.replace(".txt", ".ann"), 'r') annotations = an.readlines() for a in annotations: a = re.sub(r'\d+;\d+', '', a).replace(' ', ' ') split_ann = a.split('\t') if (split_ann[0].startswith("T")): id = split_ann[0] sp_split_ann = split_ann[1].split(' ') low_level_ann = sp_split_ann[0] if low_level_ann == "ProjectMark": continue span_start = sp_split_ann[1] span_end = sp_split_ann[2] ann_text = split_ann[2] Ann = Annotation() Ann.AnnotationText = ann_text Ann.StartSpan = int(span_start) Ann.EndSpan = int(span_end) Ann.FromAnnotator = Annot.Name Ann.FromFile = file Ann.LowLevelClass = low_level_ann if (low_level_ann == "SL_Outputs_3a"): Ann.HighLevelClass = "Outputs" if ( low_level_ann == "SL_Objective_1a" or low_level_ann == "SL_Objective_1b" or low_level_ann == "SL_Objective_1c"): Ann.HighLevelClass = "Objectives" if ( low_level_ann == "SL_Actors_2a" or low_level_ann == "SL_Actors_2b" or low_level_ann == "SL_Actors_2c"): Ann.HighLevelClass = "Actors" if (low_level_ann == "SL_Innovativeness_4a"): Ann.HighLevelClass = "Innovativeness" doc.Annotations.append(Ann) for line in doc.Lines: if line.StartSpan <= Ann.StartSpan and line.EndSpan >= Ann.EndSpan: line.Annotations.append(Ann) else: id = split_ann[0] sp_split_ann = split_ann[1].split(' ') mark_name = sp_split_ann[0] if (len(sp_split_ann) <= 2): continue mark = sp_split_ann[2].replace('\n', '') if (mark_name == "DL_Outputs_3a"): doc.Project_Mark_Outputs_3A = int(mark) if int(mark) >= 1: doc.isProjectOutputSatisfied = True if (mark_name == "DL_Objective_1a"): doc.Project_Mark_Objective_1A = int(mark) if int(mark) >= 1: doc.isProjectObjectiveSatisfied = True if (mark_name == "DL_Objective_1b" or mark_name == "DL_Objective"): doc.Project_Mark_Objective_1B = int(mark) if int(mark) >= 1: doc.isProjectObjectiveSatisfied = True if (mark_name == "DL_Objective_1c"): doc.Project_Mark_Objective_1C = int(mark) if int(mark) >= 1: doc.isProjectObjectiveSatisfied = True if (mark_name == "DL_Innovativeness_4a" or mark_name == "DL_Innovativeness"): doc.Project_Mark_Innovativeness_3A = int(mark) if int(mark) >= 1: doc.isProjectInnovativenessSatisfied = True if (mark_name == "DL_Actors_2a" or mark_name == "DL_Actors"): doc.Project_Mark_Actors_2A = int(mark) if int(mark) >= 1: doc.isProjectActorSatisfied = True if (mark_name == "DL_Actors_2b"): doc.Project_Mark_Actors_2B = int(mark) if int(mark) >= 1: doc.isProjectActorSatisfied = True if (mark_name == "DL_Actors_2c"): doc.Project_Mark_Actors_2C = int(mark) if int(mark) >= 1: doc.isProjectActorSatisfied = True if ( doc.Project_Mark_Objective_1A == 0 and doc.Project_Mark_Objective_1B == 0 and doc.Project_Mark_Objective_1C == 0 and doc.Project_Mark_Actors_2A == 0 and doc.Project_Mark_Actors_2B == 0 and doc.Project_Mark_Actors_2B == 0 and doc.Project_Mark_Actors_2C == 0 and doc.Project_Mark_Outputs_3A == 0 and doc.Project_Mark_Innovativeness_3A == 0): doc.isSpam = True total_num_spam = total_num_spam + 1 i = 0 j = i + 1 kappa_files = 0 done_documents = [] num_overlap_spam = 0 num_spam = 0 total_objectives = 0 total_outputs = 0 total_actors = 0 total_innovativeness = 0 ann1_annotations_objectives = [] ann2_annotations_objectives = [] ann1_annotations_actors = [] ann2_annotations_actors = [] ann1_annotations_outputs = [] ann2_annotations_outputs = [] ann1_annotations_innovativeness = [] ann2_annotations_innovativeness = [] match_objectives = 0 match_outputs = 0 match_actors = 0 match_innovativeness = 0 while i < len(ds.Annotators) - 1: while j < len(ds.Annotators): annotator1 = ds.Annotators[i] annotator2 = ds.Annotators[j] for doc1 in annotator1.documents: for doc2 in annotator2.documents: if doc1.DocumentName == doc2.DocumentName and doc1.DocumentName not in done_documents: done_documents.append(doc1.DocumentName) line_num = 0 ann1_objective = [0] * len(doc1.Lines) ann2_objective = [0] * len(doc2.Lines) ann1_output = [0] * len(doc1.Lines) ann2_output = [0] * len(doc2.Lines) ann1_actor = [0] * len(doc1.Lines) ann2_actor = [0] * len(doc2.Lines) ann1_innovativeness = [0] * len(doc1.Lines) ann2_innovativeness = [0] * len(doc2.Lines) while line_num < len(doc1.Lines): if len(doc1.Lines[line_num].Annotations) > 0: for a in doc1.Lines[line_num].Annotations: if a.HighLevelClass == "Objectives": ann1_objective[line_num] = 1 total_objectives = total_objectives + 1 if a.HighLevelClass == "Outputs": ann1_output[line_num] = 1 total_outputs = total_outputs + 1 if a.HighLevelClass == "Actors": ann1_actor[line_num] = 1 total_actors = total_actors + 1 if a.HighLevelClass == "Innovativeness": ann1_innovativeness[line_num] = 1 total_innovativeness = total_innovativeness + 1 for a1 in doc2.Lines[line_num].Annotations: if a1.HighLevelClass == a.HighLevelClass: if a1.HighLevelClass == "Objectives": match_objectives = match_objectives + 1 if a1.HighLevelClass == "Outputs": match_outputs = match_outputs + 1 if a1.HighLevelClass == "Actors": match_actors = match_actors + 1 if a1.HighLevelClass == "Innovativeness": match_innovativeness = match_innovativeness + 1 if len(doc2.Lines[line_num].Annotations) > 0: for a in doc2.Lines[line_num].Annotations: if a.HighLevelClass == "Objectives": ann2_objective[line_num] = 1 total_objectives = total_objectives + 1 if a.HighLevelClass == "Outputs": ann2_output[line_num] = 1 total_outputs = total_outputs + 1 if a.HighLevelClass == "Actors": ann2_actor[line_num] = 1 total_actors = total_actors + 1 if a.HighLevelClass == "Innovativeness": ann2_innovativeness[line_num] = 1 total_innovativeness = total_innovativeness + 1 line_num = line_num + 1 ann1_annotations_outputs.extend(ann1_output) ann2_annotations_outputs.extend(ann2_output) ann1_annotations_objectives.extend(ann1_objective) ann2_annotations_objectives.extend(ann2_objective) ann1_annotations_actors.extend(ann1_actor) ann2_annotations_actors.extend(ann2_actor) ann1_annotations_innovativeness.extend(ann1_innovativeness) ann2_annotations_innovativeness.extend(ann2_innovativeness) print "Statistics for document:" + doc1.DocumentName print "Annotators " + annotator1.Name + " and " + annotator2.Name print "Spam by " + annotator1.Name + ":" + str(doc1.isSpam) print "Spam by " + annotator2.Name + ":" + str(doc2.isSpam) if (doc1.isSpam == doc2.isSpam): num_overlap_spam = num_overlap_spam + 1 if doc1.isSpam: num_spam = num_spam + 1 if doc2.isSpam: num_spam = num_spam + 1 kappa_files = kappa_files + 1 j = j + 1 i = i + 1 j = i + 1 print annotators doc_array = [] text_array = [] objectives = [] actors = [] outputs = [] innovativeness = [] for ann in ds.Annotators: for doc in ann.documents: doc_array.append( [doc.Text, doc.isProjectObjectiveSatisfied, doc.isProjectActorSatisfied, doc.isProjectOutputSatisfied, doc.isProjectInnovativenessSatisfied]) objectives.append(doc.isProjectObjectiveSatisfied) actors.append(doc.isProjectActorSatisfied) outputs.append(doc.isProjectOutputSatisfied) innovativeness.append(doc.isProjectInnovativenessSatisfied) text_array.append(doc.Text) df = pd.DataFrame({'text':text_array,'classa':outputs}) df_majority = df[df.classa==0] df_minority = df[df.classa==1] df_minority_upsampled = resample(df_minority, replace=True, # sample with replacement n_samples=160, # to match majority class random_state=83293) # reproducible results df_upsampled = pd.concat([df_majority, df_minority_upsampled]) # Display new class counts print df_upsampled.classa.value_counts() train = text_array[0:int(0.8*len(text_array))] train_Y = outputs[0:int(0.8*len(actors))] test = text_array[int(0.8*len(text_array)):] test_Y = outputs[int(0.8*len(actors)):] #categories = ['non actor', 'actor'] text_clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', MultinomialNB()), ]) scores = cross_val_score(text_clf, df_upsampled.text, df_upsampled.classa, cv=10,scoring='f1') final = 0 for score in scores: final = final + score print scores print "Final:" + str(final/10) text_clf.fit( df_upsampled.text, df_upsampled.classa) filename = '../Models/naive_bayes_outputs.sav' pickle.dump(text_clf, open(filename, 'wb'))
gpl-3.0
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/sklearn/preprocessing/data.py
5
94481
# Authors: Alexandre Gramfort <[email protected]> # Mathieu Blondel <[email protected]> # Olivier Grisel <[email protected]> # Andreas Mueller <[email protected]> # Eric Martin <[email protected]> # Giorgio Patrini <[email protected]> # License: BSD 3 clause from __future__ import division from itertools import chain, combinations import numbers import warnings from itertools import combinations_with_replacement as combinations_w_r import numpy as np from scipy import sparse from scipy import stats from ..base import BaseEstimator, TransformerMixin from ..externals import six from ..externals.six import string_types from ..utils import check_array from ..utils.extmath import row_norms from ..utils.extmath import _incremental_mean_and_var from ..utils.sparsefuncs_fast import (inplace_csr_row_normalize_l1, inplace_csr_row_normalize_l2) from ..utils.sparsefuncs import (inplace_column_scale, mean_variance_axis, incr_mean_variance_axis, min_max_axis) from ..utils.validation import (check_is_fitted, check_random_state, FLOAT_DTYPES) BOUNDS_THRESHOLD = 1e-7 zip = six.moves.zip map = six.moves.map range = six.moves.range __all__ = [ 'Binarizer', 'KernelCenterer', 'MinMaxScaler', 'MaxAbsScaler', 'Normalizer', 'OneHotEncoder', 'RobustScaler', 'StandardScaler', 'QuantileTransformer', 'add_dummy_feature', 'binarize', 'normalize', 'scale', 'robust_scale', 'maxabs_scale', 'minmax_scale', 'quantile_transform', ] def _handle_zeros_in_scale(scale, copy=True): ''' Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features.''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): if scale == .0: scale = 1. return scale elif isinstance(scale, np.ndarray): if copy: # New array to avoid side-effects scale = scale.copy() scale[scale == 0.0] = 1.0 return scale def scale(X, axis=0, with_mean=True, with_std=True, copy=True): """Standardize a dataset along any axis Center to the mean and component wise scale to unit variance. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- X : {array-like, sparse matrix} The data to center and scale. axis : int (0 by default) axis used to compute the means and standard deviations along. If 0, independently standardize each feature, otherwise (if 1) standardize each sample. with_mean : boolean, True by default If True, center the data before scaling. with_std : boolean, True by default If True, scale the data to unit variance (or equivalently, unit standard deviation). copy : boolean, optional, default True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSC matrix and if axis is 1). Notes ----- This implementation will refuse to center scipy.sparse matrices since it would make them non-sparse and would potentially crash the program with memory exhaustion problems. Instead the caller is expected to either set explicitly `with_mean=False` (in that case, only variance scaling will be performed on the features of the CSC matrix) or to call `X.toarray()` if he/she expects the materialized dense array to fit in memory. To avoid memory copy the caller should pass a CSC matrix. For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. See also -------- StandardScaler: Performs scaling to unit variance using the``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`). """ # noqa X = check_array(X, accept_sparse='csc', copy=copy, ensure_2d=False, warn_on_dtype=True, estimator='the scale function', dtype=FLOAT_DTYPES) if sparse.issparse(X): if with_mean: raise ValueError( "Cannot center sparse matrices: pass `with_mean=False` instead" " See docstring for motivation and alternatives.") if axis != 0: raise ValueError("Can only scale sparse matrix on axis=0, " " got axis=%d" % axis) if with_std: _, var = mean_variance_axis(X, axis=0) var = _handle_zeros_in_scale(var, copy=False) inplace_column_scale(X, 1 / np.sqrt(var)) else: X = np.asarray(X) if with_mean: mean_ = np.mean(X, axis) if with_std: scale_ = np.std(X, axis) # Xr is a view on the original array that enables easy use of # broadcasting on the axis in which we are interested in Xr = np.rollaxis(X, axis) if with_mean: Xr -= mean_ mean_1 = Xr.mean(axis=0) # Verify that mean_1 is 'close to zero'. If X contains very # large values, mean_1 can also be very large, due to a lack of # precision of mean_. In this case, a pre-scaling of the # concerned feature is efficient, for instance by its mean or # maximum. if not np.allclose(mean_1, 0): warnings.warn("Numerical issues were encountered " "when centering the data " "and might not be solved. Dataset may " "contain too large values. You may need " "to prescale your features.") Xr -= mean_1 if with_std: scale_ = _handle_zeros_in_scale(scale_, copy=False) Xr /= scale_ if with_mean: mean_2 = Xr.mean(axis=0) # If mean_2 is not 'close to zero', it comes from the fact that # scale_ is very small so that mean_2 = mean_1/scale_ > 0, even # if mean_1 was close to zero. The problem is thus essentially # due to the lack of precision of mean_. A solution is then to # subtract the mean again: if not np.allclose(mean_2, 0): warnings.warn("Numerical issues were encountered " "when scaling the data " "and might not be solved. The standard " "deviation of the data is probably " "very close to 0. ") Xr -= mean_2 return X class MinMaxScaler(BaseEstimator, TransformerMixin): """Transforms features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, i.e. between zero and one. The transformation is given by:: X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min where min, max = feature_range. This transformation is often used as an alternative to zero mean, unit variance scaling. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- feature_range : tuple (min, max), default=(0, 1) Desired range of transformed data. copy : boolean, optional, default True Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array). Attributes ---------- min_ : ndarray, shape (n_features,) Per feature adjustment for minimum. scale_ : ndarray, shape (n_features,) Per feature relative scaling of the data. .. versionadded:: 0.17 *scale_* attribute. data_min_ : ndarray, shape (n_features,) Per feature minimum seen in the data .. versionadded:: 0.17 *data_min_* data_max_ : ndarray, shape (n_features,) Per feature maximum seen in the data .. versionadded:: 0.17 *data_max_* data_range_ : ndarray, shape (n_features,) Per feature range ``(data_max_ - data_min_)`` seen in the data .. versionadded:: 0.17 *data_range_* Examples -------- >>> from sklearn.preprocessing import MinMaxScaler >>> >>> data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]] >>> scaler = MinMaxScaler() >>> print(scaler.fit(data)) MinMaxScaler(copy=True, feature_range=(0, 1)) >>> print(scaler.data_max_) [ 1. 18.] >>> print(scaler.transform(data)) [[ 0. 0. ] [ 0.25 0.25] [ 0.5 0.5 ] [ 1. 1. ]] >>> print(scaler.transform([[2, 2]])) [[ 1.5 0. ]] See also -------- minmax_scale: Equivalent function without the estimator API. Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. """ def __init__(self, feature_range=(0, 1), copy=True): self.feature_range = feature_range self.copy = copy def _reset(self): """Reset internal data-dependent state of the scaler, if necessary. __init__ parameters are not touched. """ # Checking one attribute is enough, becase they are all set together # in partial_fit if hasattr(self, 'scale_'): del self.scale_ del self.min_ del self.n_samples_seen_ del self.data_min_ del self.data_max_ del self.data_range_ def fit(self, X, y=None): """Compute the minimum and maximum to be used for later scaling. Parameters ---------- X : array-like, shape [n_samples, n_features] The data used to compute the per-feature minimum and maximum used for later scaling along the features axis. """ # Reset internal state before fitting self._reset() return self.partial_fit(X, y) def partial_fit(self, X, y=None): """Online computation of min and max on X for later scaling. All of X is processed as a single batch. This is intended for cases when `fit` is not feasible due to very large number of `n_samples` or because X is read from a continuous stream. Parameters ---------- X : array-like, shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. y : Passthrough for ``Pipeline`` compatibility. """ feature_range = self.feature_range if feature_range[0] >= feature_range[1]: raise ValueError("Minimum of desired feature range must be smaller" " than maximum. Got %s." % str(feature_range)) if sparse.issparse(X): raise TypeError("MinMaxScaler does no support sparse input. " "You may consider to use MaxAbsScaler instead.") X = check_array(X, copy=self.copy, warn_on_dtype=True, estimator=self, dtype=FLOAT_DTYPES) data_min = np.min(X, axis=0) data_max = np.max(X, axis=0) # First pass if not hasattr(self, 'n_samples_seen_'): self.n_samples_seen_ = X.shape[0] # Next steps else: data_min = np.minimum(self.data_min_, data_min) data_max = np.maximum(self.data_max_, data_max) self.n_samples_seen_ += X.shape[0] data_range = data_max - data_min self.scale_ = ((feature_range[1] - feature_range[0]) / _handle_zeros_in_scale(data_range)) self.min_ = feature_range[0] - data_min * self.scale_ self.data_min_ = data_min self.data_max_ = data_max self.data_range_ = data_range return self def transform(self, X): """Scaling features of X according to feature_range. Parameters ---------- X : array-like, shape [n_samples, n_features] Input data that will be transformed. """ check_is_fitted(self, 'scale_') X = check_array(X, copy=self.copy, dtype=FLOAT_DTYPES) X *= self.scale_ X += self.min_ return X def inverse_transform(self, X): """Undo the scaling of X according to feature_range. Parameters ---------- X : array-like, shape [n_samples, n_features] Input data that will be transformed. It cannot be sparse. """ check_is_fitted(self, 'scale_') X = check_array(X, copy=self.copy, dtype=FLOAT_DTYPES) X -= self.min_ X /= self.scale_ return X def minmax_scale(X, feature_range=(0, 1), axis=0, copy=True): """Transforms features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, i.e. between zero and one. The transformation is given by:: X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min where min, max = feature_range. This transformation is often used as an alternative to zero mean, unit variance scaling. Read more in the :ref:`User Guide <preprocessing_scaler>`. .. versionadded:: 0.17 *minmax_scale* function interface to :class:`sklearn.preprocessing.MinMaxScaler`. Parameters ---------- X : array-like, shape (n_samples, n_features) The data. feature_range : tuple (min, max), default=(0, 1) Desired range of transformed data. axis : int (0 by default) axis used to scale along. If 0, independently scale each feature, otherwise (if 1) scale each sample. copy : boolean, optional, default is True Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array). See also -------- MinMaxScaler: Performs scaling to a given range using the``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`). Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. """ # noqa # Unlike the scaler object, this function allows 1d input. # If copy is required, it will be done inside the scaler object. X = check_array(X, copy=False, ensure_2d=False, warn_on_dtype=True, dtype=FLOAT_DTYPES) original_ndim = X.ndim if original_ndim == 1: X = X.reshape(X.shape[0], 1) s = MinMaxScaler(feature_range=feature_range, copy=copy) if axis == 0: X = s.fit_transform(X) else: X = s.fit_transform(X.T).T if original_ndim == 1: X = X.ravel() return X class StandardScaler(BaseEstimator, TransformerMixin): """Standardize features by removing the mean and scaling to unit variance Centering and scaling happen independently on each feature by computing the relevant statistics on the samples in the training set. Mean and standard deviation are then stored to be used on later data using the `transform` method. Standardization of a dataset is a common requirement for many machine learning estimators: they might behave badly if the individual feature do not more or less look like standard normally distributed data (e.g. Gaussian with 0 mean and unit variance). For instance many elements used in the objective function of a learning algorithm (such as the RBF kernel of Support Vector Machines or the L1 and L2 regularizers of linear models) assume that all features are centered around 0 and have variance in the same order. If a feature has a variance that is orders of magnitude larger that others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected. This scaler can also be applied to sparse CSR or CSC matrices by passing `with_mean=False` to avoid breaking the sparsity structure of the data. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- copy : boolean, optional, default True If False, try to avoid a copy and do inplace scaling instead. This is not guaranteed to always work inplace; e.g. if the data is not a NumPy array or scipy.sparse CSR matrix, a copy may still be returned. with_mean : boolean, True by default If True, center the data before scaling. This does not work (and will raise an exception) when attempted on sparse matrices, because centering them entails building a dense matrix which in common use cases is likely to be too large to fit in memory. with_std : boolean, True by default If True, scale the data to unit variance (or equivalently, unit standard deviation). Attributes ---------- scale_ : ndarray, shape (n_features,) Per feature relative scaling of the data. .. versionadded:: 0.17 *scale_* mean_ : array of floats with shape [n_features] The mean value for each feature in the training set. var_ : array of floats with shape [n_features] The variance for each feature in the training set. Used to compute `scale_` n_samples_seen_ : int The number of samples processed by the estimator. Will be reset on new calls to fit, but increments across ``partial_fit`` calls. Examples -------- >>> from sklearn.preprocessing import StandardScaler >>> >>> data = [[0, 0], [0, 0], [1, 1], [1, 1]] >>> scaler = StandardScaler() >>> print(scaler.fit(data)) StandardScaler(copy=True, with_mean=True, with_std=True) >>> print(scaler.mean_) [ 0.5 0.5] >>> print(scaler.transform(data)) [[-1. -1.] [-1. -1.] [ 1. 1.] [ 1. 1.]] >>> print(scaler.transform([[2, 2]])) [[ 3. 3.]] See also -------- scale: Equivalent function without the estimator API. :class:`sklearn.decomposition.PCA` Further removes the linear correlation across features with 'whiten=True'. Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. """ # noqa def __init__(self, copy=True, with_mean=True, with_std=True): self.with_mean = with_mean self.with_std = with_std self.copy = copy def _reset(self): """Reset internal data-dependent state of the scaler, if necessary. __init__ parameters are not touched. """ # Checking one attribute is enough, becase they are all set together # in partial_fit if hasattr(self, 'scale_'): del self.scale_ del self.n_samples_seen_ del self.mean_ del self.var_ def fit(self, X, y=None): """Compute the mean and std to be used for later scaling. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. y : Passthrough for ``Pipeline`` compatibility. """ # Reset internal state before fitting self._reset() return self.partial_fit(X, y) def partial_fit(self, X, y=None): """Online computation of mean and std on X for later scaling. All of X is processed as a single batch. This is intended for cases when `fit` is not feasible due to very large number of `n_samples` or because X is read from a continuous stream. The algorithm for incremental mean and std is given in Equation 1.5a,b in Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. "Algorithms for computing the sample variance: Analysis and recommendations." The American Statistician 37.3 (1983): 242-247: Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. y : Passthrough for ``Pipeline`` compatibility. """ X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, warn_on_dtype=True, estimator=self, dtype=FLOAT_DTYPES) # Even in the case of `with_mean=False`, we update the mean anyway # This is needed for the incremental computation of the var # See incr_mean_variance_axis and _incremental_mean_variance_axis if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot center sparse matrices: pass `with_mean=False` " "instead. See docstring for motivation and alternatives.") if self.with_std: # First pass if not hasattr(self, 'n_samples_seen_'): self.mean_, self.var_ = mean_variance_axis(X, axis=0) self.n_samples_seen_ = X.shape[0] # Next passes else: self.mean_, self.var_, self.n_samples_seen_ = \ incr_mean_variance_axis(X, axis=0, last_mean=self.mean_, last_var=self.var_, last_n=self.n_samples_seen_) else: self.mean_ = None self.var_ = None else: # First pass if not hasattr(self, 'n_samples_seen_'): self.mean_ = .0 self.n_samples_seen_ = 0 if self.with_std: self.var_ = .0 else: self.var_ = None self.mean_, self.var_, self.n_samples_seen_ = \ _incremental_mean_and_var(X, self.mean_, self.var_, self.n_samples_seen_) if self.with_std: self.scale_ = _handle_zeros_in_scale(np.sqrt(self.var_)) else: self.scale_ = None return self def transform(self, X, y='deprecated', copy=None): """Perform standardization by centering and scaling Parameters ---------- X : array-like, shape [n_samples, n_features] The data used to scale along the features axis. y : (ignored) .. deprecated:: 0.19 This parameter will be removed in 0.21. copy : bool, optional (default: None) Copy the input X or not. """ if not isinstance(y, string_types) or y != 'deprecated': warnings.warn("The parameter y on transform() is " "deprecated since 0.19 and will be removed in 0.21", DeprecationWarning) check_is_fitted(self, 'scale_') copy = copy if copy is not None else self.copy X = check_array(X, accept_sparse='csr', copy=copy, warn_on_dtype=True, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot center sparse matrices: pass `with_mean=False` " "instead. See docstring for motivation and alternatives.") if self.scale_ is not None: inplace_column_scale(X, 1 / self.scale_) else: if self.with_mean: X -= self.mean_ if self.with_std: X /= self.scale_ return X def inverse_transform(self, X, copy=None): """Scale back the data to the original representation Parameters ---------- X : array-like, shape [n_samples, n_features] The data used to scale along the features axis. copy : bool, optional (default: None) Copy the input X or not. Returns ------- X_tr : array-like, shape [n_samples, n_features] Transformed array. """ check_is_fitted(self, 'scale_') copy = copy if copy is not None else self.copy if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot uncenter sparse matrices: pass `with_mean=False` " "instead See docstring for motivation and alternatives.") if not sparse.isspmatrix_csr(X): X = X.tocsr() copy = False if copy: X = X.copy() if self.scale_ is not None: inplace_column_scale(X, self.scale_) else: X = np.asarray(X) if copy: X = X.copy() if self.with_std: X *= self.scale_ if self.with_mean: X += self.mean_ return X class MaxAbsScaler(BaseEstimator, TransformerMixin): """Scale each feature by its maximum absolute value. This estimator scales and translates each feature individually such that the maximal absolute value of each feature in the training set will be 1.0. It does not shift/center the data, and thus does not destroy any sparsity. This scaler can also be applied to sparse CSR or CSC matrices. .. versionadded:: 0.17 Parameters ---------- copy : boolean, optional, default is True Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array). Attributes ---------- scale_ : ndarray, shape (n_features,) Per feature relative scaling of the data. .. versionadded:: 0.17 *scale_* attribute. max_abs_ : ndarray, shape (n_features,) Per feature maximum absolute value. n_samples_seen_ : int The number of samples processed by the estimator. Will be reset on new calls to fit, but increments across ``partial_fit`` calls. See also -------- maxabs_scale: Equivalent function without the estimator API. Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. """ def __init__(self, copy=True): self.copy = copy def _reset(self): """Reset internal data-dependent state of the scaler, if necessary. __init__ parameters are not touched. """ # Checking one attribute is enough, becase they are all set together # in partial_fit if hasattr(self, 'scale_'): del self.scale_ del self.n_samples_seen_ del self.max_abs_ def fit(self, X, y=None): """Compute the maximum absolute value to be used for later scaling. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the per-feature minimum and maximum used for later scaling along the features axis. """ # Reset internal state before fitting self._reset() return self.partial_fit(X, y) def partial_fit(self, X, y=None): """Online computation of max absolute value of X for later scaling. All of X is processed as a single batch. This is intended for cases when `fit` is not feasible due to very large number of `n_samples` or because X is read from a continuous stream. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. y : Passthrough for ``Pipeline`` compatibility. """ X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): mins, maxs = min_max_axis(X, axis=0) max_abs = np.maximum(np.abs(mins), np.abs(maxs)) else: max_abs = np.abs(X).max(axis=0) # First pass if not hasattr(self, 'n_samples_seen_'): self.n_samples_seen_ = X.shape[0] # Next passes else: max_abs = np.maximum(self.max_abs_, max_abs) self.n_samples_seen_ += X.shape[0] self.max_abs_ = max_abs self.scale_ = _handle_zeros_in_scale(max_abs) return self def transform(self, X): """Scale the data Parameters ---------- X : {array-like, sparse matrix} The data that should be scaled. """ check_is_fitted(self, 'scale_') X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): inplace_column_scale(X, 1.0 / self.scale_) else: X /= self.scale_ return X def inverse_transform(self, X): """Scale back the data to the original representation Parameters ---------- X : {array-like, sparse matrix} The data that should be transformed back. """ check_is_fitted(self, 'scale_') X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): inplace_column_scale(X, self.scale_) else: X *= self.scale_ return X def maxabs_scale(X, axis=0, copy=True): """Scale each feature to the [-1, 1] range without breaking the sparsity. This estimator scales each feature individually such that the maximal absolute value of each feature in the training set will be 1.0. This scaler can also be applied to sparse CSR or CSC matrices. Parameters ---------- X : array-like, shape (n_samples, n_features) The data. axis : int (0 by default) axis used to scale along. If 0, independently scale each feature, otherwise (if 1) scale each sample. copy : boolean, optional, default is True Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array). See also -------- MaxAbsScaler: Performs scaling to the [-1, 1] range using the``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`). Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. """ # noqa # Unlike the scaler object, this function allows 1d input. # If copy is required, it will be done inside the scaler object. X = check_array(X, accept_sparse=('csr', 'csc'), copy=False, ensure_2d=False, dtype=FLOAT_DTYPES) original_ndim = X.ndim if original_ndim == 1: X = X.reshape(X.shape[0], 1) s = MaxAbsScaler(copy=copy) if axis == 0: X = s.fit_transform(X) else: X = s.fit_transform(X.T).T if original_ndim == 1: X = X.ravel() return X class RobustScaler(BaseEstimator, TransformerMixin): """Scale features using statistics that are robust to outliers. This Scaler removes the median and scales the data according to the quantile range (defaults to IQR: Interquartile Range). The IQR is the range between the 1st quartile (25th quantile) and the 3rd quartile (75th quantile). Centering and scaling happen independently on each feature (or each sample, depending on the ``axis`` argument) by computing the relevant statistics on the samples in the training set. Median and interquartile range are then stored to be used on later data using the ``transform`` method. Standardization of a dataset is a common requirement for many machine learning estimators. Typically this is done by removing the mean and scaling to unit variance. However, outliers can often influence the sample mean / variance in a negative way. In such cases, the median and the interquartile range often give better results. .. versionadded:: 0.17 Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- with_centering : boolean, True by default If True, center the data before scaling. This will cause ``transform`` to raise an exception when attempted on sparse matrices, because centering them entails building a dense matrix which in common use cases is likely to be too large to fit in memory. with_scaling : boolean, True by default If True, scale the data to interquartile range. quantile_range : tuple (q_min, q_max), 0.0 < q_min < q_max < 100.0 Default: (25.0, 75.0) = (1st quantile, 3rd quantile) = IQR Quantile range used to calculate ``scale_``. .. versionadded:: 0.18 copy : boolean, optional, default is True If False, try to avoid a copy and do inplace scaling instead. This is not guaranteed to always work inplace; e.g. if the data is not a NumPy array or scipy.sparse CSR matrix, a copy may still be returned. Attributes ---------- center_ : array of floats The median value for each feature in the training set. scale_ : array of floats The (scaled) interquartile range for each feature in the training set. .. versionadded:: 0.17 *scale_* attribute. See also -------- robust_scale: Equivalent function without the estimator API. :class:`sklearn.decomposition.PCA` Further removes the linear correlation across features with 'whiten=True'. Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. https://en.wikipedia.org/wiki/Median_(statistics) https://en.wikipedia.org/wiki/Interquartile_range """ def __init__(self, with_centering=True, with_scaling=True, quantile_range=(25.0, 75.0), copy=True): self.with_centering = with_centering self.with_scaling = with_scaling self.quantile_range = quantile_range self.copy = copy def _check_array(self, X, copy): """Makes sure centering is not enabled for sparse matrices.""" X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): if self.with_centering: raise ValueError( "Cannot center sparse matrices: use `with_centering=False`" " instead. See docstring for motivation and alternatives.") return X def fit(self, X, y=None): """Compute the median and quantiles to be used for scaling. Parameters ---------- X : array-like, shape [n_samples, n_features] The data used to compute the median and quantiles used for later scaling along the features axis. """ if sparse.issparse(X): raise TypeError("RobustScaler cannot be fitted on sparse inputs") X = self._check_array(X, self.copy) if self.with_centering: self.center_ = np.median(X, axis=0) if self.with_scaling: q_min, q_max = self.quantile_range if not 0 <= q_min <= q_max <= 100: raise ValueError("Invalid quantile range: %s" % str(self.quantile_range)) q = np.percentile(X, self.quantile_range, axis=0) self.scale_ = (q[1] - q[0]) self.scale_ = _handle_zeros_in_scale(self.scale_, copy=False) return self def transform(self, X): """Center and scale the data. Can be called on sparse input, provided that ``RobustScaler`` has been fitted to dense input and ``with_centering=False``. Parameters ---------- X : {array-like, sparse matrix} The data used to scale along the specified axis. """ if self.with_centering: check_is_fitted(self, 'center_') if self.with_scaling: check_is_fitted(self, 'scale_') X = self._check_array(X, self.copy) if sparse.issparse(X): if self.with_scaling: inplace_column_scale(X, 1.0 / self.scale_) else: if self.with_centering: X -= self.center_ if self.with_scaling: X /= self.scale_ return X def inverse_transform(self, X): """Scale back the data to the original representation Parameters ---------- X : array-like The data used to scale along the specified axis. """ if self.with_centering: check_is_fitted(self, 'center_') if self.with_scaling: check_is_fitted(self, 'scale_') X = self._check_array(X, self.copy) if sparse.issparse(X): if self.with_scaling: inplace_column_scale(X, self.scale_) else: if self.with_scaling: X *= self.scale_ if self.with_centering: X += self.center_ return X def robust_scale(X, axis=0, with_centering=True, with_scaling=True, quantile_range=(25.0, 75.0), copy=True): """Standardize a dataset along any axis Center to the median and component wise scale according to the interquartile range. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- X : array-like The data to center and scale. axis : int (0 by default) axis used to compute the medians and IQR along. If 0, independently scale each feature, otherwise (if 1) scale each sample. with_centering : boolean, True by default If True, center the data before scaling. with_scaling : boolean, True by default If True, scale the data to unit variance (or equivalently, unit standard deviation). quantile_range : tuple (q_min, q_max), 0.0 < q_min < q_max < 100.0 Default: (25.0, 75.0) = (1st quantile, 3rd quantile) = IQR Quantile range used to calculate ``scale_``. .. versionadded:: 0.18 copy : boolean, optional, default is True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix and if axis is 1). Notes ----- This implementation will refuse to center scipy.sparse matrices since it would make them non-sparse and would potentially crash the program with memory exhaustion problems. Instead the caller is expected to either set explicitly `with_centering=False` (in that case, only variance scaling will be performed on the features of the CSR matrix) or to call `X.toarray()` if he/she expects the materialized dense array to fit in memory. To avoid memory copy the caller should pass a CSR matrix. For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. See also -------- RobustScaler: Performs centering and scaling using the ``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`). """ s = RobustScaler(with_centering=with_centering, with_scaling=with_scaling, quantile_range=quantile_range, copy=copy) if axis == 0: return s.fit_transform(X) else: return s.fit_transform(X.T).T class PolynomialFeatures(BaseEstimator, TransformerMixin): """Generate polynomial and interaction features. Generate a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. For example, if an input sample is two dimensional and of the form [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2]. Parameters ---------- degree : integer The degree of the polynomial features. Default = 2. interaction_only : boolean, default = False If true, only interaction features are produced: features that are products of at most ``degree`` *distinct* input features (so not ``x[1] ** 2``, ``x[0] * x[2] ** 3``, etc.). include_bias : boolean If True (default), then include a bias column, the feature in which all polynomial powers are zero (i.e. a column of ones - acts as an intercept term in a linear model). Examples -------- >>> X = np.arange(6).reshape(3, 2) >>> X array([[0, 1], [2, 3], [4, 5]]) >>> poly = PolynomialFeatures(2) >>> poly.fit_transform(X) array([[ 1., 0., 1., 0., 0., 1.], [ 1., 2., 3., 4., 6., 9.], [ 1., 4., 5., 16., 20., 25.]]) >>> poly = PolynomialFeatures(interaction_only=True) >>> poly.fit_transform(X) array([[ 1., 0., 1., 0.], [ 1., 2., 3., 6.], [ 1., 4., 5., 20.]]) Attributes ---------- powers_ : array, shape (n_output_features, n_input_features) powers_[i, j] is the exponent of the jth input in the ith output. n_input_features_ : int The total number of input features. n_output_features_ : int The total number of polynomial output features. The number of output features is computed by iterating over all suitably sized combinations of input features. Notes ----- Be aware that the number of features in the output array scales polynomially in the number of features of the input array, and exponentially in the degree. High degrees can cause overfitting. See :ref:`examples/linear_model/plot_polynomial_interpolation.py <sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.py>` """ def __init__(self, degree=2, interaction_only=False, include_bias=True): self.degree = degree self.interaction_only = interaction_only self.include_bias = include_bias @staticmethod def _combinations(n_features, degree, interaction_only, include_bias): comb = (combinations if interaction_only else combinations_w_r) start = int(not include_bias) return chain.from_iterable(comb(range(n_features), i) for i in range(start, degree + 1)) @property def powers_(self): check_is_fitted(self, 'n_input_features_') combinations = self._combinations(self.n_input_features_, self.degree, self.interaction_only, self.include_bias) return np.vstack(np.bincount(c, minlength=self.n_input_features_) for c in combinations) def get_feature_names(self, input_features=None): """ Return feature names for output features Parameters ---------- input_features : list of string, length n_features, optional String names for input features if available. By default, "x0", "x1", ... "xn_features" is used. Returns ------- output_feature_names : list of string, length n_output_features """ powers = self.powers_ if input_features is None: input_features = ['x%d' % i for i in range(powers.shape[1])] feature_names = [] for row in powers: inds = np.where(row)[0] if len(inds): name = " ".join("%s^%d" % (input_features[ind], exp) if exp != 1 else input_features[ind] for ind, exp in zip(inds, row[inds])) else: name = "1" feature_names.append(name) return feature_names def fit(self, X, y=None): """ Compute number of output features. Parameters ---------- X : array-like, shape (n_samples, n_features) The data. Returns ------- self : instance """ n_samples, n_features = check_array(X).shape combinations = self._combinations(n_features, self.degree, self.interaction_only, self.include_bias) self.n_input_features_ = n_features self.n_output_features_ = sum(1 for _ in combinations) return self def transform(self, X): """Transform data to polynomial features Parameters ---------- X : array-like, shape [n_samples, n_features] The data to transform, row by row. Returns ------- XP : np.ndarray shape [n_samples, NP] The matrix of features, where NP is the number of polynomial features generated from the combination of inputs. """ check_is_fitted(self, ['n_input_features_', 'n_output_features_']) X = check_array(X, dtype=FLOAT_DTYPES) n_samples, n_features = X.shape if n_features != self.n_input_features_: raise ValueError("X shape does not match training shape") # allocate output data XP = np.empty((n_samples, self.n_output_features_), dtype=X.dtype) combinations = self._combinations(n_features, self.degree, self.interaction_only, self.include_bias) for i, c in enumerate(combinations): XP[:, i] = X[:, c].prod(1) return XP def normalize(X, norm='l2', axis=1, copy=True, return_norm=False): """Scale input vectors individually to unit norm (vector length). Read more in the :ref:`User Guide <preprocessing_normalization>`. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data to normalize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy. norm : 'l1', 'l2', or 'max', optional ('l2' by default) The norm to use to normalize each non zero sample (or each non-zero feature if axis is 0). axis : 0 or 1, optional (1 by default) axis used to normalize the data along. If 1, independently normalize each sample, otherwise (if 0) normalize each feature. copy : boolean, optional, default True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix and if axis is 1). return_norm : boolean, default False whether to return the computed norms Returns ------- X : {array-like, sparse matrix}, shape [n_samples, n_features] Normalized input X. norms : array, shape [n_samples] if axis=1 else [n_features] An array of norms along given axis for X. When X is sparse, a NotImplementedError will be raised for norm 'l1' or 'l2'. See also -------- Normalizer: Performs normalization using the ``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`). Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. """ if norm not in ('l1', 'l2', 'max'): raise ValueError("'%s' is not a supported norm" % norm) if axis == 0: sparse_format = 'csc' elif axis == 1: sparse_format = 'csr' else: raise ValueError("'%d' is not a supported axis" % axis) X = check_array(X, sparse_format, copy=copy, estimator='the normalize function', dtype=FLOAT_DTYPES) if axis == 0: X = X.T if sparse.issparse(X): if return_norm and norm in ('l1', 'l2'): raise NotImplementedError("return_norm=True is not implemented " "for sparse matrices with norm 'l1' " "or norm 'l2'") if norm == 'l1': inplace_csr_row_normalize_l1(X) elif norm == 'l2': inplace_csr_row_normalize_l2(X) elif norm == 'max': _, norms = min_max_axis(X, 1) norms_elementwise = norms.repeat(np.diff(X.indptr)) mask = norms_elementwise != 0 X.data[mask] /= norms_elementwise[mask] else: if norm == 'l1': norms = np.abs(X).sum(axis=1) elif norm == 'l2': norms = row_norms(X) elif norm == 'max': norms = np.max(X, axis=1) norms = _handle_zeros_in_scale(norms, copy=False) X /= norms[:, np.newaxis] if axis == 0: X = X.T if return_norm: return X, norms else: return X class Normalizer(BaseEstimator, TransformerMixin): """Normalize samples individually to unit norm. Each sample (i.e. each row of the data matrix) with at least one non zero component is rescaled independently of other samples so that its norm (l1 or l2) equals one. This transformer is able to work both with dense numpy arrays and scipy.sparse matrix (use CSR format if you want to avoid the burden of a copy / conversion). Scaling inputs to unit norms is a common operation for text classification or clustering for instance. For instance the dot product of two l2-normalized TF-IDF vectors is the cosine similarity of the vectors and is the base similarity metric for the Vector Space Model commonly used by the Information Retrieval community. Read more in the :ref:`User Guide <preprocessing_normalization>`. Parameters ---------- norm : 'l1', 'l2', or 'max', optional ('l2' by default) The norm to use to normalize each non zero sample. copy : boolean, optional, default True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix). Notes ----- This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline. For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. See also -------- normalize: Equivalent function without the estimator API. """ def __init__(self, norm='l2', copy=True): self.norm = norm self.copy = copy def fit(self, X, y=None): """Do nothing and return the estimator unchanged This method is just there to implement the usual API and hence work in pipelines. Parameters ---------- X : array-like """ X = check_array(X, accept_sparse='csr') return self def transform(self, X, y='deprecated', copy=None): """Scale each non zero row of X to unit norm Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data to normalize, row by row. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy. y : (ignored) .. deprecated:: 0.19 This parameter will be removed in 0.21. copy : bool, optional (default: None) Copy the input X or not. """ if not isinstance(y, string_types) or y != 'deprecated': warnings.warn("The parameter y on transform() is " "deprecated since 0.19 and will be removed in 0.21", DeprecationWarning) copy = copy if copy is not None else self.copy X = check_array(X, accept_sparse='csr') return normalize(X, norm=self.norm, axis=1, copy=copy) def binarize(X, threshold=0.0, copy=True): """Boolean thresholding of array-like or scipy.sparse matrix Read more in the :ref:`User Guide <preprocessing_binarization>`. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data to binarize, element by element. scipy.sparse matrices should be in CSR or CSC format to avoid an un-necessary copy. threshold : float, optional (0.0 by default) Feature values below or equal to this are replaced by 0, above it by 1. Threshold may not be less than 0 for operations on sparse matrices. copy : boolean, optional, default True set to False to perform inplace binarization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR / CSC matrix and if axis is 1). See also -------- Binarizer: Performs binarization using the ``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`). """ X = check_array(X, accept_sparse=['csr', 'csc'], copy=copy) if sparse.issparse(X): if threshold < 0: raise ValueError('Cannot binarize a sparse matrix with threshold ' '< 0') cond = X.data > threshold not_cond = np.logical_not(cond) X.data[cond] = 1 X.data[not_cond] = 0 X.eliminate_zeros() else: cond = X > threshold not_cond = np.logical_not(cond) X[cond] = 1 X[not_cond] = 0 return X class Binarizer(BaseEstimator, TransformerMixin): """Binarize data (set feature values to 0 or 1) according to a threshold Values greater than the threshold map to 1, while values less than or equal to the threshold map to 0. With the default threshold of 0, only positive values map to 1. Binarization is a common operation on text count data where the analyst can decide to only consider the presence or absence of a feature rather than a quantified number of occurrences for instance. It can also be used as a pre-processing step for estimators that consider boolean random variables (e.g. modelled using the Bernoulli distribution in a Bayesian setting). Read more in the :ref:`User Guide <preprocessing_binarization>`. Parameters ---------- threshold : float, optional (0.0 by default) Feature values below or equal to this are replaced by 0, above it by 1. Threshold may not be less than 0 for operations on sparse matrices. copy : boolean, optional, default True set to False to perform inplace binarization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix). Notes ----- If the input is a sparse matrix, only the non-zero values are subject to update by the Binarizer class. This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline. See also -------- binarize: Equivalent function without the estimator API. """ def __init__(self, threshold=0.0, copy=True): self.threshold = threshold self.copy = copy def fit(self, X, y=None): """Do nothing and return the estimator unchanged This method is just there to implement the usual API and hence work in pipelines. Parameters ---------- X : array-like """ check_array(X, accept_sparse='csr') return self def transform(self, X, y='deprecated', copy=None): """Binarize each element of X Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] The data to binarize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy. y : (ignored) .. deprecated:: 0.19 This parameter will be removed in 0.21. copy : bool Copy the input X or not. """ if not isinstance(y, string_types) or y != 'deprecated': warnings.warn("The parameter y on transform() is " "deprecated since 0.19 and will be removed in 0.21", DeprecationWarning) copy = copy if copy is not None else self.copy return binarize(X, threshold=self.threshold, copy=copy) class KernelCenterer(BaseEstimator, TransformerMixin): """Center a kernel matrix Let K(x, z) be a kernel defined by phi(x)^T phi(z), where phi is a function mapping x to a Hilbert space. KernelCenterer centers (i.e., normalize to have zero mean) the data without explicitly computing phi(x). It is equivalent to centering phi(x) with sklearn.preprocessing.StandardScaler(with_std=False). Read more in the :ref:`User Guide <kernel_centering>`. """ def fit(self, K, y=None): """Fit KernelCenterer Parameters ---------- K : numpy array of shape [n_samples, n_samples] Kernel matrix. Returns ------- self : returns an instance of self. """ K = check_array(K, dtype=FLOAT_DTYPES) n_samples = K.shape[0] self.K_fit_rows_ = np.sum(K, axis=0) / n_samples self.K_fit_all_ = self.K_fit_rows_.sum() / n_samples return self def transform(self, K, y='deprecated', copy=True): """Center kernel matrix. Parameters ---------- K : numpy array of shape [n_samples1, n_samples2] Kernel matrix. y : (ignored) .. deprecated:: 0.19 This parameter will be removed in 0.21. copy : boolean, optional, default True Set to False to perform inplace computation. Returns ------- K_new : numpy array of shape [n_samples1, n_samples2] """ if not isinstance(y, string_types) or y != 'deprecated': warnings.warn("The parameter y on transform() is " "deprecated since 0.19 and will be removed in 0.21", DeprecationWarning) check_is_fitted(self, 'K_fit_all_') K = check_array(K, copy=copy, dtype=FLOAT_DTYPES) K_pred_cols = (np.sum(K, axis=1) / self.K_fit_rows_.shape[0])[:, np.newaxis] K -= self.K_fit_rows_ K -= K_pred_cols K += self.K_fit_all_ return K @property def _pairwise(self): return True def add_dummy_feature(X, value=1.0): """Augment dataset with an additional dummy feature. This is useful for fitting an intercept term with implementations which cannot otherwise fit it directly. Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] Data. value : float Value to use for the dummy feature. Returns ------- X : {array, sparse matrix}, shape [n_samples, n_features + 1] Same data with dummy feature added as first column. Examples -------- >>> from sklearn.preprocessing import add_dummy_feature >>> add_dummy_feature([[0, 1], [1, 0]]) array([[ 1., 0., 1.], [ 1., 1., 0.]]) """ X = check_array(X, accept_sparse=['csc', 'csr', 'coo'], dtype=FLOAT_DTYPES) n_samples, n_features = X.shape shape = (n_samples, n_features + 1) if sparse.issparse(X): if sparse.isspmatrix_coo(X): # Shift columns to the right. col = X.col + 1 # Column indices of dummy feature are 0 everywhere. col = np.concatenate((np.zeros(n_samples), col)) # Row indices of dummy feature are 0, ..., n_samples-1. row = np.concatenate((np.arange(n_samples), X.row)) # Prepend the dummy feature n_samples times. data = np.concatenate((np.ones(n_samples) * value, X.data)) return sparse.coo_matrix((data, (row, col)), shape) elif sparse.isspmatrix_csc(X): # Shift index pointers since we need to add n_samples elements. indptr = X.indptr + n_samples # indptr[0] must be 0. indptr = np.concatenate((np.array([0]), indptr)) # Row indices of dummy feature are 0, ..., n_samples-1. indices = np.concatenate((np.arange(n_samples), X.indices)) # Prepend the dummy feature n_samples times. data = np.concatenate((np.ones(n_samples) * value, X.data)) return sparse.csc_matrix((data, indices, indptr), shape) else: klass = X.__class__ return klass(add_dummy_feature(X.tocoo(), value)) else: return np.hstack((np.ones((n_samples, 1)) * value, X)) def _transform_selected(X, transform, selected="all", copy=True): """Apply a transform function to portion of selected features Parameters ---------- X : {array-like, sparse matrix}, shape [n_samples, n_features] Dense array or sparse matrix. transform : callable A callable transform(X) -> X_transformed copy : boolean, optional Copy X even if it could be avoided. selected: "all" or array of indices or mask Specify which features to apply the transform to. Returns ------- X : array or sparse matrix, shape=(n_samples, n_features_new) """ X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES) if isinstance(selected, six.string_types) and selected == "all": return transform(X) if len(selected) == 0: return X n_features = X.shape[1] ind = np.arange(n_features) sel = np.zeros(n_features, dtype=bool) sel[np.asarray(selected)] = True not_sel = np.logical_not(sel) n_selected = np.sum(sel) if n_selected == 0: # No features selected. return X elif n_selected == n_features: # All features selected. return transform(X) else: X_sel = transform(X[:, ind[sel]]) X_not_sel = X[:, ind[not_sel]] if sparse.issparse(X_sel) or sparse.issparse(X_not_sel): return sparse.hstack((X_sel, X_not_sel)) else: return np.hstack((X_sel, X_not_sel)) class OneHotEncoder(BaseEstimator, TransformerMixin): """Encode categorical integer features using a one-hot aka one-of-K scheme. The input to this transformer should be a matrix of integers, denoting the values taken on by categorical (discrete) features. The output will be a sparse matrix where each column corresponds to one possible value of one feature. It is assumed that input features take on values in the range [0, n_values). This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels. Note: a one-hot encoding of y labels should use a LabelBinarizer instead. Read more in the :ref:`User Guide <preprocessing_categorical_features>`. Parameters ---------- n_values : 'auto', int or array of ints Number of values per feature. - 'auto' : determine value range from training data. - int : number of categorical values per feature. Each feature value should be in ``range(n_values)`` - array : ``n_values[i]`` is the number of categorical values in ``X[:, i]``. Each feature value should be in ``range(n_values[i])`` categorical_features : "all" or array of indices or mask Specify what features are treated as categorical. - 'all' (default): All features are treated as categorical. - array of indices: Array of categorical feature indices. - mask: Array of length n_features and with dtype=bool. Non-categorical features are always stacked to the right of the matrix. dtype : number type, default=np.float Desired dtype of output. sparse : boolean, default=True Will return sparse matrix if set True else will return an array. handle_unknown : str, 'error' or 'ignore' Whether to raise an error or ignore if a unknown categorical feature is present during transform. Attributes ---------- active_features_ : array Indices for active features, meaning values that actually occur in the training set. Only available when n_values is ``'auto'``. feature_indices_ : array of shape (n_features,) Indices to feature ranges. Feature ``i`` in the original data is mapped to features from ``feature_indices_[i]`` to ``feature_indices_[i+1]`` (and then potentially masked by `active_features_` afterwards) n_values_ : array of shape (n_features,) Maximum number of values per feature. Examples -------- Given a dataset with three features and four samples, we let the encoder find the maximum value per feature and transform the data to a binary one-hot encoding. >>> from sklearn.preprocessing import OneHotEncoder >>> enc = OneHotEncoder() >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], \ [1, 0, 2]]) # doctest: +ELLIPSIS OneHotEncoder(categorical_features='all', dtype=<... 'numpy.float64'>, handle_unknown='error', n_values='auto', sparse=True) >>> enc.n_values_ array([2, 3, 4]) >>> enc.feature_indices_ array([0, 2, 5, 9]) >>> enc.transform([[0, 1, 1]]).toarray() array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]]) See also -------- sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of dictionary items (also handles string-valued features). sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot encoding of dictionary items or strings. sklearn.preprocessing.LabelBinarizer : binarizes labels in a one-vs-all fashion. sklearn.preprocessing.MultiLabelBinarizer : transforms between iterable of iterables and a multilabel format, e.g. a (samples x classes) binary matrix indicating the presence of a class label. sklearn.preprocessing.LabelEncoder : encodes labels with values between 0 and n_classes-1. """ def __init__(self, n_values="auto", categorical_features="all", dtype=np.float64, sparse=True, handle_unknown='error'): self.n_values = n_values self.categorical_features = categorical_features self.dtype = dtype self.sparse = sparse self.handle_unknown = handle_unknown def fit(self, X, y=None): """Fit OneHotEncoder to X. Parameters ---------- X : array-like, shape [n_samples, n_feature] Input array of type int. Returns ------- self """ self.fit_transform(X) return self def _fit_transform(self, X): """Assumes X contains only categorical features.""" X = check_array(X, dtype=np.int) if np.any(X < 0): raise ValueError("X needs to contain only non-negative integers.") n_samples, n_features = X.shape if (isinstance(self.n_values, six.string_types) and self.n_values == 'auto'): n_values = np.max(X, axis=0) + 1 elif isinstance(self.n_values, numbers.Integral): if (np.max(X, axis=0) >= self.n_values).any(): raise ValueError("Feature out of bounds for n_values=%d" % self.n_values) n_values = np.empty(n_features, dtype=np.int) n_values.fill(self.n_values) else: try: n_values = np.asarray(self.n_values, dtype=int) except (ValueError, TypeError): raise TypeError("Wrong type for parameter `n_values`. Expected" " 'auto', int or array of ints, got %r" % type(X)) if n_values.ndim < 1 or n_values.shape[0] != X.shape[1]: raise ValueError("Shape mismatch: if n_values is an array," " it has to be of shape (n_features,).") self.n_values_ = n_values n_values = np.hstack([[0], n_values]) indices = np.cumsum(n_values) self.feature_indices_ = indices column_indices = (X + indices[:-1]).ravel() row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), n_features) data = np.ones(n_samples * n_features) out = sparse.coo_matrix((data, (row_indices, column_indices)), shape=(n_samples, indices[-1]), dtype=self.dtype).tocsr() if (isinstance(self.n_values, six.string_types) and self.n_values == 'auto'): mask = np.array(out.sum(axis=0)).ravel() != 0 active_features = np.where(mask)[0] out = out[:, active_features] self.active_features_ = active_features return out if self.sparse else out.toarray() def fit_transform(self, X, y=None): """Fit OneHotEncoder to X, then transform X. Equivalent to self.fit(X).transform(X), but more convenient and more efficient. See fit for the parameters, transform for the return value. Parameters ---------- X : array-like, shape [n_samples, n_feature] Input array of type int. """ return _transform_selected(X, self._fit_transform, self.categorical_features, copy=True) def _transform(self, X): """Assumes X contains only categorical features.""" X = check_array(X, dtype=np.int) if np.any(X < 0): raise ValueError("X needs to contain only non-negative integers.") n_samples, n_features = X.shape indices = self.feature_indices_ if n_features != indices.shape[0] - 1: raise ValueError("X has different shape than during fitting." " Expected %d, got %d." % (indices.shape[0] - 1, n_features)) # We use only those categorical features of X that are known using fit. # i.e lesser than n_values_ using mask. # This means, if self.handle_unknown is "ignore", the row_indices and # col_indices corresponding to the unknown categorical feature are # ignored. mask = (X < self.n_values_).ravel() if np.any(~mask): if self.handle_unknown not in ['error', 'ignore']: raise ValueError("handle_unknown should be either error or " "unknown got %s" % self.handle_unknown) if self.handle_unknown == 'error': raise ValueError("unknown categorical feature present %s " "during transform." % X.ravel()[~mask]) column_indices = (X + indices[:-1]).ravel()[mask] row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), n_features)[mask] data = np.ones(np.sum(mask)) out = sparse.coo_matrix((data, (row_indices, column_indices)), shape=(n_samples, indices[-1]), dtype=self.dtype).tocsr() if (isinstance(self.n_values, six.string_types) and self.n_values == 'auto'): out = out[:, self.active_features_] return out if self.sparse else out.toarray() def transform(self, X): """Transform X using one-hot encoding. Parameters ---------- X : array-like, shape [n_samples, n_features] Input array of type int. Returns ------- X_out : sparse matrix if sparse=True else a 2-d array, dtype=int Transformed input. """ return _transform_selected(X, self._transform, self.categorical_features, copy=True) class QuantileTransformer(BaseEstimator, TransformerMixin): """Transform features using quantiles information. This method transforms the features to follow a uniform or a normal distribution. Therefore, for a given feature, this transformation tends to spread out the most frequent values. It also reduces the impact of (marginal) outliers: this is therefore a robust preprocessing scheme. The transformation is applied on each feature independently. The cumulative density function of a feature is used to project the original values. Features values of new/unseen data that fall below or above the fitted range will be mapped to the bounds of the output distribution. Note that this transform is non-linear. It may distort linear correlations between variables measured at the same scale but renders variables measured at different scales more directly comparable. Read more in the :ref:`User Guide <preprocessing_transformer>`. Parameters ---------- n_quantiles : int, optional (default=1000) Number of quantiles to be computed. It corresponds to the number of landmarks used to discretize the cumulative density function. output_distribution : str, optional (default='uniform') Marginal distribution for the transformed data. The choices are 'uniform' (default) or 'normal'. ignore_implicit_zeros : bool, optional (default=False) Only applies to sparse matrices. If True, the sparse entries of the matrix are discarded to compute the quantile statistics. If False, these entries are treated as zeros. subsample : int, optional (default=1e5) Maximum number of samples used to estimate the quantiles for computational efficiency. Note that the subsampling procedure may differ for value-identical sparse and dense matrices. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Note that this is used by subsampling and smoothing noise. copy : boolean, optional, (default=True) Set to False to perform inplace transformation and avoid a copy (if the input is already a numpy array). Attributes ---------- quantiles_ : ndarray, shape (n_quantiles, n_features) The values corresponding the quantiles of reference. references_ : ndarray, shape(n_quantiles, ) Quantiles of references. Examples -------- >>> import numpy as np >>> from sklearn.preprocessing import QuantileTransformer >>> rng = np.random.RandomState(0) >>> X = np.sort(rng.normal(loc=0.5, scale=0.25, size=(25, 1)), axis=0) >>> qt = QuantileTransformer(n_quantiles=10, random_state=0) >>> qt.fit_transform(X) # doctest: +ELLIPSIS array([...]) See also -------- quantile_transform : Equivalent function without the estimator API. StandardScaler : perform standardization that is faster, but less robust to outliers. RobustScaler : perform robust standardization that removes the influence of outliers but does not put outliers and inliers on the same scale. Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. """ def __init__(self, n_quantiles=1000, output_distribution='uniform', ignore_implicit_zeros=False, subsample=int(1e5), random_state=None, copy=True): self.n_quantiles = n_quantiles self.output_distribution = output_distribution self.ignore_implicit_zeros = ignore_implicit_zeros self.subsample = subsample self.random_state = random_state self.copy = copy def _dense_fit(self, X, random_state): """Compute percentiles for dense matrices. Parameters ---------- X : ndarray, shape (n_samples, n_features) The data used to scale along the features axis. """ if self.ignore_implicit_zeros: warnings.warn("'ignore_implicit_zeros' takes effect only with" " sparse matrix. This parameter has no effect.") n_samples, n_features = X.shape # for compatibility issue with numpy<=1.8.X, references # need to be a list scaled between 0 and 100 references = (self.references_ * 100).tolist() self.quantiles_ = [] for col in X.T: if self.subsample < n_samples: subsample_idx = random_state.choice(n_samples, size=self.subsample, replace=False) col = col.take(subsample_idx, mode='clip') self.quantiles_.append(np.percentile(col, references)) self.quantiles_ = np.transpose(self.quantiles_) def _sparse_fit(self, X, random_state): """Compute percentiles for sparse matrices. Parameters ---------- X : sparse matrix CSC, shape (n_samples, n_features) The data used to scale along the features axis. The sparse matrix needs to be nonnegative. """ n_samples, n_features = X.shape # for compatibility issue with numpy<=1.8.X, references # need to be a list scaled between 0 and 100 references = list(map(lambda x: x * 100, self.references_)) self.quantiles_ = [] for feature_idx in range(n_features): column_nnz_data = X.data[X.indptr[feature_idx]: X.indptr[feature_idx + 1]] if len(column_nnz_data) > self.subsample: column_subsample = (self.subsample * len(column_nnz_data) // n_samples) if self.ignore_implicit_zeros: column_data = np.zeros(shape=column_subsample, dtype=X.dtype) else: column_data = np.zeros(shape=self.subsample, dtype=X.dtype) column_data[:column_subsample] = random_state.choice( column_nnz_data, size=column_subsample, replace=False) else: if self.ignore_implicit_zeros: column_data = np.zeros(shape=len(column_nnz_data), dtype=X.dtype) else: column_data = np.zeros(shape=n_samples, dtype=X.dtype) column_data[:len(column_nnz_data)] = column_nnz_data if not column_data.size: # if no nnz, an error will be raised for computing the # quantiles. Force the quantiles to be zeros. self.quantiles_.append([0] * len(references)) else: self.quantiles_.append( np.percentile(column_data, references)) self.quantiles_ = np.transpose(self.quantiles_) def fit(self, X, y=None): """Compute the quantiles used for transforming. Parameters ---------- X : ndarray or sparse matrix, shape (n_samples, n_features) The data used to scale along the features axis. If a sparse matrix is provided, it will be converted into a sparse ``csc_matrix``. Additionally, the sparse matrix needs to be nonnegative if `ignore_implicit_zeros` is False. Returns ------- self : object Returns self """ if self.n_quantiles <= 0: raise ValueError("Invalid value for 'n_quantiles': %d. " "The number of quantiles must be at least one." % self.n_quantiles) if self.subsample <= 0: raise ValueError("Invalid value for 'subsample': %d. " "The number of subsamples must be at least one." % self.subsample) if self.n_quantiles > self.subsample: raise ValueError("The number of quantiles cannot be greater than" " the number of samples used. Got {} quantiles" " and {} samples.".format(self.n_quantiles, self.subsample)) X = self._check_inputs(X) rng = check_random_state(self.random_state) # Create the quantiles of reference self.references_ = np.linspace(0, 1, self.n_quantiles, endpoint=True) if sparse.issparse(X): self._sparse_fit(X, rng) else: self._dense_fit(X, rng) return self def _transform_col(self, X_col, quantiles, inverse): """Private function to transform a single feature""" if self.output_distribution == 'normal': output_distribution = 'norm' else: output_distribution = self.output_distribution output_distribution = getattr(stats, output_distribution) # older version of scipy do not handle tuple as fill_value # clipping the value before transform solve the issue if not inverse: lower_bound_x = quantiles[0] upper_bound_x = quantiles[-1] lower_bound_y = 0 upper_bound_y = 1 else: lower_bound_x = 0 upper_bound_x = 1 lower_bound_y = quantiles[0] upper_bound_y = quantiles[-1] # for inverse transform, match a uniform PDF X_col = output_distribution.cdf(X_col) # find index for lower and higher bounds lower_bounds_idx = (X_col - BOUNDS_THRESHOLD < lower_bound_x) upper_bounds_idx = (X_col + BOUNDS_THRESHOLD > upper_bound_x) if not inverse: # Interpolate in one direction and in the other and take the # mean. This is in case of repeated values in the features # and hence repeated quantiles # # If we don't do this, only one extreme of the duplicated is # used (the upper when we do assending, and the # lower for descending). We take the mean of these two X_col = .5 * (np.interp(X_col, quantiles, self.references_) - np.interp(-X_col, -quantiles[::-1], -self.references_[::-1])) else: X_col = np.interp(X_col, self.references_, quantiles) X_col[upper_bounds_idx] = upper_bound_y X_col[lower_bounds_idx] = lower_bound_y # for forward transform, match the output PDF if not inverse: X_col = output_distribution.ppf(X_col) # find the value to clip the data to avoid mapping to # infinity. Clip such that the inverse transform will be # consistent clip_min = output_distribution.ppf(BOUNDS_THRESHOLD - np.spacing(1)) clip_max = output_distribution.ppf(1 - (BOUNDS_THRESHOLD - np.spacing(1))) X_col = np.clip(X_col, clip_min, clip_max) return X_col def _check_inputs(self, X, accept_sparse_negative=False): """Check inputs before fit and transform""" X = check_array(X, accept_sparse='csc', copy=self.copy, dtype=[np.float64, np.float32]) # we only accept positive sparse matrix when ignore_implicit_zeros is # false and that we call fit or transform. if (not accept_sparse_negative and not self.ignore_implicit_zeros and (sparse.issparse(X) and np.any(X.data < 0))): raise ValueError('QuantileTransformer only accepts non-negative' ' sparse matrices.') # check the output PDF if self.output_distribution not in ('normal', 'uniform'): raise ValueError("'output_distribution' has to be either 'normal'" " or 'uniform'. Got '{}' instead.".format( self.output_distribution)) return X def _check_is_fitted(self, X): """Check the inputs before transforming""" check_is_fitted(self, 'quantiles_') # check that the dimension of X are adequate with the fitted data if X.shape[1] != self.quantiles_.shape[1]: raise ValueError('X does not have the same number of features as' ' the previously fitted data. Got {} instead of' ' {}.'.format(X.shape[1], self.quantiles_.shape[1])) def _transform(self, X, inverse=False): """Forward and inverse transform. Parameters ---------- X : ndarray, shape (n_samples, n_features) The data used to scale along the features axis. inverse : bool, optional (default=False) If False, apply forward transform. If True, apply inverse transform. Returns ------- X : ndarray, shape (n_samples, n_features) Projected data """ if sparse.issparse(X): for feature_idx in range(X.shape[1]): column_slice = slice(X.indptr[feature_idx], X.indptr[feature_idx + 1]) X.data[column_slice] = self._transform_col( X.data[column_slice], self.quantiles_[:, feature_idx], inverse) else: for feature_idx in range(X.shape[1]): X[:, feature_idx] = self._transform_col( X[:, feature_idx], self.quantiles_[:, feature_idx], inverse) return X def transform(self, X): """Feature-wise transformation of the data. Parameters ---------- X : ndarray or sparse matrix, shape (n_samples, n_features) The data used to scale along the features axis. If a sparse matrix is provided, it will be converted into a sparse ``csc_matrix``. Additionally, the sparse matrix needs to be nonnegative if `ignore_implicit_zeros` is False. Returns ------- Xt : ndarray or sparse matrix, shape (n_samples, n_features) The projected data. """ X = self._check_inputs(X) self._check_is_fitted(X) return self._transform(X, inverse=False) def inverse_transform(self, X): """Back-projection to the original space. Parameters ---------- X : ndarray or sparse matrix, shape (n_samples, n_features) The data used to scale along the features axis. If a sparse matrix is provided, it will be converted into a sparse ``csc_matrix``. Additionally, the sparse matrix needs to be nonnegative if `ignore_implicit_zeros` is False. Returns ------- Xt : ndarray or sparse matrix, shape (n_samples, n_features) The projected data. """ X = self._check_inputs(X, accept_sparse_negative=True) self._check_is_fitted(X) return self._transform(X, inverse=True) def quantile_transform(X, axis=0, n_quantiles=1000, output_distribution='uniform', ignore_implicit_zeros=False, subsample=int(1e5), random_state=None, copy=False): """Transform features using quantiles information. This method transforms the features to follow a uniform or a normal distribution. Therefore, for a given feature, this transformation tends to spread out the most frequent values. It also reduces the impact of (marginal) outliers: this is therefore a robust preprocessing scheme. The transformation is applied on each feature independently. The cumulative density function of a feature is used to project the original values. Features values of new/unseen data that fall below or above the fitted range will be mapped to the bounds of the output distribution. Note that this transform is non-linear. It may distort linear correlations between variables measured at the same scale but renders variables measured at different scales more directly comparable. Read more in the :ref:`User Guide <preprocessing_transformer>`. Parameters ---------- X : array-like, sparse matrix The data to transform. axis : int, (default=0) Axis used to compute the means and standard deviations along. If 0, transform each feature, otherwise (if 1) transform each sample. n_quantiles : int, optional (default=1000) Number of quantiles to be computed. It corresponds to the number of landmarks used to discretize the cumulative density function. output_distribution : str, optional (default='uniform') Marginal distribution for the transformed data. The choices are 'uniform' (default) or 'normal'. ignore_implicit_zeros : bool, optional (default=False) Only applies to sparse matrices. If True, the sparse entries of the matrix are discarded to compute the quantile statistics. If False, these entries are treated as zeros. subsample : int, optional (default=1e5) Maximum number of samples used to estimate the quantiles for computational efficiency. Note that the subsampling procedure may differ for value-identical sparse and dense matrices. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Note that this is used by subsampling and smoothing noise. copy : boolean, optional, (default=True) Set to False to perform inplace transformation and avoid a copy (if the input is already a numpy array). Attributes ---------- quantiles_ : ndarray, shape (n_quantiles, n_features) The values corresponding the quantiles of reference. references_ : ndarray, shape(n_quantiles, ) Quantiles of references. Examples -------- >>> import numpy as np >>> from sklearn.preprocessing import quantile_transform >>> rng = np.random.RandomState(0) >>> X = np.sort(rng.normal(loc=0.5, scale=0.25, size=(25, 1)), axis=0) >>> quantile_transform(X, n_quantiles=10, random_state=0) ... # doctest: +ELLIPSIS array([...]) See also -------- QuantileTransformer : Performs quantile-based scaling using the ``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`). scale : perform standardization that is faster, but less robust to outliers. robust_scale : perform robust standardization that removes the influence of outliers but does not put outliers and inliers on the same scale. Notes ----- For a comparison of the different scalers, transformers, and normalizers, see :ref:`examples/preprocessing/plot_all_scaling.py <sphx_glr_auto_examples_preprocessing_plot_all_scaling.py>`. """ n = QuantileTransformer(n_quantiles=n_quantiles, output_distribution=output_distribution, subsample=subsample, ignore_implicit_zeros=ignore_implicit_zeros, random_state=random_state, copy=copy) if axis == 0: return n.fit_transform(X) elif axis == 1: return n.fit_transform(X.T).T else: raise ValueError("axis should be either equal to 0 or 1. Got" " axis={}".format(axis))
mit
stylianos-kampakis/scikit-learn
examples/svm/plot_svm_regression.py
249
1451
""" =================================================================== Support Vector Regression (SVR) using linear and non-linear kernels =================================================================== Toy example of 1D regression using linear, polynomial and RBF kernels. """ print(__doc__) import numpy as np from sklearn.svm import SVR import matplotlib.pyplot as plt ############################################################################### # Generate sample data X = np.sort(5 * np.random.rand(40, 1), axis=0) y = np.sin(X).ravel() ############################################################################### # Add noise to targets y[::5] += 3 * (0.5 - np.random.rand(8)) ############################################################################### # Fit regression model svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1) svr_lin = SVR(kernel='linear', C=1e3) svr_poly = SVR(kernel='poly', C=1e3, degree=2) y_rbf = svr_rbf.fit(X, y).predict(X) y_lin = svr_lin.fit(X, y).predict(X) y_poly = svr_poly.fit(X, y).predict(X) ############################################################################### # look at the results plt.scatter(X, y, c='k', label='data') plt.hold('on') plt.plot(X, y_rbf, c='g', label='RBF model') plt.plot(X, y_lin, c='r', label='Linear model') plt.plot(X, y_poly, c='b', label='Polynomial model') plt.xlabel('data') plt.ylabel('target') plt.title('Support Vector Regression') plt.legend() plt.show()
bsd-3-clause
jpautom/scikit-learn
examples/cluster/plot_birch_vs_minibatchkmeans.py
333
3694
""" ================================= Compare BIRCH and MiniBatchKMeans ================================= This example compares the timing of Birch (with and without the global clustering step) and MiniBatchKMeans on a synthetic dataset having 100,000 samples and 2 features generated using make_blobs. If ``n_clusters`` is set to None, the data is reduced from 100,000 samples to a set of 158 clusters. This can be viewed as a preprocessing step before the final (global) clustering step that further reduces these 158 clusters to 100 clusters. """ # Authors: Manoj Kumar <[email protected] # Alexandre Gramfort <[email protected]> # License: BSD 3 clause print(__doc__) from itertools import cycle from time import time import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from sklearn.preprocessing import StandardScaler from sklearn.cluster import Birch, MiniBatchKMeans from sklearn.datasets.samples_generator import make_blobs # Generate centers for the blobs so that it forms a 10 X 10 grid. xx = np.linspace(-22, 22, 10) yy = np.linspace(-22, 22, 10) xx, yy = np.meshgrid(xx, yy) n_centres = np.hstack((np.ravel(xx)[:, np.newaxis], np.ravel(yy)[:, np.newaxis])) # Generate blobs to do a comparison between MiniBatchKMeans and Birch. X, y = make_blobs(n_samples=100000, centers=n_centres, random_state=0) # Use all colors that matplotlib provides by default. colors_ = cycle(colors.cnames.keys()) fig = plt.figure(figsize=(12, 4)) fig.subplots_adjust(left=0.04, right=0.98, bottom=0.1, top=0.9) # Compute clustering with Birch with and without the final clustering step # and plot. birch_models = [Birch(threshold=1.7, n_clusters=None), Birch(threshold=1.7, n_clusters=100)] final_step = ['without global clustering', 'with global clustering'] for ind, (birch_model, info) in enumerate(zip(birch_models, final_step)): t = time() birch_model.fit(X) time_ = time() - t print("Birch %s as the final step took %0.2f seconds" % ( info, (time() - t))) # Plot result labels = birch_model.labels_ centroids = birch_model.subcluster_centers_ n_clusters = np.unique(labels).size print("n_clusters : %d" % n_clusters) ax = fig.add_subplot(1, 3, ind + 1) for this_centroid, k, col in zip(centroids, range(n_clusters), colors_): mask = labels == k ax.plot(X[mask, 0], X[mask, 1], 'w', markerfacecolor=col, marker='.') if birch_model.n_clusters is None: ax.plot(this_centroid[0], this_centroid[1], '+', markerfacecolor=col, markeredgecolor='k', markersize=5) ax.set_ylim([-25, 25]) ax.set_xlim([-25, 25]) ax.set_autoscaley_on(False) ax.set_title('Birch %s' % info) # Compute clustering with MiniBatchKMeans. mbk = MiniBatchKMeans(init='k-means++', n_clusters=100, batch_size=100, n_init=10, max_no_improvement=10, verbose=0, random_state=0) t0 = time() mbk.fit(X) t_mini_batch = time() - t0 print("Time taken to run MiniBatchKMeans %0.2f seconds" % t_mini_batch) mbk_means_labels_unique = np.unique(mbk.labels_) ax = fig.add_subplot(1, 3, 3) for this_centroid, k, col in zip(mbk.cluster_centers_, range(n_clusters), colors_): mask = mbk.labels_ == k ax.plot(X[mask, 0], X[mask, 1], 'w', markerfacecolor=col, marker='.') ax.plot(this_centroid[0], this_centroid[1], '+', markeredgecolor='k', markersize=5) ax.set_xlim([-25, 25]) ax.set_ylim([-25, 25]) ax.set_title("MiniBatchKMeans") ax.set_autoscaley_on(False) plt.show()
bsd-3-clause
cybercomgroup/Big_Data
Cloudera/Code/million_song_dataset/Spark_scripts/spark_visualisehottnessbyartist.py
1
1183
from pyspark import SparkConf from pyspark import SparkContext import sys import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import svm import random #To run: PYSPARK_PYTHON=/opt/cloudera/parcels/Anaconda/bin/python spark-submit spark_visualisehottnessbyartist.py /user/cloudera/song/song_final.csv def rddToPand(RDD): header = "temp" first = True data = [] # Convert unicode to ascii for x in RDD.collect(): if first: first = False header = x.encode("ascii").split(',') else: data.append(tuple(x.encode("ascii").split(','))) return pd.DataFrame.from_records(data, columns = header) def test(row): for x in range(0, row.count()): if x!=3 and x!=5: row[x]='' return row # Init Spark conf = SparkConf() conf.setMaster('yarn-client') conf.setAppName('artisthotness-job') sc = SparkContext(conf=conf) rdd = sc.textFile(str(sys.argv[1])) mapped = rdd.map(lambda line: line.split(',')).map(lambda line: row[3]) mapped2 = rdd.map(lambda line: line.split(',')).map(lambda line: row[5]) maps = mapped.join(mapped2) df = rddToPand(mapped) file = open('visualise.txt', 'w') file.write(str(mapped2.take(10))) file.close()
gpl-3.0
jangorecki/h2o-3
h2o-py/dynamic_tests/testdir_algos/glm/pyunit_glm_binomial_large.py
4
116214
from __future__ import print_function import sys sys.path.insert(1, "../../../") import random import os import math import numpy as np import h2o import time from builtins import range from tests import pyunit_utils from h2o.estimators.glm import H2OGeneralizedLinearEstimator from h2o.grid.grid_search import H2OGridSearch from scipy import stats from sklearn.linear_model import LogisticRegression from sklearn import metrics class TestGLMBinomial: """ This class is created to test the GLM algo with Binomial family. In this case, the relationship between the response Y and predictor vector X is assumed to be Prob(Y = 1|X) = exp(W^T * X + E)/(1+exp(W^T * X + E)) where E is unknown Gaussian noise. We generate random data set using the exact formula. To evaluate the H2O GLM Model, we run the sklearn logistic regression with the same data sets and compare the performance of the two. If they are close enough within a certain tolerance, we declare the H2O model working. When regularization and other parameters are enabled, we can evaluate H2O GLM model performance by comparing the logloss/accuracy from H2O model and to the H2O model generated without regularization. As long as they do not deviate too much, we consider the H2O model performance satisfactory. In particular, I have written 8 tests in the hope to exercise as many parameters settings of the GLM algo with Binomial distribution as possible. Tomas has requested 2 tests to be added to test his new feature of missing_values_handling with predictors with both categorical/real columns. Here is a list of all tests descriptions: test1_glm_no_regularization(): sklearn logistic regression model is built. H2O GLM is built for Binomial family with the same random data sets. We observe the weights, confusion matrices from the two models. We compare the logloss, prediction accuracy from the two models to determine if H2O GLM model shall pass the test. test2_glm_lambda_search(): test lambda search with alpha set to 0.5 per Tomas's suggestion. Make sure logloss and prediction accuracy generated here is comparable in value to H2O GLM with no regularization. test3_glm_grid_search_over_params(): test grid search over various alpha values while lambda is set to be the best value obtained from test 2. Cross validation with k=5 and random assignment is enabled as well. The best model performance hopefully will generate logloss and prediction accuracies close to H2O with no regularization in test 1. test4_glm_remove_collinear_columns(): test parameter remove_collinear_columns=True with lambda set to best lambda from test 2, alpha set to best alpha from Gridsearch and solver set to the one which generate the smallest validation logloss. The same dataset is used here except that we randomly choose predictor columns to repeat and scale. Make sure logloss and prediction accuracies generated here is comparable in value to H2O GLM model with no regularization. test5_missing_values(): Test parameter missing_values_handling="MeanImputation" with only real value predictors. The same data sets as before is used. However, we go into the predictor matrix and randomly decide to replace a value with nan and create missing values. Sklearn logistic regression model is built using the data set where we have imputed the missing values. This Sklearn model will be used to compare our H2O models with. test6_enum_missing_values(): Test parameter missing_values_handling="MeanImputation" with mixed predictors (categorical/real value columns). We first generate a data set that contains a random number of columns of categorical and real value columns. Next, we encode the categorical columns. Then, we generate the random data set using the formula as before. Next, we go into the predictor matrix and randomly decide to change a value to be nan and create missing values. Again, we build a Sklearn logistic regression model and compare our H2O model with it. test7_missing_enum_values_lambda_search(): Test parameter missing_values_handling="MeanImputation" with mixed predictors (categorical/real value columns). Test parameter missing_values_handling="MeanImputation" with mixed predictors (categorical/real value columns) and setting lambda search to be True. We use the same prediction data with missing values from test6. Next, we encode the categorical columns using true one hot encoding since Lambda-search will be enabled with alpha set to 0.5. Since the encoding is different in this case from test6, we will build a brand new Sklearn logistic regression model and compare the best H2O model logloss/prediction accuracy with it. """ # parameters set by users, change with care max_col_count = 50 # set maximum values of train/test row and column counts max_col_count_ratio = 500 # set max row count to be multiples of col_count to avoid overfitting min_col_count_ratio = 100 # set min row count to be multiples of col_count to avoid overfitting ###### for debugging # max_col_count = 5 # set maximum values of train/test row and column counts # max_col_count_ratio = 50 # set max row count to be multiples of col_count to avoid overfitting # min_col_count_ratio = 10 max_p_value = 2 # set maximum predictor value min_p_value = -2 # set minimum predictor value max_w_value = 2 # set maximum weight value min_w_value = -2 # set minimum weight value enum_levels = 5 # maximum number of levels for categorical variables not counting NAs class_method = 'probability' # can be 'probability' or 'threshold', control how discrete response is generated test_class_method = 'probability' # for test data set margin = 0.0 # only used when class_method = 'threshold' test_class_margin = 0.2 # for test data set family = 'binomial' # this test is for Binomial GLM curr_time = str(round(time.time())) # parameters denoting filenames of interested that store training/validation/test data sets training_filename = family+"_"+curr_time+"_training_set.csv" training_filename_duplicate = family+"_"+curr_time+"_training_set_duplicate.csv" training_filename_nans = family+"_"+curr_time+"_training_set_NA.csv" training_filename_enum = family+"_"+curr_time+"_training_set_enum.csv" training_filename_enum_true_one_hot = family+"_"+curr_time+"_training_set_enum_trueOneHot.csv" training_filename_enum_nans = family+"_"+curr_time+"_training_set_enum_NAs.csv" training_filename_enum_nans_true_one_hot = family+"_"+curr_time+"_training_set_enum_NAs_trueOneHot.csv" validation_filename = family+"_"+curr_time+"_validation_set.csv" validation_filename_enum = family+"_"+curr_time+"_validation_set_enum.csv" validation_filename_enum_true_one_hot = family+"_"+curr_time+"_validation_set_enum_trueOneHot.csv" validation_filename_enum_nans = family+"_"+curr_time+"_validation_set_enum_NAs.csv" validation_filename_enum_nans_true_one_hot = family+"_"+curr_time+"_validation_set_enum_NAs_trueOneHot.csv" test_filename = family+"_"+curr_time+"_test_set.csv" test_filename_duplicate = family+"_"+curr_time+"_test_set_duplicate.csv" test_filename_nans = family+"_"+curr_time+"_test_set_NA.csv" test_filename_enum = family+"_"+curr_time+"_test_set_enum.csv" test_filename_enum_true_one_hot = family+"_"+curr_time+"_test_set_enum_trueOneHot.csv" test_filename_enum_nans = family+"_"+curr_time+"_test_set_enum_NAs.csv" test_filename_enum_nans_true_one_hot = family+"_"+curr_time+"_test_set_enum_NAs_trueOneHot.csv" weight_filename = family+"_"+curr_time+"_weight.csv" weight_filename_enum = family+"_"+curr_time+"_weight_enum.csv" total_test_number = 7 # total number of tests being run for GLM Binomial family ignored_eps = 1e-15 # if p-values < than this value, no comparison is performed, only for Gaussian allowed_diff = 0.1 # tolerance of comparison for logloss/prediction accuracy, okay to be loose. Condition # to run the codes are different duplicate_col_counts = 5 # maximum number of times to duplicate a column duplicate_threshold = 0.2 # for each column, a coin is tossed to see if we duplicate that column or not duplicate_max_scale = 2 # maximum scale factor for duplicated columns nan_fraction = 0.2 # denote maximum fraction of NA's to be inserted into a column # System parameters, do not change. Dire consequences may follow if you do current_dir = os.path.dirname(os.path.realpath(sys.argv[1])) # directory of this test file enum_col = 0 # set maximum number of categorical columns in predictor enum_level_vec = [] # vector containing number of levels for each categorical column noise_std = 0 # noise variance in Binomial noise generation added to response train_row_count = 0 # training data row count, randomly generated later train_col_count = 0 # training data column count, randomly generated later class_number = 2 # actual number of classes existed in data set, randomly generated later data_type = 2 # determine data type of data set and weight, 1: integers, 2: real # parameters denoting filenames with absolute paths training_data_file = os.path.join(current_dir, training_filename) training_data_file_duplicate = os.path.join(current_dir, training_filename_duplicate) training_data_file_nans = os.path.join(current_dir, training_filename_nans) training_data_file_enum = os.path.join(current_dir, training_filename_enum) training_data_file_enum_true_one_hot = os.path.join(current_dir, training_filename_enum_true_one_hot) training_data_file_enum_nans = os.path.join(current_dir, training_filename_enum_nans) training_data_file_enum_nans_true_one_hot = os.path.join(current_dir, training_filename_enum_nans_true_one_hot) validation_data_file = os.path.join(current_dir, validation_filename) validation_data_file_enum = os.path.join(current_dir, validation_filename_enum) validation_data_file_enum_true_one_hot = os.path.join(current_dir, validation_filename_enum_true_one_hot) validation_data_file_enum_nans = os.path.join(current_dir, validation_filename_enum_nans) validation_data_file_enum_nans_true_one_hot = os.path.join(current_dir, validation_filename_enum_nans_true_one_hot) test_data_file = os.path.join(current_dir, test_filename) test_data_file_duplicate = os.path.join(current_dir, test_filename_duplicate) test_data_file_nans = os.path.join(current_dir, test_filename_nans) test_data_file_enum = os.path.join(current_dir, test_filename_enum) test_data_file_enum_true_one_hot = os.path.join(current_dir, test_filename_enum_true_one_hot) test_data_file_enum_nans = os.path.join(current_dir, test_filename_enum_nans) test_data_file_enum_nans_true_one_hot = os.path.join(current_dir, test_filename_enum_nans_true_one_hot) weight_data_file = os.path.join(current_dir, weight_filename) weight_data_file_enum = os.path.join(current_dir, weight_filename_enum) # store template model performance values for later comparison test1_model = None # store template model for later comparison test1_model_metrics = None # store template model test metrics for later comparison best_lambda = 0.0 # store best lambda obtained using lambda search test_name = "pyunit_glm_binomial.py" # name of this test sandbox_dir = "" # sandbox directory where we are going to save our failed test data sets # store information about training data set, validation and test data sets that are used # by many tests. We do not want to keep loading them for each set in the hope of # saving time. Trading off memory and speed here. x_indices = [] # store predictor indices in the data set y_index = [] # store response index in the data set training_data = [] # store training data set test_data = [] # store test data set valid_data = [] # store validation data set training_data_grid = [] # store combined training and validation data set for cross validation best_alpha = 0.5 # store best alpha value found best_grid_logloss = -1 # store lowest MSE found from grid search test_failed_array = [0]*total_test_number # denote test results for all tests run. 1 error, 0 pass test_num = 0 # index representing which test is being run duplicate_col_indices = [] # denote column indices when column duplication is applied duplicate_col_scales = [] # store scaling factor for all columns when duplication is applied noise_var = noise_std*noise_std # Binomial noise variance test_failed = 0 # count total number of tests that have failed sklearn_class_weight = {} # used to make sure Sklearn will know the correct number of classes def __init__(self): self.setup() def setup(self): """ This function performs all initializations necessary: 1. generates all the random values for our dynamic tests like the Binomial noise std, column count and row count for training data set; 2. generate the training/validation/test data sets with only real values; 3. insert missing values into training/valid/test data sets. 4. taken the training/valid/test data sets, duplicate random certain columns, each duplicated column is repeated for a random number of times and randomly scaled; 5. generate the training/validation/test data sets with predictors containing enum and real values as well***. 6. insert missing values into the training/validation/test data sets with predictors containing enum and real values as well *** according to Tomas, when working with mixed predictors (contains both enum/real value columns), the encoding used is different when regularization is enabled or disabled. When regularization is enabled, true one hot encoding is enabled to encode the enum values to binary bits. When regularization is disabled, a reference level plus one hot encoding is enabled when encoding the enum values to binary bits. One data set is generated when we work with mixed predictors. """ # clean out the sandbox directory first self.sandbox_dir = pyunit_utils.make_Rsandbox_dir(self.current_dir, self.test_name, True) # randomly set Binomial noise standard deviation as a fraction of actual predictor standard deviation self.noise_std = random.uniform(0, math.sqrt(pow((self.max_p_value - self.min_p_value), 2) / 12)) self.noise_var = self.noise_std*self.noise_std # randomly determine data set size in terms of column and row counts self.train_col_count = random.randint(3, self.max_col_count) # account for enum columns later self.train_row_count = int(round(self.train_col_count*random.uniform(self.min_col_count_ratio, self.max_col_count_ratio))) # # DEBUGGING setup_data, remember to comment them out once done. # self.train_col_count = 3 # self.train_row_count = 500 # end DEBUGGING # randomly set number of enum and real columns in the data set self.enum_col = random.randint(1, self.train_col_count-1) # randomly set number of levels for each categorical column self.enum_level_vec = np.random.random_integers(2, self.enum_levels-1, [self.enum_col, 1]) # generate real value weight vector and training/validation/test data sets for GLM pyunit_utils.write_syn_floating_point_dataset_glm(self.training_data_file, self.validation_data_file, self.test_data_file, self.weight_data_file, self.train_row_count, self.train_col_count, self.data_type, self.max_p_value, self.min_p_value, self.max_w_value, self.min_w_value, self.noise_std, self.family, self.train_row_count, self.train_row_count, class_number=self.class_number, class_method=[self.class_method, self.class_method, self.test_class_method], class_margin=[self.margin, self.margin, self.test_class_margin]) # randomly generate the duplicated and scaled columns (self.duplicate_col_indices, self.duplicate_col_scales) = \ pyunit_utils.random_col_duplication(self.train_col_count, self.duplicate_threshold, self.duplicate_col_counts, True, self.duplicate_max_scale) # apply the duplication and scaling to training and test set # need to add the response column to the end of duplicated column indices and scale dup_col_indices = self.duplicate_col_indices dup_col_indices.append(self.train_col_count) dup_col_scale = self.duplicate_col_scales dup_col_scale.append(1.0) # print out duplication information for easy debugging print("duplication column and duplication scales are: ") print(dup_col_indices) print(dup_col_scale) # print out duplication information for easy debugging print("duplication column and duplication scales are: ") print(dup_col_indices) print(dup_col_scale) pyunit_utils.duplicate_scale_cols(dup_col_indices, dup_col_scale, self.training_data_file, self.training_data_file_duplicate) pyunit_utils.duplicate_scale_cols(dup_col_indices, dup_col_scale, self.test_data_file, self.test_data_file_duplicate) # insert NAs into training/test data sets pyunit_utils.insert_nan_in_data(self.training_data_file, self.training_data_file_nans, self.nan_fraction) pyunit_utils.insert_nan_in_data(self.test_data_file, self.test_data_file_nans, self.nan_fraction) # generate data sets with enum as well as real values pyunit_utils.write_syn_mixed_dataset_glm(self.training_data_file_enum, self.training_data_file_enum_true_one_hot, self.validation_data_file_enum, self.validation_data_file_enum_true_one_hot, self.test_data_file_enum, self.test_data_file_enum_true_one_hot, self.weight_data_file_enum, self.train_row_count, self.train_col_count, self.max_p_value, self.min_p_value, self.max_w_value, self.min_w_value, self.noise_std, self.family, self.train_row_count, self.train_row_count, self.enum_col, self.enum_level_vec, class_number=self.class_number, class_method=[self.class_method, self.class_method, self.test_class_method], class_margin=[self.margin, self.margin, self.test_class_margin]) # insert NAs into data set with categorical columns pyunit_utils.insert_nan_in_data(self.training_data_file_enum, self.training_data_file_enum_nans, self.nan_fraction) pyunit_utils.insert_nan_in_data(self.validation_data_file_enum, self.validation_data_file_enum_nans, self.nan_fraction) pyunit_utils.insert_nan_in_data(self.test_data_file_enum, self.test_data_file_enum_nans, self.nan_fraction) pyunit_utils.insert_nan_in_data(self.training_data_file_enum_true_one_hot, self.training_data_file_enum_nans_true_one_hot, self.nan_fraction) pyunit_utils.insert_nan_in_data(self.validation_data_file_enum_true_one_hot, self.validation_data_file_enum_nans_true_one_hot, self.nan_fraction) pyunit_utils.insert_nan_in_data(self.test_data_file_enum_true_one_hot, self.test_data_file_enum_nans_true_one_hot, self.nan_fraction) # only preload data sets that will be used for multiple tests and change the response to enums self.training_data = h2o.import_file(pyunit_utils.locate(self.training_data_file)) # set indices for response and predictor columns in data set for H2O GLM model to use self.y_index = self.training_data.ncol-1 self.x_indices = list(range(self.y_index)) # added the round() so that this will work on win8. self.training_data[self.y_index] = self.training_data[self.y_index].round().asfactor() # check to make sure all response classes are represented, otherwise, quit if self.training_data[self.y_index].nlevels()[0] < self.class_number: print("Response classes are not represented in training dataset.") sys.exit(0) self.valid_data = h2o.import_file(pyunit_utils.locate(self.validation_data_file)) self.valid_data[self.y_index] = self.valid_data[self.y_index].round().asfactor() self.test_data = h2o.import_file(pyunit_utils.locate(self.test_data_file)) self.test_data[self.y_index] = self.test_data[self.y_index].round().asfactor() # make a bigger training set for grid search by combining data from validation data set self.training_data_grid = self.training_data.rbind(self.valid_data) # setup_data sklearn class weight of all ones. Used only to make sure sklearn know the correct number of classes for ind in range(self.class_number): self.sklearn_class_weight[ind] = 1.0 # save the training data files just in case the code crashed. pyunit_utils.remove_csv_files(self.current_dir, ".csv", action='copy', new_dir_path=self.sandbox_dir) def teardown(self): """ This function performs teardown after the dynamic test is completed. If all tests passed, it will delete all data sets generated since they can be quite large. It will move the training/validation/test data sets into a Rsandbox directory so that we can re-run the failed test. """ remove_files = [] # create Rsandbox directory to keep data sets and weight information self.sandbox_dir = pyunit_utils.make_Rsandbox_dir(self.current_dir, self.test_name, True) # Do not want to save all data sets. Only save data sets that are needed for failed tests if sum(self.test_failed_array[0:4]): pyunit_utils.move_files(self.sandbox_dir, self.training_data_file, self.training_filename) pyunit_utils.move_files(self.sandbox_dir, self.validation_data_file, self.validation_filename) pyunit_utils.move_files(self.sandbox_dir, self.test_data_file, self.test_filename) else: # remove those files instead of moving them remove_files.append(self.training_data_file) remove_files.append(self.validation_data_file) remove_files.append(self.test_data_file) if sum(self.test_failed_array[0:6]): pyunit_utils.move_files(self.sandbox_dir, self.weight_data_file, self.weight_filename) else: remove_files.append(self.weight_data_file) if self.test_failed_array[3]: pyunit_utils.move_files(self.sandbox_dir, self.training_data_file, self.training_filename) pyunit_utils.move_files(self.sandbox_dir, self.test_data_file, self.test_filename) pyunit_utils.move_files(self.sandbox_dir, self.test_data_file_duplicate, self.test_filename_duplicate) pyunit_utils.move_files(self.sandbox_dir, self.training_data_file_duplicate, self.training_filename_duplicate) else: remove_files.append(self.training_data_file_duplicate) remove_files.append(self.test_data_file_duplicate) if self.test_failed_array[4]: pyunit_utils.move_files(self.sandbox_dir, self.training_data_file, self.training_filename) pyunit_utils.move_files(self.sandbox_dir, self.test_data_file, self.test_filename) pyunit_utils.move_files(self.sandbox_dir, self.training_data_file_nans, self.training_filename_nans) pyunit_utils.move_files(self.sandbox_dir, self.test_data_file_nans, self.test_filename_nans) else: remove_files.append(self.training_data_file_nans) remove_files.append(self.test_data_file_nans) if self.test_failed_array[5]: pyunit_utils.move_files(self.sandbox_dir, self.training_data_file_enum_nans, self.training_filename_enum_nans) pyunit_utils.move_files(self.sandbox_dir, self.test_data_file_enum_nans, self.test_filename_enum_nans) pyunit_utils.move_files(self.sandbox_dir, self.weight_data_file_enum, self.weight_filename_enum) else: remove_files.append(self.training_data_file_enum_nans) remove_files.append(self.training_data_file_enum) remove_files.append(self.test_data_file_enum_nans) remove_files.append(self.test_data_file_enum) remove_files.append(self.validation_data_file_enum_nans) remove_files.append(self.validation_data_file_enum) remove_files.append(self.weight_data_file_enum) if self.test_failed_array[6]: pyunit_utils.move_files(self.sandbox_dir, self.training_data_file_enum_nans_true_one_hot, self.training_filename_enum_nans_true_one_hot) pyunit_utils.move_files(self.sandbox_dir, self.validation_data_file_enum_nans_true_one_hot, self.validation_filename_enum_nans_true_one_hot) pyunit_utils.move_files(self.sandbox_dir, self.test_data_file_enum_nans_true_one_hot, self.test_filename_enum_nans_true_one_hot) pyunit_utils.move_files(self.sandbox_dir, self.weight_data_file_enum, self.weight_filename_enum) else: remove_files.append(self.training_data_file_enum_nans_true_one_hot) remove_files.append(self.training_data_file_enum_true_one_hot) remove_files.append(self.validation_data_file_enum_nans_true_one_hot) remove_files.append(self.validation_data_file_enum_true_one_hot) remove_files.append(self.test_data_file_enum_nans_true_one_hot) remove_files.append(self.test_data_file_enum_true_one_hot) if not(self.test_failed): # all tests have passed. Delete sandbox if if was not wiped before pyunit_utils.make_Rsandbox_dir(self.current_dir, self.test_name, False) # remove any csv files left in test directory, do not remove them, shared computing resources if len(remove_files) > 0: for file in remove_files: pyunit_utils.remove_files(file) def test1_glm_no_regularization(self): """ In this test, a sklearn logistic regression model and a H2O GLM are built for Binomial family with the same random data sets. We observe the weights, confusion matrices from the two models. We compare the logloss, prediction accuracy from the two models to determine if H2O GLM model shall pass the test. """ print("*******************************************************************************************") print("Test1: build H2O GLM with Binomial with no regularization.") h2o.cluster_info() # training result from python Sklearn logistic regression model (p_weights, p_logloss_train, p_cm_train, p_accuracy_training, p_logloss_test, p_cm_test, p_accuracy_test) = \ self.sklearn_binomial_result(self.training_data_file, self.test_data_file, False, False) # build our H2O model self.test1_model = H2OGeneralizedLinearEstimator(family=self.family, Lambda=0) self.test1_model.train(x=self.x_indices, y=self.y_index, training_frame=self.training_data) # calculate test metrics self.test1_model_metrics = self.test1_model.model_performance(test_data=self.test_data) num_test_failed = self.test_failed # used to determine if the current test has failed # print out comparison results for weight/logloss/prediction accuracy self.test_failed = \ pyunit_utils.extract_comparison_attributes_and_print_multinomial(self.test1_model, self.test1_model_metrics, self.family, "\nTest1 Done!", compare_att_str=[ "\nComparing intercept and " "weights ....", "\nComparing logloss from training " "dataset ....", "\nComparing logloss from" " test dataset ....", "\nComparing confusion matrices from " "training dataset ....", "\nComparing confusion matrices from " "test dataset ...", "\nComparing accuracy from training " "dataset ....", "\nComparing accuracy from test " "dataset ...."], h2o_att_str=[ "H2O intercept and weights: \n", "H2O logloss from training dataset: ", "H2O logloss from test dataset", "H2O confusion matrix from training " "dataset: \n", "H2O confusion matrix from test" " dataset: \n", "H2O accuracy from training dataset: ", "H2O accuracy from test dataset: "], template_att_str=[ "Sklearn intercept and weights: \n", "Sklearn logloss from training " "dataset: ", "Sklearn logloss from test dataset: ", "Sklearn confusion matrix from" " training dataset: \n", "Sklearn confusion matrix from test " "dataset: \n", "Sklearn accuracy from training " "dataset: ", "Sklearn accuracy from test " "dataset: "], att_str_fail=[ "Intercept and weights are not equal!", "Logloss from training dataset differ " "too much!", "Logloss from test dataset differ too " "much!", "", "", "Accuracies from training dataset " "differ too much!", "Accuracies from test dataset differ " "too much!"], att_str_success=[ "Intercept and weights are close" " enough!", "Logloss from training dataset are " "close enough!", "Logloss from test dataset are close " "enough!", "", "", "Accuracies from training dataset are " "close enough!", "Accuracies from test dataset are" " close enough!"], can_be_better_than_template=[ True, True, True, True, True, True, True], just_print=[True, True, True, True, True, True, False], failed_test_number=self.test_failed, template_params=[ p_weights, p_logloss_train, p_cm_train, p_accuracy_training, p_logloss_test, p_cm_test, p_accuracy_test], ignored_eps=self.ignored_eps, allowed_diff=self.allowed_diff) # print out test results and update test_failed_array status to reflect if this test has failed self.test_failed_array[self.test_num] += pyunit_utils.show_test_results("test1_glm_no_regularization", num_test_failed, self.test_failed) self.test_num += 1 # update test index def test2_glm_lambda_search(self): """ This test is used to test the lambda search. Recall that lambda search enables efficient and automatic search for the optimal value of the lambda parameter. When lambda search is enabled, GLM will first fit a model with maximum regularization and then keep decreasing it until over-fitting occurs. The resulting model is based on the best lambda value. According to Tomas, set alpha = 0.5 and enable validation but not cross-validation. """ print("*******************************************************************************************") print("Test2: tests the lambda search.") h2o.cluster_info() # generate H2O model with lambda search enabled model_h2o_0p5 = H2OGeneralizedLinearEstimator(family=self.family, lambda_search=True, alpha=0.5, lambda_min_ratio=1e-20) model_h2o_0p5.train(x=self.x_indices, y=self.y_index, training_frame=self.training_data, validation_frame=self.valid_data) # get best lambda here self.best_lambda = pyunit_utils.get_train_glm_params(model_h2o_0p5, 'best_lambda') # get test performance here h2o_model_0p5_test_metrics = model_h2o_0p5.model_performance(test_data=self.test_data) num_test_failed = self.test_failed # print out comparison results for our H2O GLM and test1 H2O model self.test_failed = \ pyunit_utils.extract_comparison_attributes_and_print_multinomial(model_h2o_0p5, h2o_model_0p5_test_metrics, self.family, "\nTest2 Done!", test_model=self.test1_model, test_model_metric=self.test1_model_metrics, compare_att_str=[ "\nComparing intercept and" " weights ....", "\nComparing logloss from training " "dataset ....", "\nComparing logloss from test" " dataset ....", "\nComparing confusion matrices from " "training dataset ....", "\nComparing confusion matrices from " "test dataset ...", "\nComparing accuracy from training " "dataset ....", "\nComparing accuracy from test" " dataset ...."], h2o_att_str=[ "H2O lambda search intercept and " "weights: \n", "H2O lambda search logloss from" " training dataset: ", "H2O lambda search logloss from test " "dataset", "H2O lambda search confusion matrix " "from training dataset: \n", "H2O lambda search confusion matrix " "from test dataset: \n", "H2O lambda search accuracy from " "training dataset: ", "H2O lambda search accuracy from test" " dataset: "], template_att_str=[ "H2O test1 template intercept and" " weights: \n", "H2O test1 template logloss from " "training dataset: ", "H2O test1 template logloss from " "test dataset: ", "H2O test1 template confusion" " matrix from training dataset: \n", "H2O test1 template confusion" " matrix from test dataset: \n", "H2O test1 template accuracy from " "training dataset: ", "H2O test1 template accuracy from" " test dataset: "], att_str_fail=[ "Intercept and weights are not equal!", "Logloss from training dataset differ " "too much!", "Logloss from test dataset differ too" " much!", "", "", "Accuracies from training dataset" " differ too much!", "Accuracies from test dataset differ" " too much!"], att_str_success=[ "Intercept and weights are close " "enough!", "Logloss from training dataset are" " close enough!", "Logloss from test dataset are close" " enough!", "", "", "Accuracies from training dataset are" " close enough!", "Accuracies from test dataset are" " close enough!"], can_be_better_than_template=[ True, False, True, True, True, True, True], just_print=[True, False, False, True, True, True, False], failed_test_number=self.test_failed, ignored_eps=self.ignored_eps, allowed_diff=self.allowed_diff) # print out test results and update test_failed_array status to reflect if this test has failed self.test_failed_array[self.test_num] += pyunit_utils.show_test_results("test2_glm_lambda_search", num_test_failed, self.test_failed) self.test_num += 1 def test3_glm_grid_search(self): """ This test is used to test GridSearch with the following parameters: 1. Lambda = best_lambda value from test2 2. alpha = [0 0.5 0.99] 3. cross-validation with k = 5, fold_assignment = "Random" We will look at the best results from the grid search and compare it with H2O model built in test 1. :return: None """ print("*******************************************************************************************") print("Test3: explores various parameter settings in training the GLM using GridSearch using solver ") h2o.cluster_info() hyper_parameters = {'alpha': [0, 0.5, 0.99]} # set hyper_parameters for grid search # train H2O GLM model with grid search model_h2o_gridsearch = \ H2OGridSearch(H2OGeneralizedLinearEstimator(family=self.family, Lambda=self.best_lambda, nfolds=5, fold_assignment='Random'), hyper_parameters) model_h2o_gridsearch.train(x=self.x_indices, y=self.y_index, training_frame=self.training_data_grid) # print out the model sequence ordered by the best validation logloss values, thanks Ludi! temp_model = model_h2o_gridsearch.sort_by("logloss(xval=True)") # obtain the model ID of best model (with smallest MSE) and use that for our evaluation best_model_id = temp_model['Model Id'][0] self.best_grid_logloss = temp_model['logloss(xval=True)'][0] self.best_alpha = model_h2o_gridsearch.get_hyperparams(best_model_id) best_model = h2o.get_model(best_model_id) best_model_test_metrics = best_model.model_performance(test_data=self.test_data) num_test_failed = self.test_failed # print out comparison results for our H2O GLM with H2O model from test 1 self.test_failed = \ pyunit_utils.extract_comparison_attributes_and_print_multinomial(best_model, best_model_test_metrics, self.family, "\nTest3 " + " Done!", test_model=self.test1_model, test_model_metric=self.test1_model_metrics, compare_att_str=[ "\nComparing intercept and" " weights ....", "\nComparing logloss from training " "dataset ....", "\nComparing logloss from test dataset" " ....", "\nComparing confusion matrices from " "training dataset ....", "\nComparing confusion matrices from " "test dataset ...", "\nComparing accuracy from training " "dataset ....", "\nComparing accuracy from test " " sdataset ...."], h2o_att_str=[ "H2O grid search intercept and " "weights: \n", "H2O grid search logloss from training" " dataset: ", "H2O grid search logloss from test " "dataset", "H2O grid search confusion matrix from" " training dataset: \n", "H2O grid search confusion matrix from" " test dataset: \n", "H2O grid search accuracy from" " training dataset: ", "H2O grid search accuracy from test " "dataset: "], template_att_str=[ "H2O test1 template intercept and" " weights: \n", "H2O test1 template logloss from" " training dataset: ", "H2O test1 template logloss from" " test dataset: ", "H2O test1 template confusion" " matrix from training dataset: \n", "H2O test1 template confusion" " matrix from test dataset: \n", "H2O test1 template accuracy from" " training dataset: ", "H2O test1 template accuracy from" " test dataset: "], att_str_fail=[ "Intercept and weights are not equal!", "Logloss from training dataset differ" " too much!", "Logloss from test dataset differ too" " much!", "", "", "Accuracies from training dataset" " differ too much!", "Accuracies from test dataset differ" " too much!"], att_str_success=[ "Intercept and weights are close" " enough!", "Logloss from training dataset are" " close enough!", "Logloss from test dataset are close" " enough!", "", "", "Accuracies from training dataset are" " close enough!", "Accuracies from test dataset are" " close enough!"], can_be_better_than_template=[ True, True, True, True, True, True, True], just_print=[ True, True, True, True, True, True, False], failed_test_number=self.test_failed, ignored_eps=self.ignored_eps, allowed_diff=self.allowed_diff) # print out test results and update test_failed_array status to reflect if this test has failed self.test_failed_array[self.test_num] += pyunit_utils.show_test_results("test_glm_grid_search_over_params", num_test_failed, self.test_failed) self.test_num += 1 def test4_glm_remove_collinear_columns(self): """ With the best parameters obtained from test 3 grid search, we will trained GLM with duplicated columns and enable remove_collinear_columns and see if the algorithm catches the duplicated columns. We will compare the results with test 1 results. """ print("*******************************************************************************************") print("Test4: test the GLM remove_collinear_columns.") h2o.cluster_info() # read in training data sets with duplicated columns training_data = h2o.import_file(pyunit_utils.locate(self.training_data_file_duplicate)) test_data = h2o.import_file(pyunit_utils.locate(self.test_data_file_duplicate)) y_index = training_data.ncol-1 x_indices = list(range(y_index)) # change response variable to be categorical training_data[y_index] = training_data[y_index].round().asfactor() test_data[y_index] = test_data[y_index].round().asfactor() # train H2O model with remove_collinear_columns=True model_h2o = H2OGeneralizedLinearEstimator(family=self.family, Lambda=self.best_lambda, alpha=self.best_alpha, remove_collinear_columns=True) model_h2o.train(x=x_indices, y=y_index, training_frame=training_data) print("Best lambda is {0}, best alpha is {1}".format(self.best_lambda, self.best_alpha)) # evaluate model over test data set model_h2o_metrics = model_h2o.model_performance(test_data=test_data) num_test_failed = self.test_failed # print out comparison results our H2O GLM and test1 H2O model self.test_failed = \ pyunit_utils.extract_comparison_attributes_and_print_multinomial(model_h2o, model_h2o_metrics, self.family, "\nTest3 Done!", test_model=self.test1_model, test_model_metric=self.test1_model_metrics, compare_att_str=[ "\nComparing intercept and weights" " ....", "\nComparing logloss from training " "dataset ....", "\nComparing logloss from test" " dataset ....", "\nComparing confusion matrices from" " training dataset ....", "\nComparing confusion matrices from" " test dataset ...", "\nComparing accuracy from training" " dataset ....", "\nComparing accuracy from test" " dataset ...."], h2o_att_str=[ "H2O remove_collinear_columns " "intercept and weights: \n", "H2O remove_collinear_columns" " logloss from training dataset: ", "H2O remove_collinear_columns" " logloss from test dataset", "H2O remove_collinear_columns" " confusion matrix from " "training dataset: \n", "H2O remove_collinear_columns" " confusion matrix from" " test dataset: \n", "H2O remove_collinear_columns" " accuracy from" " training dataset: ", "H2O remove_collinear_columns" " accuracy from test" " dataset: "], template_att_str=[ "H2O test1 template intercept and" " weights: \n", "H2O test1 template logloss from" " training dataset: ", "H2O test1 template logloss from" " test dataset: ", "H2O test1 template confusion" " matrix from training dataset: \n", "H2O test1 template confusion" " matrix from test dataset: \n", "H2O test1 template accuracy from" " training dataset: ", "H2O test1 template accuracy from" " test dataset: "], att_str_fail=[ "Intercept and weights are not equal!", "Logloss from training dataset differ" " too much!", "Logloss from test dataset differ too" " much!", "", "", "Accuracies from training dataset" " differ too much!", "Accuracies from test dataset differ" " too much!"], att_str_success=[ "Intercept and weights are close" " enough!", "Logloss from training dataset are" " close enough!", "Logloss from test dataset are close" " enough!", "", "", "Accuracies from training dataset are" " close enough!", "Accuracies from test dataset are" " close enough!"], can_be_better_than_template=[ True, True, True, True, True, True, True], just_print=[True, True, True, True, True, True, False], failed_test_number=self.test_failed, ignored_eps=self.ignored_eps, allowed_diff=self.allowed_diff) # print out test results and update test_failed_array status to reflect if this test has failed self.test_failed_array[self.test_num] += pyunit_utils.show_test_results("test4_glm_remove_collinear_columns", num_test_failed, self.test_failed) self.test_num += 1 def test5_missing_values(self): """ Test parameter missing_values_handling="MeanImputation" with only real value predictors. The same data sets as before is used. However, we go into the predictor matrix and randomly decide to replace a value with nan and create missing values. Sklearn logistic regression model is built using the data set where we have imputed the missing values. This Sklearn model will be used to compare our H2O models with. """ print("*******************************************************************************************") print("Test5: test the GLM with imputation of missing values with column averages.") h2o.cluster_info() # training result from python sklearn (p_weights, p_logloss_train, p_cm_train, p_accuracy_training, p_logloss_test, p_cm_test, p_accuracy_test) = \ self.sklearn_binomial_result(self.training_data_file_nans, self.test_data_file_nans, False, False) # import training set and test set training_data = h2o.import_file(pyunit_utils.locate(self.training_data_file_nans)) test_data = h2o.import_file(pyunit_utils.locate(self.test_data_file_nans)) # change the response columns to be categorical training_data[self.y_index] = training_data[self.y_index].round().asfactor() test_data[self.y_index] = test_data[self.y_index].round().asfactor() # train H2O models with missing_values_handling="MeanImputation" model_h2o = H2OGeneralizedLinearEstimator(family=self.family, Lambda=0, missing_values_handling="MeanImputation") model_h2o.train(x=self.x_indices, y=self.y_index, training_frame=training_data) # calculate H2O model performance with test data set h2o_model_test_metrics = model_h2o.model_performance(test_data=test_data) num_test_failed = self.test_failed # print out comparison results our H2O GLM and Sklearn model self.test_failed = \ pyunit_utils.extract_comparison_attributes_and_print_multinomial(model_h2o, h2o_model_test_metrics, self.family, "\nTest5 Done!", compare_att_str=[ "\nComparing intercept and weights" " ....", "\nComparing logloss from training" " dataset ....", "\nComparing logloss from test" " dataset ....", "\nComparing confusion matrices from" " training dataset ....", "\nComparing confusion matrices from" " test dataset ...", "\nComparing accuracy from training" " dataset ....", "\nComparing accuracy from test" " dataset ...."], h2o_att_str=[ "H2O missing values intercept and" " weights: \n", "H2O missing values logloss from" " training dataset: ", "H2O missing values logloss from" " test dataset", "H2O missing values confusion matrix" " from training dataset: \n", "H2O missing values confusion matrix" " from test dataset: \n", "H2O missing values accuracy from" " training dataset: ", "H2O missing values accuracy from" " test dataset: "], template_att_str=[ "Sklearn missing values intercept" " and weights: \n", "Sklearn missing values logloss from" " training dataset: ", "Sklearn missing values logloss from" " test dataset: ", "Sklearn missing values confusion" " matrix from training dataset: \n", "Sklearn missing values confusion" " matrix from test dataset: \n", "Sklearn missing values accuracy" " from training dataset: ", "Sklearn missing values accuracy" " from test dataset: "], att_str_fail=[ "Intercept and weights are not equal!", "Logloss from training dataset differ" " too much!", "Logloss from test dataset differ" " too much!", "", "", "Accuracies from training dataset" " differ too much!", "Accuracies from test dataset differ" " too much!"], att_str_success=[ "Intercept and weights are close " "enough!", "Logloss from training dataset are" " close enough!", "Logloss from test dataset are close" " enough!", "", "", "Accuracies from training dataset are" " close enough!", "Accuracies from test dataset are" " close enough!"], can_be_better_than_template=[ True, True, True, True, True, True, True], just_print=[ True, True, True, True, True, True, False], failed_test_number=self.test_failed, template_params=[ p_weights, p_logloss_train, p_cm_train, p_accuracy_training, p_logloss_test, p_cm_test, p_accuracy_test], ignored_eps=self.ignored_eps, allowed_diff=self.allowed_diff) # print out test results and update test_failed_array status to reflect if tests have failed self.test_failed_array[self.test_num] += pyunit_utils.show_test_results("test5_missing_values", num_test_failed, self.test_failed) self.test_num += 1 def test6_enum_missing_values(self): """ Test parameter missing_values_handling="MeanImputation" with mixed predictors (categorical/real value columns). We first generate a data set that contains a random number of columns of categorical and real value columns. Next, we encode the categorical columns. Then, we generate the random data set using the formula as before. Next, we go into the predictor matrix and randomly decide to change a value to be nan and create missing values. Again, we build a Sklearn logistic regression and compare our H2O models with it. """ # no regularization in this case, use reference level plus one-hot-encoding print("*******************************************************************************************") print("Test6: test the GLM with enum/real values.") h2o.cluster_info() # training result from python sklearn (p_weights, p_logloss_train, p_cm_train, p_accuracy_training, p_logloss_test, p_cm_test, p_accuracy_test) = \ self.sklearn_binomial_result(self.training_data_file_enum_nans, self.test_data_file_enum_nans, True, False) # import training set and test set with missing values training_data = h2o.import_file(pyunit_utils.locate(self.training_data_file_enum_nans)) test_data = h2o.import_file(pyunit_utils.locate(self.test_data_file_enum_nans)) # change the categorical data using .asfactor() for ind in range(self.enum_col): training_data[ind] = training_data[ind].round().asfactor() test_data[ind] = test_data[ind].round().asfactor() num_col = training_data.ncol y_index = num_col - 1 x_indices = list(range(y_index)) # change response variables to be categorical training_data[y_index] = training_data[y_index].round().asfactor() # check to make sure all response classes are represented, otherwise, quit if training_data[y_index].nlevels()[0] < self.class_number: print("Response classes are not represented in training dataset.") sys.exit(0) test_data[y_index] = test_data[y_index].round().asfactor() # generate H2O model model_h2o = H2OGeneralizedLinearEstimator(family=self.family, Lambda=0, missing_values_handling="MeanImputation") model_h2o.train(x=x_indices, y=y_index, training_frame=training_data) h2o_model_test_metrics = model_h2o.model_performance(test_data=test_data) num_test_failed = self.test_failed # print out comparison results our H2O GLM with Sklearn model self.test_failed = \ pyunit_utils.extract_comparison_attributes_and_print_multinomial(model_h2o, h2o_model_test_metrics, self.family, "\nTest6 Done!", compare_att_str=[ "\nComparing intercept and " "weights ....", "\nComparing logloss from training" " dataset ....", "\nComparing logloss from test" " dataset ....", "\nComparing confusion matrices from" " training dataset ....", "\nComparing confusion matrices from" " test dataset ...", "\nComparing accuracy from training" " dataset ....", "\nComparing accuracy from test" " dataset ...."], h2o_att_str=[ "H2O with enum/real values, " "no regularization and missing values" " intercept and weights: \n", "H2O with enum/real values, no " "regularization and missing values" " logloss from training dataset: ", "H2O with enum/real values, no" " regularization and missing values" " logloss from test dataset", "H2O with enum/real values, no" " regularization and missing values" " confusion matrix from training" " dataset: \n", "H2O with enum/real values, no" " regularization and missing values" " confusion matrix from test" " dataset: \n", "H2O with enum/real values, no" " regularization and missing values " "accuracy from training dataset: ", "H2O with enum/real values, no " "regularization and missing values" " accuracy from test dataset: "], template_att_str=[ "Sklearn missing values intercept " "and weights: \n", "Sklearn with enum/real values, no" " regularization and missing values" " logloss from training dataset: ", "Sklearn with enum/real values, no " "regularization and missing values" " logloss from test dataset: ", "Sklearn with enum/real values, no " "regularization and missing values " "confusion matrix from training" " dataset: \n", "Sklearn with enum/real values, no " "regularization and missing values " "confusion matrix from test " "dataset: \n", "Sklearn with enum/real values, no " "regularization and missing values " "accuracy from training dataset: ", "Sklearn with enum/real values, no " "regularization and missing values " "accuracy from test dataset: "], att_str_fail=[ "Intercept and weights are not equal!", "Logloss from training dataset differ" " too much!", "Logloss from test dataset differ too" " much!", "", "", "Accuracies from training dataset" " differ too much!", "Accuracies from test dataset differ" " too much!"], att_str_success=[ "Intercept and weights are close" " enough!", "Logloss from training dataset are" " close enough!", "Logloss from test dataset are close" " enough!", "", "", "Accuracies from training dataset are" " close enough!", "Accuracies from test dataset are" " close enough!"], can_be_better_than_template=[ True, True, True, True, True, True, True], just_print=[ True, True, True, True, True, True, False], failed_test_number=self.test_failed, template_params=[ p_weights, p_logloss_train, p_cm_train, p_accuracy_training, p_logloss_test, p_cm_test, p_accuracy_test], ignored_eps=self.ignored_eps, allowed_diff=self.allowed_diff) h2o.cluster_info() # print out test results and update test_failed_array status to reflect if this test has failed self.test_failed_array[self.test_num] += pyunit_utils.show_test_results("test6_enum_missing_values", num_test_failed, self.test_failed) self.test_num += 1 def test7_missing_enum_values_lambda_search(self): """ Test parameter missing_values_handling="MeanImputation" with mixed predictors (categorical/real value columns). Test parameter missing_values_handling="MeanImputation" with mixed predictors (categorical/real value columns) and setting lambda search to be True. We use the same predictors with missing values from test6. Next, we encode the categorical columns using true one hot encoding since Lambda-search will be enabled with alpha set to 0.5. Since the encoding is different in this case from test6, we will build a brand new Sklearn logistic regression model and compare the best H2O model logloss/prediction accuracy with it. """ # perform lambda_search, regularization and one hot encoding. print("*******************************************************************************************") print("Test7: test the GLM with imputation of missing enum/real values under lambda search.") h2o.cluster_info() # training result from python sklearn (p_weights, p_logloss_train, p_cm_train, p_accuracy_training, p_logloss_test, p_cm_test, p_accuracy_test) = \ self.sklearn_binomial_result(self.training_data_file_enum_nans, self.test_data_file_enum_nans_true_one_hot, True, True, validation_data_file=self.validation_data_file_enum_nans_true_one_hot) # import training set and test set with missing values and true one hot encoding training_data = h2o.import_file(pyunit_utils.locate(self.training_data_file_enum_nans_true_one_hot)) validation_data = h2o.import_file(pyunit_utils.locate(self.validation_data_file_enum_nans_true_one_hot)) test_data = h2o.import_file(pyunit_utils.locate(self.test_data_file_enum_nans_true_one_hot)) # change the categorical data using .asfactor() for ind in range(self.enum_col): training_data[ind] = training_data[ind].round().asfactor() validation_data[ind] = validation_data[ind].round().asfactor() test_data[ind] = test_data[ind].round().asfactor() num_col = training_data.ncol y_index = num_col - 1 x_indices = list(range(y_index)) # change response column to be categorical training_data[y_index] = training_data[y_index].round().asfactor() # check to make sure all response classes are represented, otherwise, quit if training_data[y_index].nlevels()[0] < self.class_number: print("Response classes are not represented in training dataset.") sys.exit(0) validation_data[y_index] = validation_data[y_index].round().asfactor() test_data[y_index] = test_data[y_index].round().asfactor() # train H2O model model_h2o_0p5 = H2OGeneralizedLinearEstimator(family=self.family, lambda_search=True, alpha=0.5, lambda_min_ratio=1e-20, missing_values_handling="MeanImputation") model_h2o_0p5.train(x=x_indices, y=y_index, training_frame=training_data, validation_frame=validation_data) h2o_model_0p5_test_metrics = model_h2o_0p5.model_performance(test_data=test_data) num_test_failed = self.test_failed # print out comparison results for our H2O GLM with Sklearn model self.test_failed = \ pyunit_utils.extract_comparison_attributes_and_print_multinomial(model_h2o_0p5, h2o_model_0p5_test_metrics, self.family, "\nTest7 Done!", compare_att_str=[ "\nComparing intercept and " "weights ....", "\nComparing logloss from training" " dataset ....", "\nComparing logloss from test" " dataset ....", "\nComparing confusion matrices from" " training dataset ....", "\nComparing confusion matrices from" " test dataset ...", "\nComparing accuracy from training" " dataset ....", "\nComparing accuracy from test" " dataset ...."], h2o_att_str=[ "H2O with enum/real values, lamba " "search and missing values intercept" " and weights: \n", "H2O with enum/real values, lamba " "search and missing values logloss " "from training dataset: ", "H2O with enum/real values, lamba " "search and missing values logloss " "from test dataset", "H2O with enum/real values, lamba " "search and missing values confusion " "matrix from training dataset: \n", "H2O with enum/real values, lamba " "search and missing values confusion " "matrix from test dataset: \n", "H2O with enum/real values, lamba " "search and missing values accuracy " "from training dataset: ", "H2O with enum/real values, lamba " "search and missing values accuracy " "from test dataset: "], template_att_str=[ "Sklearn with enum/real values, lamba" " search and missing values intercept" " and weights: \n", "Sklearn with enum/real values, lamba" " search and missing values logloss " "from training dataset: ", "Sklearn with enum/real values, lamba" " search and missing values logloss " "from test dataset: ", "Sklearn with enum/real values, lamba" " search and missing values confusion" " matrix from training dataset: \n", "Sklearn with enum/real values, lamba" " search and missing values confusion" " matrix from test dataset: \n", "Sklearn with enum/real values, lamba" " search and missing values accuracy" " from training dataset: ", "Sklearn with enum/real values, lamba" " search and missing values accuracy" " from test dataset: "], att_str_fail=[ "Intercept and weights are not equal!", "Logloss from training dataset differ " "too much!", "Logloss from test dataset differ too" " much!", "", "", "Accuracies from" " training dataset differ too much!", "Accuracies from test dataset differ" " too much!"], att_str_success=[ "Intercept and weights are close " "enough!", "Logloss from training dataset are" " close enough!", "Logloss from test dataset are close" " enough!", "", "", "Accuracies from training dataset are" " close enough!", "Accuracies from test dataset are" " close enough!"], can_be_better_than_template=[ True, True, True, True, True, True, True], just_print=[ True, True, True, True, True, True, False], failed_test_number=self.test_failed, template_params=[ p_weights, p_logloss_train, p_cm_train, p_accuracy_training, p_logloss_test, p_cm_test, p_accuracy_test], ignored_eps=self.ignored_eps, allowed_diff=self.allowed_diff) # print out test results and update test_failed_array status to reflect if this test has failed self.test_failed_array[self.test_num] += \ pyunit_utils.show_test_results("test7_missing_enum_values_lambda_search", num_test_failed, self.test_failed) self.test_num += 1 def sklearn_binomial_result(self, training_data_file, test_data_file, has_categorical, true_one_hot, validation_data_file=""): """ This function will generate a Sklearn logistic model using the same set of data sets we have used to build our H2O models. The purpose here is to be able to compare the performance of H2O models with the Sklearn model built here. This is useful in cases where theoretical solutions do not exist. If the data contains missing values, mean imputation is applied to the data set before a Sklearn model is built. In addition, if there are enum columns in predictors and also missing values, the same encoding and missing value imputation method used by H2O is applied to the data set before we build the Sklearn model. :param training_data_file: string storing training data set filename with directory path. :param test_data_file: string storing test data set filename with directory path. :param has_categorical: bool indicating if we data set contains mixed predictors (both enum and real) :param true_one_hot: bool True: true one hot encoding is used. False: reference level plus one hot encoding is used :param validation_data_file: optional string, denoting validation file so that we can concatenate training and validation data sets into a big training set since H2O model is using a training and a validation data set. :return: a tuple containing the weights, logloss, confusion matrix, prediction accuracy calculated on training data set and test data set respectively. """ # read in the training data into a matrix training_data_xy = np.asmatrix(np.genfromtxt(training_data_file, delimiter=',', dtype=None)) test_data_xy = np.asmatrix(np.genfromtxt(test_data_file, delimiter=',', dtype=None)) if len(validation_data_file) > 0: # validation data set exist and add it to training_data temp_data_xy = np.asmatrix(np.genfromtxt(validation_data_file, delimiter=',', dtype=None)) training_data_xy = np.concatenate((training_data_xy, temp_data_xy), axis=0) # if predictor contains categorical data, perform encoding of enums to binary bits # for missing categorical enums, a new level is created for the nans if has_categorical: training_data_xy = pyunit_utils.encode_enum_dataset(training_data_xy, self.enum_level_vec, self.enum_col, true_one_hot, np.any(training_data_xy)) test_data_xy = pyunit_utils.encode_enum_dataset(test_data_xy, self.enum_level_vec, self.enum_col, true_one_hot, np.any(training_data_xy)) # replace missing values for real value columns with column mean before proceeding for training/test data sets if np.isnan(training_data_xy).any(): inds = np.where(np.isnan(training_data_xy)) col_means = np.asarray(np.nanmean(training_data_xy, axis=0))[0] training_data_xy[inds] = np.take(col_means, inds[1]) if np.isnan(test_data_xy).any(): # replace the actual means with column means from training inds = np.where(np.isnan(test_data_xy)) test_data_xy = pyunit_utils.replace_nan_with_mean(test_data_xy, inds, col_means) # now data is ready to be massaged into format that sklearn can use (response_y, x_mat) = pyunit_utils.prepare_data_sklearn_multinomial(training_data_xy) (t_response_y, t_x_mat) = pyunit_utils.prepare_data_sklearn_multinomial(test_data_xy) # train the sklearn Model sklearn_model = LogisticRegression(class_weight=self.sklearn_class_weight) sklearn_model = sklearn_model.fit(x_mat, response_y) # grab the performance metrics on training data set accuracy_training = sklearn_model.score(x_mat, response_y) weights = sklearn_model.coef_ p_response_y = sklearn_model.predict(x_mat) log_prob = sklearn_model.predict_log_proba(x_mat) logloss_training = self.logloss_sklearn(response_y, log_prob) cm_train = metrics.confusion_matrix(response_y, p_response_y) # grab the performance metrics on the test data set p_response_y = sklearn_model.predict(t_x_mat) log_prob = sklearn_model.predict_log_proba(t_x_mat) logloss_test = self.logloss_sklearn(t_response_y, log_prob) cm_test = metrics.confusion_matrix(t_response_y, p_response_y) accuracy_test = metrics.accuracy_score(t_response_y, p_response_y) return weights, logloss_training, cm_train, accuracy_training, logloss_test, cm_test, accuracy_test def logloss_sklearn(self, true_y, log_prob): """ This function calculate the average logloss for SKlean model given the true response (trueY) and the log probabilities (logProb). :param true_y: array denoting the true class label :param log_prob: matrix containing the log of Prob(Y=0) and Prob(Y=1) :return: average logloss. """ (num_row, num_class) = log_prob.shape logloss = 0.0 for ind in range(num_row): logloss += log_prob[ind, int(true_y[ind])] return -1.0 * logloss / num_row def test_glm_binomial(): """ Create and instantiate TestGLMBinomial class and perform tests specified for GLM Binomial family. :return: None """ test_glm_binomial = TestGLMBinomial() test_glm_binomial.test1_glm_no_regularization() test_glm_binomial.test2_glm_lambda_search() test_glm_binomial.test3_glm_grid_search() test_glm_binomial.test4_glm_remove_collinear_columns() test_glm_binomial.test5_missing_values() test_glm_binomial.test6_enum_missing_values() test_glm_binomial.test7_missing_enum_values_lambda_search() test_glm_binomial.teardown() sys.stdout.flush() if test_glm_binomial.test_failed: # exit with error if any tests have failed sys.exit(1) if __name__ == "__main__": pyunit_utils.standalone_test(test_glm_binomial) else: test_glm_binomial()
apache-2.0
Titan-C/scikit-learn
sklearn/datasets/tests/test_kddcup99.py
42
1278
"""Test kddcup99 loader. Only 'percent10' mode is tested, as the full data is too big to use in unit-testing. The test is skipped if the data wasn't previously fetched and saved to scikit-learn data folder. """ from sklearn.datasets import fetch_kddcup99 from sklearn.utils.testing import assert_equal, SkipTest def test_percent10(): try: data = fetch_kddcup99(download_if_missing=False) except IOError: raise SkipTest("kddcup99 dataset can not be loaded.") assert_equal(data.data.shape, (494021, 41)) assert_equal(data.target.shape, (494021,)) data_shuffled = fetch_kddcup99(shuffle=True, random_state=0) assert_equal(data.data.shape, data_shuffled.data.shape) assert_equal(data.target.shape, data_shuffled.target.shape) data = fetch_kddcup99('SA') assert_equal(data.data.shape, (100655, 41)) assert_equal(data.target.shape, (100655,)) data = fetch_kddcup99('SF') assert_equal(data.data.shape, (73237, 4)) assert_equal(data.target.shape, (73237,)) data = fetch_kddcup99('http') assert_equal(data.data.shape, (58725, 3)) assert_equal(data.target.shape, (58725,)) data = fetch_kddcup99('smtp') assert_equal(data.data.shape, (9571, 3)) assert_equal(data.target.shape, (9571,))
bsd-3-clause
vigilv/scikit-learn
sklearn/feature_extraction/tests/test_dict_vectorizer.py
276
3790
# Authors: Lars Buitinck <[email protected]> # Dan Blanchard <[email protected]> # License: BSD 3 clause from random import Random import numpy as np import scipy.sparse as sp from numpy.testing import assert_array_equal from sklearn.utils.testing import (assert_equal, assert_in, assert_false, assert_true) from sklearn.feature_extraction import DictVectorizer from sklearn.feature_selection import SelectKBest, chi2 def test_dictvectorizer(): D = [{"foo": 1, "bar": 3}, {"bar": 4, "baz": 2}, {"bar": 1, "quux": 1, "quuux": 2}] for sparse in (True, False): for dtype in (int, np.float32, np.int16): for sort in (True, False): for iterable in (True, False): v = DictVectorizer(sparse=sparse, dtype=dtype, sort=sort) X = v.fit_transform(iter(D) if iterable else D) assert_equal(sp.issparse(X), sparse) assert_equal(X.shape, (3, 5)) assert_equal(X.sum(), 14) assert_equal(v.inverse_transform(X), D) if sparse: # CSR matrices can't be compared for equality assert_array_equal(X.A, v.transform(iter(D) if iterable else D).A) else: assert_array_equal(X, v.transform(iter(D) if iterable else D)) if sort: assert_equal(v.feature_names_, sorted(v.feature_names_)) def test_feature_selection(): # make two feature dicts with two useful features and a bunch of useless # ones, in terms of chi2 d1 = dict([("useless%d" % i, 10) for i in range(20)], useful1=1, useful2=20) d2 = dict([("useless%d" % i, 10) for i in range(20)], useful1=20, useful2=1) for indices in (True, False): v = DictVectorizer().fit([d1, d2]) X = v.transform([d1, d2]) sel = SelectKBest(chi2, k=2).fit(X, [0, 1]) v.restrict(sel.get_support(indices=indices), indices=indices) assert_equal(v.get_feature_names(), ["useful1", "useful2"]) def test_one_of_k(): D_in = [{"version": "1", "ham": 2}, {"version": "2", "spam": .3}, {"version=3": True, "spam": -1}] v = DictVectorizer() X = v.fit_transform(D_in) assert_equal(X.shape, (3, 5)) D_out = v.inverse_transform(X) assert_equal(D_out[0], {"version=1": 1, "ham": 2}) names = v.get_feature_names() assert_true("version=2" in names) assert_false("version" in names) def test_unseen_or_no_features(): D = [{"camelot": 0, "spamalot": 1}] for sparse in [True, False]: v = DictVectorizer(sparse=sparse).fit(D) X = v.transform({"push the pram a lot": 2}) if sparse: X = X.toarray() assert_array_equal(X, np.zeros((1, 2))) X = v.transform({}) if sparse: X = X.toarray() assert_array_equal(X, np.zeros((1, 2))) try: v.transform([]) except ValueError as e: assert_in("empty", str(e)) def test_deterministic_vocabulary(): # Generate equal dictionaries with different memory layouts items = [("%03d" % i, i) for i in range(1000)] rng = Random(42) d_sorted = dict(items) rng.shuffle(items) d_shuffled = dict(items) # check that the memory layout does not impact the resulting vocabulary v_1 = DictVectorizer().fit([d_sorted]) v_2 = DictVectorizer().fit([d_shuffled]) assert_equal(v_1.vocabulary_, v_2.vocabulary_)
bsd-3-clause
KennyCandy/HAR
_module123/C_64_32.py
1
17396
# Note that the dataset must be already downloaded for this script to work, do: # $ cd data/ # $ python download_dataset.py # quoc_trinh import tensorflow as tf import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn import metrics import os import sys import datetime # get current file_name as [0] of array file_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] print(" File Name:") print(file_name) print("") # FLAG to know that whether this is traning process or not. FLAG = 'train' N_HIDDEN_CONFIG = 32 save_path_name = file_name + "/model.ckpt" print(datetime.datetime.now()) # Write to file: time to start, type, time to end f = open(file_name + '/time.txt', 'a+') f.write("------------- \n") f.write("This is time \n") f.write("Started at \n") f.write(str(datetime.datetime.now())+'\n') if __name__ == "__main__": # ----------------------------- # step1: load and prepare data # ----------------------------- # Those are separate normalised input features for the neural network INPUT_SIGNAL_TYPES = [ "body_acc_x_", "body_acc_y_", "body_acc_z_", "body_gyro_x_", "body_gyro_y_", "body_gyro_z_", "total_acc_x_", "total_acc_y_", "total_acc_z_" ] # Output classes to learn how to classify LABELS = [ "WALKING", "WALKING_UPSTAIRS", "WALKING_DOWNSTAIRS", "SITTING", "STANDING", "LAYING" ] DATA_PATH = "../data/" DATASET_PATH = DATA_PATH + "UCI HAR Dataset/" print("\n" + "Dataset is now located at: " + DATASET_PATH) # Preparing data set: TRAIN = "train/" TEST = "test/" # Load "X" (the neural network's training and testing inputs) def load_X(X_signals_paths): X_signals = [] for signal_type_path in X_signals_paths: file = open(signal_type_path, 'rb') # Read dataset from disk, dealing with text files' syntax X_signals.append( [np.array(serie, dtype=np.float32) for serie in [ row.replace(' ', ' ').strip().split(' ') for row in file ]] ) file.close() """Examples -------- >> > x = np.arange(4).reshape((2, 2)) >> > x array([[0, 1], [2, 3]]) >> > np.transpose(x) array([[0, 2], [1, 3]]) >> > x = np.ones((1, 2, 3)) >> > np.transpose(x, (1, 0, 2)).shape (2, 1, 3) """ return np.transpose(np.array(X_signals), (1, 2, 0)) X_train_signals_paths = [ DATASET_PATH + TRAIN + "Inertial Signals/" + signal + "train.txt" for signal in INPUT_SIGNAL_TYPES ] X_test_signals_paths = [ DATASET_PATH + TEST + "Inertial Signals/" + signal + "test.txt" for signal in INPUT_SIGNAL_TYPES ] X_train = load_X(X_train_signals_paths) # [7352, 128, 9] X_test = load_X(X_test_signals_paths) # [7352, 128, 9] # print(X_train) print(len(X_train)) # 7352 print(len(X_train[0])) # 128 print(len(X_train[0][0])) # 9 print(type(X_train)) X_train = np.reshape(X_train, [-1, 32, 36]) X_test = np.reshape(X_test, [-1, 32, 36]) print("-----------------X_train---------------") # print(X_train) print(len(X_train)) # 7352 print(len(X_train[0])) # 32 print(len(X_train[0][0])) # 36 print(type(X_train)) # exit() y_train_path = DATASET_PATH + TRAIN + "y_train.txt" y_test_path = DATASET_PATH + TEST + "y_test.txt" def one_hot(label): """convert label from dense to one hot argument: label: ndarray dense label ,shape: [sample_num,1] return: one_hot_label: ndarray one hot, shape: [sample_num,n_class] """ label_num = len(label) new_label = label.reshape(label_num) # shape : [sample_num] # because max is 5, and we will create 6 columns n_values = np.max(new_label) + 1 return np.eye(n_values)[np.array(new_label, dtype=np.int32)] # Load "y" (the neural network's training and testing outputs) def load_y(y_path): file = open(y_path, 'rb') # Read dataset from disk, dealing with text file's syntax y_ = np.array( [elem for elem in [ row.replace(' ', ' ').strip().split(' ') for row in file ]], dtype=np.int32 ) file.close() # Subtract 1 to each output class for friendly 0-based indexing return y_ - 1 y_train = one_hot(load_y(y_train_path)) y_test = one_hot(load_y(y_test_path)) print("---------y_train----------") # print(y_train) print(len(y_train)) # 7352 print(len(y_train[0])) # 6 # ----------------------------------- # step2: define parameters for model # ----------------------------------- class Config(object): """ define a class to store parameters, the input should be feature mat of training and testing """ def __init__(self, X_train, X_test): # Input data self.train_count = len(X_train) # 7352 training series self.test_data_count = len(X_test) # 2947 testing series self.n_steps = len(X_train[0]) # 128 time_steps per series # Training self.learning_rate = 0.0025 self.lambda_loss_amount = 0.0015 self.training_epochs = 300 self.batch_size = 1000 # LSTM structure self.n_inputs = len(X_train[0][0]) # Features count is of 9: three 3D sensors features over time self.n_hidden = N_HIDDEN_CONFIG # nb of neurons inside the neural network self.n_classes = 6 # Final output classes self.W = { 'hidden': tf.Variable(tf.random_normal([self.n_inputs, self.n_hidden])), # [9, 32] 'output': tf.Variable(tf.random_normal([self.n_hidden, self.n_classes])) # [32, 6] } self.biases = { 'hidden': tf.Variable(tf.random_normal([self.n_hidden], mean=1.0)), # [32] 'output': tf.Variable(tf.random_normal([self.n_classes])) # [6] } config = Config(X_train, X_test) # print("Some useful info to get an insight on dataset's shape and normalisation:") # print("features shape, labels shape, each features mean, each features standard deviation") # print(X_test.shape, y_test.shape, # np.mean(X_test), np.std(X_test)) # print("the dataset is therefore properly normalised, as expected.") # # # ------------------------------------------------------ # step3: Let's get serious and build the neural network # ------------------------------------------------------ # [none, 128, 9] X = tf.placeholder(tf.float32, [None, config.n_steps, config.n_inputs]) # [none, 6] Y = tf.placeholder(tf.float32, [None, config.n_classes]) print("-------X Y----------") print(X) X = tf.reshape(X, shape=[-1, 32, 36]) print(X) print(Y) Y = tf.reshape(Y, shape=[-1, 6]) print(Y) # Weight Initialization def weight_variable(shape): # tra ve 1 gia tri random theo thuat toan truncated_ normal initial = tf.truncated_normal(shape, mean=0.0, stddev=0.1, dtype=tf.float32) return tf.Variable(initial) def bias_varibale(shape): initial = tf.constant(0.1, shape=shape, name='Bias') return tf.Variable(initial) # Convolution and Pooling def conv2d(x, W): # Must have `strides[0] = strides[3] = 1 `. # For the most common case of the same horizontal and vertices strides, `strides = [1, stride, stride, 1] `. return tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME', name='conv_2d') def max_pool_2x2(x): return tf.nn.max_pool(value=x, ksize=[1, 2, 2, 1], strides=[1, 1, 1, 1], padding='SAME', name='max_pool') def LSTM_Network(feature_mat, config): """model a LSTM Network, it stacks 2 LSTM layers, each layer has n_hidden=32 cells and 1 output layer, it is a full connet layer argument: feature_mat: ndarray feature matrix, shape=[batch_size,time_steps,n_inputs] config: class containing config of network return: : matrix output shape [batch_size,n_classes] """ W_conv1 = weight_variable([3, 3, 1, 64]) b_conv1 = bias_varibale([64]) # x_image = tf.reshape(x, shape=[-1, 28, 28, 1]) feature_mat_image = tf.reshape(feature_mat, shape=[-1, 32, 36, 1]) print("----feature_mat_image-----") print(feature_mat_image.get_shape()) h_conv1 = tf.nn.relu(conv2d(feature_mat_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # Second Convolutional Layer W_conv2 = weight_variable([3, 3, 64, 1]) b_conv2 = weight_variable([1]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = h_conv2 h_pool2 = tf.reshape(h_pool2, shape=[-1, 32, 36]) feature_mat = h_pool2 print("----feature_mat-----") print(feature_mat) # exit() # W_fc1 = weight_variable([8 * 9 * 1, 1024]) # b_fc1 = bias_varibale([1024]) # h_pool2_flat = tf.reshape(h_pool2, [-1, 8 * 9 * 1]) # h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # print("----h_fc1_drop-----") # print(h_fc1) # exit() # # # keep_prob = tf.placeholder(tf.float32) # keep_prob = tf.placeholder(1.0) # h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob=keep_prob) # print("----h_fc1_drop-----") # print(h_fc1_drop) # exit() # # W_fc2 = weight_variable([1024, 10]) # b_fc2 = bias_varibale([10]) # # y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 # print("----y_conv-----") # print(y_conv) # exit() # Exchange dim 1 and dim 0 # Start at: [0,1,2] = [batch_size, 128, 9] => [batch_size, 32, 36] feature_mat = tf.transpose(feature_mat, [1, 0, 2]) # New feature_mat's shape: [time_steps, batch_size, n_inputs] [128, batch_size, 9] print("----feature_mat-----") print(feature_mat) # exit() # Temporarily crush the feature_mat's dimensions feature_mat = tf.reshape(feature_mat, [-1, config.n_inputs]) # 9 # New feature_mat's shape: [time_steps*batch_size, n_inputs] # 128 * batch_size, 9 # Linear activation, reshaping inputs to the LSTM's number of hidden: hidden = tf.nn.relu(tf.matmul( feature_mat, config.W['hidden'] ) + config.biases['hidden']) # New feature_mat (hidden) shape: [time_steps*batch_size, n_hidden] [128*batch_size, 32] print("--n_steps--") print(config.n_steps) print("--hidden--") print(hidden) # Split the series because the rnn cell needs time_steps features, each of shape: hidden = tf.split(0, config.n_steps, hidden) # (0, 128, [128*batch_size, 32]) # New hidden's shape: a list of length "time_step" containing tensors of shape [batch_size, n_hidden] # Define LSTM cell of first hidden layer: lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(config.n_hidden, forget_bias=1.0) # Stack two LSTM layers, both layers has the same shape lsmt_layers = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * 2) # Get LSTM outputs, the states are internal to the LSTM cells,they are not our attention here outputs, _ = tf.nn.rnn(lsmt_layers, hidden, dtype=tf.float32) # outputs' shape: a list of lenght "time_step" containing tensors of shape [batch_size, n_hidden] print("------------------list-------------------") print(outputs) # Get last time step's output feature for a "many to one" style classifier, # as in the image describing RNNs at the top of this page lstm_last_output = outputs[-1] # Get the last element of the array: [?, 32] print("------------------last outputs-------------------") print (lstm_last_output) # Linear activation return tf.matmul(lstm_last_output, config.W['output']) + config.biases['output'] pred_Y = LSTM_Network(X, config) # shape[?,6] print("------------------pred_Y-------------------") print(pred_Y) # Loss,train_step,evaluation l2 = config.lambda_loss_amount * \ sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()) # Softmax loss and L2 cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(pred_Y, Y)) + l2 train_step = tf.train.AdamOptimizer( learning_rate=config.learning_rate).minimize(cost) correct_prediction = tf.equal(tf.argmax(pred_Y, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32)) # -------------------------------------------- # step4: Hooray, now train the neural network # -------------------------------------------- # Note that log_device_placement can be turned ON but will cause console spam. # Initializing the variables init = tf.initialize_all_variables() # Add ops to save and restore all the variables. saver = tf.train.Saver() best_accuracy = 0.0 # sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=False)) if (FLAG == 'train') : # If it is the training mode with tf.Session() as sess: # tf.initialize_all_variables().run() sess.run(init) # .run() f.write("---Save model \n") # Start training for each batch and loop epochs for i in range(config.training_epochs): for start, end in zip(range(0, config.train_count, config.batch_size), # (0, 7352, 1500) range(config.batch_size, config.train_count + 1, config.batch_size)): # (1500, 7353, 1500) print(start) print(end) sess.run(train_step, feed_dict={X: X_train[start:end], Y: y_train[start:end]}) # Test completely at every epoch: calculate accuracy pred_out, accuracy_out, loss_out = sess.run([pred_Y, accuracy, cost], feed_dict={ X: X_test, Y: y_test}) print("traing iter: {},".format(i) + \ " test accuracy : {},".format(accuracy_out) + \ " loss : {}".format(loss_out)) best_accuracy = max(best_accuracy, accuracy_out) # Save the model in this session save_path = saver.save(sess, file_name + "/model.ckpt") print("Model saved in file: %s" % save_path) print("") print("final loss: {}").format(loss_out) print("final test accuracy: {}".format(accuracy_out)) print("best epoch's test accuracy: {}".format(best_accuracy)) print("") # Write all output to file f.write("final loss:" + str(format(loss_out)) +" \n") f.write("final test accuracy:" + str(format(accuracy_out)) +" \n") f.write("best epoch's test accuracy:" + str(format(best_accuracy)) + " \n") else : # Running a new session print("Starting 2nd session...") with tf.Session() as sess: # Initialize variables sess.run(init) f.write("---Restore model \n") # Restore model weights from previously saved model saver.restore(sess, file_name+ "/model.ckpt") print("Model restored from file: %s" % save_path_name) # Test completely at every epoch: calculate accuracy pred_out, accuracy_out, loss_out = sess.run([pred_Y, accuracy, cost], feed_dict={ X: X_test, Y: y_test}) # print("traing iter: {}," + \ # " test accuracy : {},".format(accuracy_out) + \ # " loss : {}".format(loss_out)) best_accuracy = max(best_accuracy, accuracy_out) print("") print("final loss: {}").format(loss_out) print("final test accuracy: {}".format(accuracy_out)) print("best epoch's test accuracy: {}".format(best_accuracy)) print("") # Write all output to file f.write("final loss:" + str(format(loss_out)) +" \n") f.write("final test accuracy:" + str(format(accuracy_out)) +" \n") f.write("best epoch's test accuracy:" + str(format(best_accuracy)) + " \n") # # #------------------------------------------------------------------ # # step5: Training is good, but having visual insight is even better # #------------------------------------------------------------------ # # The code is in the .ipynb # # #------------------------------------------------------------------ # # step6: And finally, the multi-class confusion matrix and metrics! # #------------------------------------------------------------------ # # The code is in the .ipynb f.write("Ended at \n") f.write(str(datetime.datetime.now())+'\n') f.write("------------- \n") f.close()
mit
jaidevd/scikit-learn
examples/svm/plot_svm_nonlinear.py
268
1091
""" ============== Non-linear SVM ============== Perform binary classification using non-linear SVC with RBF kernel. The target to predict is a XOR of the inputs. The color map illustrates the decision function learned by the SVC. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm xx, yy = np.meshgrid(np.linspace(-3, 3, 500), np.linspace(-3, 3, 500)) np.random.seed(0) X = np.random.randn(300, 2) Y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0) # fit the model clf = svm.NuSVC() clf.fit(X, Y) # plot the decision function for each datapoint on the grid Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.imshow(Z, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto', origin='lower', cmap=plt.cm.PuOr_r) contours = plt.contour(xx, yy, Z, levels=[0], linewidths=2, linetypes='--') plt.scatter(X[:, 0], X[:, 1], s=30, c=Y, cmap=plt.cm.Paired) plt.xticks(()) plt.yticks(()) plt.axis([-3, 3, -3, 3]) plt.show()
bsd-3-clause
saiwing-yeung/scikit-learn
examples/linear_model/lasso_dense_vs_sparse_data.py
348
1862
""" ============================== Lasso on dense and sparse data ============================== We show that linear_model.Lasso provides the same results for dense and sparse data and that in the case of sparse data the speed is improved. """ print(__doc__) from time import time from scipy import sparse from scipy import linalg from sklearn.datasets.samples_generator import make_regression from sklearn.linear_model import Lasso ############################################################################### # The two Lasso implementations on Dense data print("--- Dense matrices") X, y = make_regression(n_samples=200, n_features=5000, random_state=0) X_sp = sparse.coo_matrix(X) alpha = 1 sparse_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=1000) dense_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=1000) t0 = time() sparse_lasso.fit(X_sp, y) print("Sparse Lasso done in %fs" % (time() - t0)) t0 = time() dense_lasso.fit(X, y) print("Dense Lasso done in %fs" % (time() - t0)) print("Distance between coefficients : %s" % linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_)) ############################################################################### # The two Lasso implementations on Sparse data print("--- Sparse matrices") Xs = X.copy() Xs[Xs < 2.5] = 0.0 Xs = sparse.coo_matrix(Xs) Xs = Xs.tocsc() print("Matrix density : %s %%" % (Xs.nnz / float(X.size) * 100)) alpha = 0.1 sparse_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=10000) dense_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=10000) t0 = time() sparse_lasso.fit(Xs, y) print("Sparse Lasso done in %fs" % (time() - t0)) t0 = time() dense_lasso.fit(Xs.toarray(), y) print("Dense Lasso done in %fs" % (time() - t0)) print("Distance between coefficients : %s" % linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_))
bsd-3-clause
jdwittenauer/ionyx
ionyx/experiment.py
1
19762
import pickle import time import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import get_scorer from sklearn.model_selection import GridSearchCV, RandomizedSearchCV from sklearn.model_selection import cross_validate, learning_curve, train_test_split from .print_message import PrintMessageMixin class Experiment(PrintMessageMixin): """ Provides functionality to create and run machine learning experiments. Designed to serve as a "wrapper" for running an experiment. This class provides methods for training, cross-validation, parameter tuning etc. The main value proposition is in providing a simplified API for common tasks, layering useful reporting and logging on top, and reconciling capabilities between several popular libraries. Parameters ---------- package : {'sklearn', 'xgboost', 'keras', 'prophet'} The source package of the model used in the experiment. Some capabilities are available only using certain packages. model : object An instantiated supervised learning model. Must be API compatible with scikit-learn estimators. Pipelines are also supported. scoring_metric : string Name of the metric to use to score models. Text must match a valid scikit-learn metric. eval_metric : string, optional, default None Separate metric used specifically for evaluation such as hold-out sets during training. Text must match an evaluation metric supported by the package the model originates from. n_jobs : int, optional, default 1 Number of parallel processes to use (where functionality is available). verbose : boolean, optional, default True If true, messages will be written to the console. logger : object, optional, default None An instantiated log writer with an open file handle. If provided, messages will be written to the log file. data : DataFrame, optional, default None The data set to be used for the experiment. Provides the option to specify the data at initialization vs. passing in training data and labels with each function call. If "data" is specified then "X_columns" and "y_column" must also be specified. X_columns : list, optional, default None List of columns in "data" to use for the training set. y_column : string, optional, default None Name of the column in "data" to use as a label for supervised learning. cv : object, optional, default None A cross-validation strategy. Accepts all options considered valid by scikit-learn. Attributes ---------- scorer_ : object Scikit-learn scoring function for the provided scoring metric. best_model_ : object The best model found during a parameter search. """ def __init__(self, package, model, scoring_metric, eval_metric=None, n_jobs=1, verbose=True, logger=None, data=None, X_columns=None, y_column=None, cv=None): PrintMessageMixin.__init__(self, verbose, logger) self.package = package self.model = model self.scoring_metric = scoring_metric self.eval_metric = eval_metric self.n_jobs = n_jobs self.scorer_ = get_scorer(self.scoring_metric) self.best_model_ = None self.data = data if self.data is not None: if X_columns and y_column: self.X = data[X_columns].values self.y = data[y_column].values else: raise Exception('X and y columns must be specified if data set is provided.') self.cv = cv self.print_message('Beginning experiment...') self.print_message('Package = {0}'.format(package)) self.print_message('Scoring Metric = {0}'.format(scoring_metric)) self.print_message('Evaluation Metric = {0}'.format(eval_metric)) self.print_message('Parallel Jobs = {0}'.format(n_jobs)) self.print_message('Model:') self.print_message(model, pprint=True) self.print_message('Parameters:') self.print_message(model.get_params(), pprint=True) def train_model(self, X=None, y=None, validate=False, early_stopping=False, early_stopping_rounds=None, plot_eval_history=False, fig_size=16): """ Trains a new model using the provided training data. Parameters ---------- X : array-like, optional, default None Training input samples. Must be specified if no data was provided during initialization. y : array-like, optional, default None Target values. Must be specified if no data was provided during initialization. validate : boolean, optional, default False Evaluate model on a hold-out set during training. early_stopping : boolean, optional, default False Stop training the model when performance on a validation set begins to drop. Eval must be enabled. early_stopping_rounds : int, optional, default None Number of training iterations to allow before stopping training due to performance on a validation set. Eval and early_stopping must be enabled. plot_eval_history : boolean, optional, default False Plot model performance as a function of training time. Eval must be enabled. fig_size : int, optional, default 16 Size of the evaluation history plot. """ if X is not None: self.X = X if y is not None: self.y = y self.print_message('Beginning model training...') self.print_message('X dimensions = {0}'.format(self.X.shape)) self.print_message('y dimensions = {0}'.format(self.y.shape)) v = 1 if self.verbose else 0 t0 = time.time() if self.package not in ['sklearn', 'xgboost', 'keras', 'prophet']: raise Exception('Package not supported.') if validate and self.package in ['xgboost', 'keras']: X_train, X_eval, y_train, y_eval = train_test_split(self.X, self.y, test_size=0.1) training_history = None min_eval_loss = None min_eval_epoch = None if early_stopping: if self.package == 'xgboost': self.model.fit(X_train, y_train, eval_set=[(X_eval, y_eval)], eval_metric=self.eval_metric, early_stopping_rounds=early_stopping_rounds, verbose=self.verbose) elif self.package == 'keras': from keras.callbacks import EarlyStopping callbacks = [ EarlyStopping(monitor='val_loss', patience=early_stopping_rounds) ] training_history = self.model.fit(X_train, y_train, verbose=v, validation_data=(X_eval, y_eval), callbacks=callbacks) else: if self.package == 'xgboost': self.model.fit(X_train, y_train, eval_set=[(X_eval, y_eval)], eval_metric=self.eval_metric, verbose=self.verbose) elif self.package == 'keras': training_history = self.model.fit(X_train, y_train, verbose=v, validation_data=(X_eval, y_eval)) if self.package == 'xgboost': training_history = self.model.evals_result()['validation_0'][self.eval_metric] min_eval_loss = min(training_history) min_eval_epoch = training_history.index(min(training_history)) + 1 elif self.package == 'keras': training_history = training_history.history['val_loss'] min_eval_loss = min(training_history) min_eval_epoch = training_history.index(min(training_history)) + 1 if plot_eval_history: df = pd.DataFrame(training_history, columns=['Eval Loss']) df.plot(figsize=(fig_size, fig_size * 3 / 4)) t1 = time.time() self.print_message('Model training complete in {0:3f} s.'.format(t1 - t0)) self.print_message('Training score = {0}' .format(self.scorer_(self.model, X_train, y_train))) self.print_message('Min. evaluation score = {0}'.format(min_eval_loss)) self.print_message('Min. evaluation epoch = {0}'.format(min_eval_epoch)) elif validate: raise Exception('Package does not support evaluation during training.') else: if self.package == 'keras': self.model.set_params(verbose=v) self.model.fit(self.X, self.y) t1 = time.time() self.print_message('Model training complete in {0:3f} s.'.format(t1 - t0)) self.print_message('Training score = {0}' .format(self.scorer_(self.model, self.X, self.y))) def cross_validate(self, X=None, y=None, cv=None): """ Performs cross-validation to estimate the true performance of the model. Parameters ---------- X : array-like, optional, default None Training input samples. Must be specified if no data was provided during initialization. y : array-like, optional, default None Target values. Must be specified if no data was provided during initialization. cv : object, optional, default None A cross-validation strategy. Accepts all options considered valid by scikit-learn. Must be specified if no cv was passed in during initialization. """ if X is not None: self.X = X if y is not None: self.y = y if cv is not None: self.cv = cv self.print_message('Beginning cross-validation...') self.print_message('X dimensions = {0}'.format(self.X.shape)) self.print_message('y dimensions = {0}'.format(self.y.shape)) self.print_message('Cross-validation strategy = {0}'.format(self.cv)) t0 = time.time() if self.package not in ['sklearn', 'xgboost', 'keras', 'prophet']: raise Exception('Package not supported.') if self.package == 'keras': self.model.set_params(verbose=0) results = cross_validate(self.model, self.X, self.y, scoring=self.scoring_metric, cv=self.cv, n_jobs=self.n_jobs, verbose=0, return_train_score=True) t1 = time.time() self.print_message('Cross-validation complete in {0:3f} s.'.format(t1 - t0)) train_score = np.mean(results['train_score']) test_score = np.mean(results['test_score']) self.print_message('Training score = {0}'.format(train_score)) self.print_message('Cross-validation score = {0}'.format(test_score)) def learning_curve(self, X=None, y=None, cv=None, fig_size=16): """ Plots a learning curve showing model performance against both training and validation data sets as a function of the number of training samples. Parameters ---------- X : array-like, optional, default None Training input samples. Must be specified if no data was provided during initialization. y : array-like, optional, default None Target values. Must be specified if no data was provided during initialization. cv : object, optional, default None A cross-validation strategy. Accepts all options considered valid by scikit-learn. Must be specified if no cv was passed in during initialization. fig_size : int, optional, default 16 Size of the plot. """ if X is not None: self.X = X if y is not None: self.y = y if cv is not None: self.cv = cv self.print_message('Plotting learning curve...') self.print_message('X dimensions = {0}'.format(self.X.shape)) self.print_message('y dimensions = {0}'.format(self.y.shape)) self.print_message('Cross-validation strategy = {0}'.format(self.cv)) t0 = time.time() if self.package not in ['sklearn', 'xgboost', 'keras', 'prophet']: raise Exception('Package not supported.') if self.package == 'keras': self.model.set_params(verbose=0) values = learning_curve(self.model, self.X, self.y, cv=self.cv, scoring=self.scoring_metric, n_jobs=self.n_jobs, verbose=0) train_sizes, train_scores, test_scores = values train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) fig, ax = plt.subplots(figsize=(fig_size, fig_size * 3 / 4)) ax.set_title('Learning Curve') ax.set_xlabel('Training Examples') ax.set_ylabel('Score') ax.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color='b') ax.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color='r') ax.plot(train_sizes, train_scores_mean, 'o-', color='b', label='Training score') ax.plot(train_sizes, test_scores_mean, 'o-', color='r', label='Cross-validation score') ax.legend(loc='best') fig.tight_layout() t1 = time.time() self.print_message('Plot generation complete in {0:3f} s.'.format(t1 - t0)) def param_search(self, param_grid, X=None, y=None, cv=None, search_type='grid', n_iter=100, save_results_path=None): """ Conduct a search over some pre-defined set of hyper-parameter configurations to find the best-performing set of parameter. Parameters ---------- param_grid : list, dict Parameter search space. See scikit-learn documentation for GridSearchCV and RandomSearchCV for acceptable formatting. X : array-like, optional, default None Training input samples. Must be specified if no data was provided during initialization. y : array-like, optional, default None Target values. Must be specified if no data was provided during initialization. cv : object, optional, default None A cross-validation strategy. Accepts all options considered valid by scikit-learn. Must be specified if no cv was passed in during initialization. search_type : {'grid', 'random'}, optional, default 'grid' Specifies use of grid search or random search. Requirements for param_grid are different depending on which method is used. See scikit-learn documentation for GridSearchCV and RandomSearchCV for details. n_iter : int, optional, default 100 Number of search iterations to run. Only applies to random search. save_results_path : string, optional, default None Specifies a location to save the full results of the search in format. File name should end in .csv. """ if X is not None: self.X = X if y is not None: self.y = y if cv is not None: self.cv = cv self.print_message('Beginning hyper-parameter search...') self.print_message('X dimensions = {0}'.format(self.X.shape)) self.print_message('y dimensions = {0}'.format(self.y.shape)) self.print_message('Cross-validation strategy = {0}'.format(self.cv)) t0 = time.time() if self.package not in ['sklearn', 'xgboost', 'keras', 'prophet']: raise Exception('Package not supported.') if self.package == 'keras': self.model.set_params(verbose=0) if search_type == 'grid': search = GridSearchCV(self.model, param_grid=param_grid, scoring=self.scoring_metric, n_jobs=self.n_jobs, cv=self.cv, refit=self.scoring_metric, verbose=0, return_train_score=True) elif search_type == 'random': search = RandomizedSearchCV(self.model, param_grid, n_iter=n_iter, scoring=self.scoring_metric, n_jobs=self.n_jobs, cv=self.cv, refit=self.scoring_metric, verbose=0, return_train_score=True) else: raise Exception('Search type not supported.') search.fit(self.X, self.y) t1 = time.time() self.print_message('Hyper-parameter search complete in {0:3f} s.'.format(t1 - t0)) self.print_message('Best score found = {0}'.format(search.best_score_)) self.print_message('Best parameters found:') self.print_message(search.best_params_, pprint=True) self.best_model_ = search.best_estimator_ if save_results_path: results = pd.DataFrame(search.cv_results_) results = results.sort_values(by='mean_test_score', ascending=False) results.to_csv(save_results_path, index=False) def load_model(self, filename): """ Load a previously trained model from disk. Parameters ---------- filename : string Location of the file to read. """ self.print_message('Loading model...') t0 = time.time() if self.package in ['sklearn', 'xgboost', 'prophet']: model_file = open(filename, 'rb') self.model = pickle.load(model_file) model_file.close() elif self.package == 'keras': from keras.models import load_model self.model.model = load_model(filename) else: raise Exception('Package not supported.') t1 = time.time() self.print_message('Model loaded in {0:3f} s.'.format(t1 - t0)) def save_model(self, filename): """ Persist a trained model to disk. Parameters ---------- filename : string Location of the file to write. Scikit-learn, XGBoost, and Prophet use pickle to write to disk (use .pkl extension for clarity) while Keras has a built-in save function that uses the HDF5 file format, so Keras models must have a .h5 extension. """ self.print_message('Saving model...') t0 = time.time() if self.package in ['sklearn', 'xgboost', 'prophet']: model_file = open(filename, 'wb') pickle.dump(self.model, model_file) model_file.close() elif self.package == 'keras': if hasattr(self.model, 'model'): self.model.model.save(filename) else: raise Exception('Keras model must be fit before saving.') else: raise Exception('Package not supported.') t1 = time.time() self.print_message('Model saved in {0:3f} s.'.format(t1 - t0))
apache-2.0
fbagirov/scikit-learn
sklearn/metrics/cluster/tests/test_unsupervised.py
230
2823
import numpy as np from scipy.sparse import csr_matrix from sklearn import datasets from sklearn.metrics.cluster.unsupervised import silhouette_score from sklearn.metrics import pairwise_distances from sklearn.utils.testing import assert_false, assert_almost_equal from sklearn.utils.testing import assert_raises_regexp def test_silhouette(): # Tests the Silhouette Coefficient. dataset = datasets.load_iris() X = dataset.data y = dataset.target D = pairwise_distances(X, metric='euclidean') # Given that the actual labels are used, we can assume that S would be # positive. silhouette = silhouette_score(D, y, metric='precomputed') assert(silhouette > 0) # Test without calculating D silhouette_metric = silhouette_score(X, y, metric='euclidean') assert_almost_equal(silhouette, silhouette_metric) # Test with sampling silhouette = silhouette_score(D, y, metric='precomputed', sample_size=int(X.shape[0] / 2), random_state=0) silhouette_metric = silhouette_score(X, y, metric='euclidean', sample_size=int(X.shape[0] / 2), random_state=0) assert(silhouette > 0) assert(silhouette_metric > 0) assert_almost_equal(silhouette_metric, silhouette) # Test with sparse X X_sparse = csr_matrix(X) D = pairwise_distances(X_sparse, metric='euclidean') silhouette = silhouette_score(D, y, metric='precomputed') assert(silhouette > 0) def test_no_nan(): # Assert Silhouette Coefficient != nan when there is 1 sample in a class. # This tests for the condition that caused issue 960. # Note that there is only one sample in cluster 0. This used to cause the # silhouette_score to return nan (see bug #960). labels = np.array([1, 0, 1, 1, 1]) # The distance matrix doesn't actually matter. D = np.random.RandomState(0).rand(len(labels), len(labels)) silhouette = silhouette_score(D, labels, metric='precomputed') assert_false(np.isnan(silhouette)) def test_correct_labelsize(): # Assert 1 < n_labels < n_samples dataset = datasets.load_iris() X = dataset.data # n_labels = n_samples y = np.arange(X.shape[0]) assert_raises_regexp(ValueError, 'Number of labels is %d\. Valid values are 2 ' 'to n_samples - 1 \(inclusive\)' % len(np.unique(y)), silhouette_score, X, y) # n_labels = 1 y = np.zeros(X.shape[0]) assert_raises_regexp(ValueError, 'Number of labels is %d\. Valid values are 2 ' 'to n_samples - 1 \(inclusive\)' % len(np.unique(y)), silhouette_score, X, y)
bsd-3-clause
ky822/nyu_ml_lectures
notebooks/figures/plot_digits_datasets.py
19
2750
# Taken from example in scikit-learn examples # Authors: Fabian Pedregosa <[email protected]> # Olivier Grisel <[email protected]> # Mathieu Blondel <[email protected]> # Gael Varoquaux # License: BSD 3 clause (C) INRIA 2011 import numpy as np import matplotlib.pyplot as plt from matplotlib import offsetbox from sklearn import (manifold, datasets, decomposition, ensemble, lda, random_projection) def digits_plot(): digits = datasets.load_digits(n_class=6) n_digits = 500 X = digits.data[:n_digits] y = digits.target[:n_digits] n_samples, n_features = X.shape n_neighbors = 30 def plot_embedding(X, title=None): x_min, x_max = np.min(X, 0), np.max(X, 0) X = (X - x_min) / (x_max - x_min) plt.figure() ax = plt.subplot(111) for i in range(X.shape[0]): plt.text(X[i, 0], X[i, 1], str(digits.target[i]), color=plt.cm.Set1(y[i] / 10.), fontdict={'weight': 'bold', 'size': 9}) if hasattr(offsetbox, 'AnnotationBbox'): # only print thumbnails with matplotlib > 1.0 shown_images = np.array([[1., 1.]]) # just something big for i in range(X.shape[0]): dist = np.sum((X[i] - shown_images) ** 2, 1) if np.min(dist) < 1e5: # don't show points that are too close # set a high threshold to basically turn this off continue shown_images = np.r_[shown_images, [X[i]]] imagebox = offsetbox.AnnotationBbox( offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r), X[i]) ax.add_artist(imagebox) plt.xticks([]), plt.yticks([]) if title is not None: plt.title(title) n_img_per_row = 10 img = np.zeros((10 * n_img_per_row, 10 * n_img_per_row)) for i in range(n_img_per_row): ix = 10 * i + 1 for j in range(n_img_per_row): iy = 10 * j + 1 img[ix:ix + 8, iy:iy + 8] = X[i * n_img_per_row + j].reshape((8, 8)) plt.imshow(img, cmap=plt.cm.binary) plt.xticks([]) plt.yticks([]) plt.title('A selection from the 64-dimensional digits dataset') print("Computing PCA projection") pca = decomposition.PCA(n_components=2).fit(X) X_pca = pca.transform(X) plot_embedding(X_pca, "Principal Components projection of the digits") plt.figure() plt.matshow(pca.components_[0, :].reshape(8, 8), cmap="gray") plt.axis('off') plt.figure() plt.matshow(pca.components_[1, :].reshape(8, 8), cmap="gray") plt.axis('off') plt.show()
cc0-1.0
Intel-Corporation/tensorflow
tensorflow/contrib/factorization/python/ops/gmm_test.py
41
8716
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for ops.gmm.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.factorization.python.ops import gmm as gmm_lib from tensorflow.contrib.learn.python.learn.estimators import kmeans from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import random_seed as random_seed_lib from tensorflow.python.ops import array_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import random_ops from tensorflow.python.platform import test from tensorflow.python.training import queue_runner class GMMTest(test.TestCase): def input_fn(self, batch_size=None, points=None): batch_size = batch_size or self.batch_size points = points if points is not None else self.points num_points = points.shape[0] def _fn(): x = constant_op.constant(points) if batch_size == num_points: return x, None indices = random_ops.random_uniform(constant_op.constant([batch_size]), minval=0, maxval=num_points-1, dtype=dtypes.int32, seed=10) return array_ops.gather(x, indices), None return _fn def setUp(self): np.random.seed(3) random_seed_lib.set_random_seed(2) self.num_centers = 2 self.num_dims = 2 self.num_points = 4000 self.batch_size = self.num_points self.true_centers = self.make_random_centers(self.num_centers, self.num_dims) self.points, self.assignments = self.make_random_points( self.true_centers, self.num_points) # Use initial means from kmeans (just like scikit-learn does). clusterer = kmeans.KMeansClustering(num_clusters=self.num_centers) clusterer.fit(input_fn=lambda: (constant_op.constant(self.points), None), steps=30) self.initial_means = clusterer.clusters() @staticmethod def make_random_centers(num_centers, num_dims): return np.round( np.random.rand(num_centers, num_dims).astype(np.float32) * 500) @staticmethod def make_random_points(centers, num_points): num_centers, num_dims = centers.shape assignments = np.random.choice(num_centers, num_points) offsets = np.round( np.random.randn(num_points, num_dims).astype(np.float32) * 20) points = centers[assignments] + offsets return (points, assignments) def test_weights(self): """Tests the shape of the weights.""" gmm = gmm_lib.GMM(self.num_centers, initial_clusters=self.initial_means, random_seed=4, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=0) weights = gmm.weights() self.assertAllEqual(list(weights.shape), [self.num_centers]) def test_clusters(self): """Tests the shape of the clusters.""" gmm = gmm_lib.GMM(self.num_centers, initial_clusters=self.initial_means, random_seed=4, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=0) clusters = gmm.clusters() self.assertAllEqual(list(clusters.shape), [self.num_centers, self.num_dims]) def test_fit(self): gmm = gmm_lib.GMM(self.num_centers, initial_clusters='random', random_seed=4, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=1) score1 = gmm.score(input_fn=self.input_fn(batch_size=self.num_points), steps=1) gmm.fit(input_fn=self.input_fn(), steps=10) score2 = gmm.score(input_fn=self.input_fn(batch_size=self.num_points), steps=1) self.assertLess(score1, score2) def test_infer(self): gmm = gmm_lib.GMM(self.num_centers, initial_clusters=self.initial_means, random_seed=4, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=60) clusters = gmm.clusters() # Make a small test set num_points = 40 points, true_assignments = self.make_random_points(clusters, num_points) assignments = [] for item in gmm.predict_assignments( input_fn=self.input_fn(points=points, batch_size=num_points)): assignments.append(item) assignments = np.ravel(assignments) self.assertAllEqual(true_assignments, assignments) def _compare_with_sklearn(self, cov_type): # sklearn version. iterations = 40 np.random.seed(5) sklearn_assignments = np.asarray([0, 0, 1, 0, 0, 0, 1, 0, 0, 1]) sklearn_means = np.asarray([[144.83417719, 254.20130341], [274.38754816, 353.16074346]]) sklearn_covs = np.asarray([[[395.0081194, -4.50389512], [-4.50389512, 408.27543989]], [[385.17484203, -31.27834935], [-31.27834935, 391.74249925]]]) # skflow version. gmm = gmm_lib.GMM(self.num_centers, initial_clusters=self.initial_means, covariance_type=cov_type, config=run_config.RunConfig(tf_random_seed=2)) gmm.fit(input_fn=self.input_fn(), steps=iterations) points = self.points[:10, :] skflow_assignments = [] for item in gmm.predict_assignments( input_fn=self.input_fn(points=points, batch_size=10)): skflow_assignments.append(item) self.assertAllClose(sklearn_assignments, np.ravel(skflow_assignments).astype(int)) self.assertAllClose(sklearn_means, gmm.clusters()) if cov_type == 'full': self.assertAllClose(sklearn_covs, gmm.covariances(), rtol=0.01) else: for d in [0, 1]: self.assertAllClose( np.diag(sklearn_covs[d]), gmm.covariances()[d, :], rtol=0.01) def test_compare_full(self): self._compare_with_sklearn('full') def test_compare_diag(self): self._compare_with_sklearn('diag') def test_random_input_large(self): # sklearn version. iterations = 5 # that should be enough to know whether this diverges np.random.seed(5) num_classes = 20 x = np.array([[np.random.random() for _ in range(100)] for _ in range(num_classes)], dtype=np.float32) # skflow version. gmm = gmm_lib.GMM(num_classes, covariance_type='full', config=run_config.RunConfig(tf_random_seed=2)) def get_input_fn(x): def input_fn(): return constant_op.constant(x.astype(np.float32)), None return input_fn gmm.fit(input_fn=get_input_fn(x), steps=iterations) self.assertFalse(np.isnan(gmm.clusters()).any()) class GMMTestQueues(test.TestCase): def input_fn(self): def _fn(): queue = data_flow_ops.FIFOQueue(capacity=10, dtypes=dtypes.float32, shapes=[10, 3]) enqueue_op = queue.enqueue(array_ops.zeros([10, 3], dtype=dtypes.float32)) queue_runner.add_queue_runner(queue_runner.QueueRunner(queue, [enqueue_op])) return queue.dequeue(), None return _fn # This test makes sure that there are no deadlocks when using a QueueRunner. # Note that since cluster initialization is dependent on inputs, if input # is generated using a QueueRunner, one has to make sure that these runners # are started before the initialization. def test_queues(self): gmm = gmm_lib.GMM(2, covariance_type='diag') gmm.fit(input_fn=self.input_fn(), steps=1) if __name__ == '__main__': test.main()
apache-2.0
zorojean/scikit-learn
sklearn/preprocessing/tests/test_label.py
156
17626
import numpy as np from scipy.sparse import issparse from scipy.sparse import coo_matrix from scipy.sparse import csc_matrix from scipy.sparse import csr_matrix from scipy.sparse import dok_matrix from scipy.sparse import lil_matrix from sklearn.utils.multiclass import type_of_target from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import ignore_warnings from sklearn.preprocessing.label import LabelBinarizer from sklearn.preprocessing.label import MultiLabelBinarizer from sklearn.preprocessing.label import LabelEncoder from sklearn.preprocessing.label import label_binarize from sklearn.preprocessing.label import _inverse_binarize_thresholding from sklearn.preprocessing.label import _inverse_binarize_multiclass from sklearn import datasets iris = datasets.load_iris() def toarray(a): if hasattr(a, "toarray"): a = a.toarray() return a def test_label_binarizer(): lb = LabelBinarizer() # one-class case defaults to negative label inp = ["pos", "pos", "pos", "pos"] expected = np.array([[0, 0, 0, 0]]).T got = lb.fit_transform(inp) assert_array_equal(lb.classes_, ["pos"]) assert_array_equal(expected, got) assert_array_equal(lb.inverse_transform(got), inp) # two-class case inp = ["neg", "pos", "pos", "neg"] expected = np.array([[0, 1, 1, 0]]).T got = lb.fit_transform(inp) assert_array_equal(lb.classes_, ["neg", "pos"]) assert_array_equal(expected, got) to_invert = np.array([[1, 0], [0, 1], [0, 1], [1, 0]]) assert_array_equal(lb.inverse_transform(to_invert), inp) # multi-class case inp = ["spam", "ham", "eggs", "ham", "0"] expected = np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]) got = lb.fit_transform(inp) assert_array_equal(lb.classes_, ['0', 'eggs', 'ham', 'spam']) assert_array_equal(expected, got) assert_array_equal(lb.inverse_transform(got), inp) def test_label_binarizer_unseen_labels(): lb = LabelBinarizer() expected = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) got = lb.fit_transform(['b', 'd', 'e']) assert_array_equal(expected, got) expected = np.array([[0, 0, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]) got = lb.transform(['a', 'b', 'c', 'd', 'e', 'f']) assert_array_equal(expected, got) def test_label_binarizer_set_label_encoding(): lb = LabelBinarizer(neg_label=-2, pos_label=0) # two-class case with pos_label=0 inp = np.array([0, 1, 1, 0]) expected = np.array([[-2, 0, 0, -2]]).T got = lb.fit_transform(inp) assert_array_equal(expected, got) assert_array_equal(lb.inverse_transform(got), inp) lb = LabelBinarizer(neg_label=-2, pos_label=2) # multi-class case inp = np.array([3, 2, 1, 2, 0]) expected = np.array([[-2, -2, -2, +2], [-2, -2, +2, -2], [-2, +2, -2, -2], [-2, -2, +2, -2], [+2, -2, -2, -2]]) got = lb.fit_transform(inp) assert_array_equal(expected, got) assert_array_equal(lb.inverse_transform(got), inp) @ignore_warnings def test_label_binarizer_errors(): # Check that invalid arguments yield ValueError one_class = np.array([0, 0, 0, 0]) lb = LabelBinarizer().fit(one_class) multi_label = [(2, 3), (0,), (0, 2)] assert_raises(ValueError, lb.transform, multi_label) lb = LabelBinarizer() assert_raises(ValueError, lb.transform, []) assert_raises(ValueError, lb.inverse_transform, []) assert_raises(ValueError, LabelBinarizer, neg_label=2, pos_label=1) assert_raises(ValueError, LabelBinarizer, neg_label=2, pos_label=2) assert_raises(ValueError, LabelBinarizer, neg_label=1, pos_label=2, sparse_output=True) # Fail on y_type assert_raises(ValueError, _inverse_binarize_thresholding, y=csr_matrix([[1, 2], [2, 1]]), output_type="foo", classes=[1, 2], threshold=0) # Sequence of seq type should raise ValueError y_seq_of_seqs = [[], [1, 2], [3], [0, 1, 3], [2]] assert_raises(ValueError, LabelBinarizer().fit_transform, y_seq_of_seqs) # Fail on the number of classes assert_raises(ValueError, _inverse_binarize_thresholding, y=csr_matrix([[1, 2], [2, 1]]), output_type="foo", classes=[1, 2, 3], threshold=0) # Fail on the dimension of 'binary' assert_raises(ValueError, _inverse_binarize_thresholding, y=np.array([[1, 2, 3], [2, 1, 3]]), output_type="binary", classes=[1, 2, 3], threshold=0) # Fail on multioutput data assert_raises(ValueError, LabelBinarizer().fit, np.array([[1, 3], [2, 1]])) assert_raises(ValueError, label_binarize, np.array([[1, 3], [2, 1]]), [1, 2, 3]) def test_label_encoder(): # Test LabelEncoder's transform and inverse_transform methods le = LabelEncoder() le.fit([1, 1, 4, 5, -1, 0]) assert_array_equal(le.classes_, [-1, 0, 1, 4, 5]) assert_array_equal(le.transform([0, 1, 4, 4, 5, -1, -1]), [1, 2, 3, 3, 4, 0, 0]) assert_array_equal(le.inverse_transform([1, 2, 3, 3, 4, 0, 0]), [0, 1, 4, 4, 5, -1, -1]) assert_raises(ValueError, le.transform, [0, 6]) def test_label_encoder_fit_transform(): # Test fit_transform le = LabelEncoder() ret = le.fit_transform([1, 1, 4, 5, -1, 0]) assert_array_equal(ret, [2, 2, 3, 4, 0, 1]) le = LabelEncoder() ret = le.fit_transform(["paris", "paris", "tokyo", "amsterdam"]) assert_array_equal(ret, [1, 1, 2, 0]) def test_label_encoder_errors(): # Check that invalid arguments yield ValueError le = LabelEncoder() assert_raises(ValueError, le.transform, []) assert_raises(ValueError, le.inverse_transform, []) # Fail on unseen labels le = LabelEncoder() le.fit([1, 2, 3, 1, -1]) assert_raises(ValueError, le.inverse_transform, [-1]) def test_sparse_output_multilabel_binarizer(): # test input as iterable of iterables inputs = [ lambda: [(2, 3), (1,), (1, 2)], lambda: (set([2, 3]), set([1]), set([1, 2])), lambda: iter([iter((2, 3)), iter((1,)), set([1, 2])]), ] indicator_mat = np.array([[0, 1, 1], [1, 0, 0], [1, 1, 0]]) inverse = inputs[0]() for sparse_output in [True, False]: for inp in inputs: # With fit_tranform mlb = MultiLabelBinarizer(sparse_output=sparse_output) got = mlb.fit_transform(inp()) assert_equal(issparse(got), sparse_output) if sparse_output: got = got.toarray() assert_array_equal(indicator_mat, got) assert_array_equal([1, 2, 3], mlb.classes_) assert_equal(mlb.inverse_transform(got), inverse) # With fit mlb = MultiLabelBinarizer(sparse_output=sparse_output) got = mlb.fit(inp()).transform(inp()) assert_equal(issparse(got), sparse_output) if sparse_output: got = got.toarray() assert_array_equal(indicator_mat, got) assert_array_equal([1, 2, 3], mlb.classes_) assert_equal(mlb.inverse_transform(got), inverse) assert_raises(ValueError, mlb.inverse_transform, csr_matrix(np.array([[0, 1, 1], [2, 0, 0], [1, 1, 0]]))) def test_multilabel_binarizer(): # test input as iterable of iterables inputs = [ lambda: [(2, 3), (1,), (1, 2)], lambda: (set([2, 3]), set([1]), set([1, 2])), lambda: iter([iter((2, 3)), iter((1,)), set([1, 2])]), ] indicator_mat = np.array([[0, 1, 1], [1, 0, 0], [1, 1, 0]]) inverse = inputs[0]() for inp in inputs: # With fit_tranform mlb = MultiLabelBinarizer() got = mlb.fit_transform(inp()) assert_array_equal(indicator_mat, got) assert_array_equal([1, 2, 3], mlb.classes_) assert_equal(mlb.inverse_transform(got), inverse) # With fit mlb = MultiLabelBinarizer() got = mlb.fit(inp()).transform(inp()) assert_array_equal(indicator_mat, got) assert_array_equal([1, 2, 3], mlb.classes_) assert_equal(mlb.inverse_transform(got), inverse) def test_multilabel_binarizer_empty_sample(): mlb = MultiLabelBinarizer() y = [[1, 2], [1], []] Y = np.array([[1, 1], [1, 0], [0, 0]]) assert_array_equal(mlb.fit_transform(y), Y) def test_multilabel_binarizer_unknown_class(): mlb = MultiLabelBinarizer() y = [[1, 2]] assert_raises(KeyError, mlb.fit(y).transform, [[0]]) mlb = MultiLabelBinarizer(classes=[1, 2]) assert_raises(KeyError, mlb.fit_transform, [[0]]) def test_multilabel_binarizer_given_classes(): inp = [(2, 3), (1,), (1, 2)] indicator_mat = np.array([[0, 1, 1], [1, 0, 0], [1, 0, 1]]) # fit_transform() mlb = MultiLabelBinarizer(classes=[1, 3, 2]) assert_array_equal(mlb.fit_transform(inp), indicator_mat) assert_array_equal(mlb.classes_, [1, 3, 2]) # fit().transform() mlb = MultiLabelBinarizer(classes=[1, 3, 2]) assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) assert_array_equal(mlb.classes_, [1, 3, 2]) # ensure works with extra class mlb = MultiLabelBinarizer(classes=[4, 1, 3, 2]) assert_array_equal(mlb.fit_transform(inp), np.hstack(([[0], [0], [0]], indicator_mat))) assert_array_equal(mlb.classes_, [4, 1, 3, 2]) # ensure fit is no-op as iterable is not consumed inp = iter(inp) mlb = MultiLabelBinarizer(classes=[1, 3, 2]) assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) def test_multilabel_binarizer_same_length_sequence(): # Ensure sequences of the same length are not interpreted as a 2-d array inp = [[1], [0], [2]] indicator_mat = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) # fit_transform() mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit_transform(inp), indicator_mat) assert_array_equal(mlb.inverse_transform(indicator_mat), inp) # fit().transform() mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) assert_array_equal(mlb.inverse_transform(indicator_mat), inp) def test_multilabel_binarizer_non_integer_labels(): tuple_classes = np.empty(3, dtype=object) tuple_classes[:] = [(1,), (2,), (3,)] inputs = [ ([('2', '3'), ('1',), ('1', '2')], ['1', '2', '3']), ([('b', 'c'), ('a',), ('a', 'b')], ['a', 'b', 'c']), ([((2,), (3,)), ((1,),), ((1,), (2,))], tuple_classes), ] indicator_mat = np.array([[0, 1, 1], [1, 0, 0], [1, 1, 0]]) for inp, classes in inputs: # fit_transform() mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit_transform(inp), indicator_mat) assert_array_equal(mlb.classes_, classes) assert_array_equal(mlb.inverse_transform(indicator_mat), inp) # fit().transform() mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat) assert_array_equal(mlb.classes_, classes) assert_array_equal(mlb.inverse_transform(indicator_mat), inp) mlb = MultiLabelBinarizer() assert_raises(TypeError, mlb.fit_transform, [({}), ({}, {'a': 'b'})]) def test_multilabel_binarizer_non_unique(): inp = [(1, 1, 1, 0)] indicator_mat = np.array([[1, 1]]) mlb = MultiLabelBinarizer() assert_array_equal(mlb.fit_transform(inp), indicator_mat) def test_multilabel_binarizer_inverse_validation(): inp = [(1, 1, 1, 0)] mlb = MultiLabelBinarizer() mlb.fit_transform(inp) # Not binary assert_raises(ValueError, mlb.inverse_transform, np.array([[1, 3]])) # The following binary cases are fine, however mlb.inverse_transform(np.array([[0, 0]])) mlb.inverse_transform(np.array([[1, 1]])) mlb.inverse_transform(np.array([[1, 0]])) # Wrong shape assert_raises(ValueError, mlb.inverse_transform, np.array([[1]])) assert_raises(ValueError, mlb.inverse_transform, np.array([[1, 1, 1]])) def test_label_binarize_with_class_order(): out = label_binarize([1, 6], classes=[1, 2, 4, 6]) expected = np.array([[1, 0, 0, 0], [0, 0, 0, 1]]) assert_array_equal(out, expected) # Modified class order out = label_binarize([1, 6], classes=[1, 6, 4, 2]) expected = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) assert_array_equal(out, expected) out = label_binarize([0, 1, 2, 3], classes=[3, 2, 0, 1]) expected = np.array([[0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0]]) assert_array_equal(out, expected) def check_binarized_results(y, classes, pos_label, neg_label, expected): for sparse_output in [True, False]: if ((pos_label == 0 or neg_label != 0) and sparse_output): assert_raises(ValueError, label_binarize, y, classes, neg_label=neg_label, pos_label=pos_label, sparse_output=sparse_output) continue # check label_binarize binarized = label_binarize(y, classes, neg_label=neg_label, pos_label=pos_label, sparse_output=sparse_output) assert_array_equal(toarray(binarized), expected) assert_equal(issparse(binarized), sparse_output) # check inverse y_type = type_of_target(y) if y_type == "multiclass": inversed = _inverse_binarize_multiclass(binarized, classes=classes) else: inversed = _inverse_binarize_thresholding(binarized, output_type=y_type, classes=classes, threshold=((neg_label + pos_label) / 2.)) assert_array_equal(toarray(inversed), toarray(y)) # Check label binarizer lb = LabelBinarizer(neg_label=neg_label, pos_label=pos_label, sparse_output=sparse_output) binarized = lb.fit_transform(y) assert_array_equal(toarray(binarized), expected) assert_equal(issparse(binarized), sparse_output) inverse_output = lb.inverse_transform(binarized) assert_array_equal(toarray(inverse_output), toarray(y)) assert_equal(issparse(inverse_output), issparse(y)) def test_label_binarize_binary(): y = [0, 1, 0] classes = [0, 1] pos_label = 2 neg_label = -1 expected = np.array([[2, -1], [-1, 2], [2, -1]])[:, 1].reshape((-1, 1)) yield check_binarized_results, y, classes, pos_label, neg_label, expected # Binary case where sparse_output = True will not result in a ValueError y = [0, 1, 0] classes = [0, 1] pos_label = 3 neg_label = 0 expected = np.array([[3, 0], [0, 3], [3, 0]])[:, 1].reshape((-1, 1)) yield check_binarized_results, y, classes, pos_label, neg_label, expected def test_label_binarize_multiclass(): y = [0, 1, 2] classes = [0, 1, 2] pos_label = 2 neg_label = 0 expected = 2 * np.eye(3) yield check_binarized_results, y, classes, pos_label, neg_label, expected assert_raises(ValueError, label_binarize, y, classes, neg_label=-1, pos_label=pos_label, sparse_output=True) def test_label_binarize_multilabel(): y_ind = np.array([[0, 1, 0], [1, 1, 1], [0, 0, 0]]) classes = [0, 1, 2] pos_label = 2 neg_label = 0 expected = pos_label * y_ind y_sparse = [sparse_matrix(y_ind) for sparse_matrix in [coo_matrix, csc_matrix, csr_matrix, dok_matrix, lil_matrix]] for y in [y_ind] + y_sparse: yield (check_binarized_results, y, classes, pos_label, neg_label, expected) assert_raises(ValueError, label_binarize, y, classes, neg_label=-1, pos_label=pos_label, sparse_output=True) def test_invalid_input_label_binarize(): assert_raises(ValueError, label_binarize, [0, 2], classes=[0, 2], pos_label=0, neg_label=1) def test_inverse_binarize_multiclass(): got = _inverse_binarize_multiclass(csr_matrix([[0, 1, 0], [-1, 0, -1], [0, 0, 0]]), np.arange(3)) assert_array_equal(got, np.array([1, 1, 0]))
bsd-3-clause
vibhorag/scikit-learn
examples/cluster/plot_kmeans_assumptions.py
270
2040
""" ==================================== Demonstration of k-means assumptions ==================================== This example is meant to illustrate situations where k-means will produce unintuitive and possibly unexpected clusters. In the first three plots, the input data does not conform to some implicit assumption that k-means makes and undesirable clusters are produced as a result. In the last plot, k-means returns intuitive clusters despite unevenly sized blobs. """ print(__doc__) # Author: Phil Roth <[email protected]> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import make_blobs plt.figure(figsize=(12, 12)) n_samples = 1500 random_state = 170 X, y = make_blobs(n_samples=n_samples, random_state=random_state) # Incorrect number of clusters y_pred = KMeans(n_clusters=2, random_state=random_state).fit_predict(X) plt.subplot(221) plt.scatter(X[:, 0], X[:, 1], c=y_pred) plt.title("Incorrect Number of Blobs") # Anisotropicly distributed data transformation = [[ 0.60834549, -0.63667341], [-0.40887718, 0.85253229]] X_aniso = np.dot(X, transformation) y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_aniso) plt.subplot(222) plt.scatter(X_aniso[:, 0], X_aniso[:, 1], c=y_pred) plt.title("Anisotropicly Distributed Blobs") # Different variance X_varied, y_varied = make_blobs(n_samples=n_samples, cluster_std=[1.0, 2.5, 0.5], random_state=random_state) y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_varied) plt.subplot(223) plt.scatter(X_varied[:, 0], X_varied[:, 1], c=y_pred) plt.title("Unequal Variance") # Unevenly sized blobs X_filtered = np.vstack((X[y == 0][:500], X[y == 1][:100], X[y == 2][:10])) y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_filtered) plt.subplot(224) plt.scatter(X_filtered[:, 0], X_filtered[:, 1], c=y_pred) plt.title("Unevenly Sized Blobs") plt.show()
bsd-3-clause
ndingwall/scikit-learn
examples/feature_selection/plot_feature_selection.py
18
3371
""" ============================ Univariate Feature Selection ============================ An example showing univariate feature selection. Noisy (non informative) features are added to the iris data and univariate feature selection is applied. For each feature, we plot the p-values for the univariate feature selection and the corresponding weights of an SVM. We can see that univariate feature selection selects the informative features and that these have larger SVM weights. In the total set of features, only the 4 first ones are significant. We can see that they have the highest score with univariate feature selection. The SVM assigns a large weight to one of these features, but also Selects many of the non-informative features. Applying univariate feature selection before the SVM increases the SVM weight attributed to the significant features, and will thus improve classification. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.svm import LinearSVC from sklearn.pipeline import make_pipeline from sklearn.feature_selection import SelectKBest, f_classif # ############################################################################# # Import some data to play with # The iris dataset X, y = load_iris(return_X_y=True) # Some noisy data not correlated E = np.random.RandomState(42).uniform(0, 0.1, size=(X.shape[0], 20)) # Add the noisy data to the informative features X = np.hstack((X, E)) # Split dataset to select feature and evaluate the classifier X_train, X_test, y_train, y_test = train_test_split( X, y, stratify=y, random_state=0 ) plt.figure(1) plt.clf() X_indices = np.arange(X.shape[-1]) # ############################################################################# # Univariate feature selection with F-test for feature scoring # We use the default selection function to select the four # most significant features selector = SelectKBest(f_classif, k=4) selector.fit(X_train, y_train) scores = -np.log10(selector.pvalues_) scores /= scores.max() plt.bar(X_indices - .45, scores, width=.2, label=r'Univariate score ($-Log(p_{value})$)') # ############################################################################# # Compare to the weights of an SVM clf = make_pipeline(MinMaxScaler(), LinearSVC()) clf.fit(X_train, y_train) print('Classification accuracy without selecting features: {:.3f}' .format(clf.score(X_test, y_test))) svm_weights = np.abs(clf[-1].coef_).sum(axis=0) svm_weights /= svm_weights.sum() plt.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight') clf_selected = make_pipeline( SelectKBest(f_classif, k=4), MinMaxScaler(), LinearSVC() ) clf_selected.fit(X_train, y_train) print('Classification accuracy after univariate feature selection: {:.3f}' .format(clf_selected.score(X_test, y_test))) svm_weights_selected = np.abs(clf_selected[-1].coef_).sum(axis=0) svm_weights_selected /= svm_weights_selected.sum() plt.bar(X_indices[selector.get_support()] - .05, svm_weights_selected, width=.2, label='SVM weights after selection') plt.title("Comparing feature selection") plt.xlabel('Feature number') plt.yticks(()) plt.axis('tight') plt.legend(loc='upper right') plt.show()
bsd-3-clause
deepesch/scikit-learn
sklearn/datasets/mldata.py
309
7838
"""Automatically download MLdata datasets.""" # Copyright (c) 2011 Pietro Berkes # License: BSD 3 clause import os from os.path import join, exists import re import numbers try: # Python 2 from urllib2 import HTTPError from urllib2 import quote from urllib2 import urlopen except ImportError: # Python 3+ from urllib.error import HTTPError from urllib.parse import quote from urllib.request import urlopen import numpy as np import scipy as sp from scipy import io from shutil import copyfileobj from .base import get_data_home, Bunch MLDATA_BASE_URL = "http://mldata.org/repository/data/download/matlab/%s" def mldata_filename(dataname): """Convert a raw name for a data set in a mldata.org filename.""" dataname = dataname.lower().replace(' ', '-') return re.sub(r'[().]', '', dataname) def fetch_mldata(dataname, target_name='label', data_name='data', transpose_data=True, data_home=None): """Fetch an mldata.org data set If the file does not exist yet, it is downloaded from mldata.org . mldata.org does not have an enforced convention for storing data or naming the columns in a data set. The default behavior of this function works well with the most common cases: 1) data values are stored in the column 'data', and target values in the column 'label' 2) alternatively, the first column stores target values, and the second data values 3) the data array is stored as `n_features x n_samples` , and thus needs to be transposed to match the `sklearn` standard Keyword arguments allow to adapt these defaults to specific data sets (see parameters `target_name`, `data_name`, `transpose_data`, and the examples below). mldata.org data sets may have multiple columns, which are stored in the Bunch object with their original name. Parameters ---------- dataname: Name of the data set on mldata.org, e.g.: "leukemia", "Whistler Daily Snowfall", etc. The raw name is automatically converted to a mldata.org URL . target_name: optional, default: 'label' Name or index of the column containing the target values. data_name: optional, default: 'data' Name or index of the column containing the data. transpose_data: optional, default: True If True, transpose the downloaded data array. data_home: optional, default: None Specify another download and cache folder for the data sets. By default all scikit learn data is stored in '~/scikit_learn_data' subfolders. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'target', the classification labels, 'DESCR', the full description of the dataset, and 'COL_NAMES', the original names of the dataset columns. Examples -------- Load the 'iris' dataset from mldata.org: >>> from sklearn.datasets.mldata import fetch_mldata >>> import tempfile >>> test_data_home = tempfile.mkdtemp() >>> iris = fetch_mldata('iris', data_home=test_data_home) >>> iris.target.shape (150,) >>> iris.data.shape (150, 4) Load the 'leukemia' dataset from mldata.org, which needs to be transposed to respects the sklearn axes convention: >>> leuk = fetch_mldata('leukemia', transpose_data=True, ... data_home=test_data_home) >>> leuk.data.shape (72, 7129) Load an alternative 'iris' dataset, which has different names for the columns: >>> iris2 = fetch_mldata('datasets-UCI iris', target_name=1, ... data_name=0, data_home=test_data_home) >>> iris3 = fetch_mldata('datasets-UCI iris', ... target_name='class', data_name='double0', ... data_home=test_data_home) >>> import shutil >>> shutil.rmtree(test_data_home) """ # normalize dataset name dataname = mldata_filename(dataname) # check if this data set has been already downloaded data_home = get_data_home(data_home=data_home) data_home = join(data_home, 'mldata') if not exists(data_home): os.makedirs(data_home) matlab_name = dataname + '.mat' filename = join(data_home, matlab_name) # if the file does not exist, download it if not exists(filename): urlname = MLDATA_BASE_URL % quote(dataname) try: mldata_url = urlopen(urlname) except HTTPError as e: if e.code == 404: e.msg = "Dataset '%s' not found on mldata.org." % dataname raise # store Matlab file try: with open(filename, 'w+b') as matlab_file: copyfileobj(mldata_url, matlab_file) except: os.remove(filename) raise mldata_url.close() # load dataset matlab file with open(filename, 'rb') as matlab_file: matlab_dict = io.loadmat(matlab_file, struct_as_record=True) # -- extract data from matlab_dict # flatten column names col_names = [str(descr[0]) for descr in matlab_dict['mldata_descr_ordering'][0]] # if target or data names are indices, transform then into names if isinstance(target_name, numbers.Integral): target_name = col_names[target_name] if isinstance(data_name, numbers.Integral): data_name = col_names[data_name] # rules for making sense of the mldata.org data format # (earlier ones have priority): # 1) there is only one array => it is "data" # 2) there are multiple arrays # a) copy all columns in the bunch, using their column name # b) if there is a column called `target_name`, set "target" to it, # otherwise set "target" to first column # c) if there is a column called `data_name`, set "data" to it, # otherwise set "data" to second column dataset = {'DESCR': 'mldata.org dataset: %s' % dataname, 'COL_NAMES': col_names} # 1) there is only one array => it is considered data if len(col_names) == 1: data_name = col_names[0] dataset['data'] = matlab_dict[data_name] # 2) there are multiple arrays else: for name in col_names: dataset[name] = matlab_dict[name] if target_name in col_names: del dataset[target_name] dataset['target'] = matlab_dict[target_name] else: del dataset[col_names[0]] dataset['target'] = matlab_dict[col_names[0]] if data_name in col_names: del dataset[data_name] dataset['data'] = matlab_dict[data_name] else: del dataset[col_names[1]] dataset['data'] = matlab_dict[col_names[1]] # set axes to sklearn conventions if transpose_data: dataset['data'] = dataset['data'].T if 'target' in dataset: if not sp.sparse.issparse(dataset['target']): dataset['target'] = dataset['target'].squeeze() return Bunch(**dataset) # The following is used by nosetests to setup the docstring tests fixture def setup_module(module): # setup mock urllib2 module to avoid downloading from mldata.org from sklearn.utils.testing import install_mldata_mock install_mldata_mock({ 'iris': { 'data': np.empty((150, 4)), 'label': np.empty(150), }, 'datasets-uci-iris': { 'double0': np.empty((150, 4)), 'class': np.empty((150,)), }, 'leukemia': { 'data': np.empty((72, 7129)), }, }) def teardown_module(module): from sklearn.utils.testing import uninstall_mldata_mock uninstall_mldata_mock()
bsd-3-clause
arabenjamin/scikit-learn
examples/feature_selection/plot_feature_selection.py
249
2827
""" =============================== Univariate Feature Selection =============================== An example showing univariate feature selection. Noisy (non informative) features are added to the iris data and univariate feature selection is applied. For each feature, we plot the p-values for the univariate feature selection and the corresponding weights of an SVM. We can see that univariate feature selection selects the informative features and that these have larger SVM weights. In the total set of features, only the 4 first ones are significant. We can see that they have the highest score with univariate feature selection. The SVM assigns a large weight to one of these features, but also Selects many of the non-informative features. Applying univariate feature selection before the SVM increases the SVM weight attributed to the significant features, and will thus improve classification. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, svm from sklearn.feature_selection import SelectPercentile, f_classif ############################################################################### # import some data to play with # The iris dataset iris = datasets.load_iris() # Some noisy data not correlated E = np.random.uniform(0, 0.1, size=(len(iris.data), 20)) # Add the noisy data to the informative features X = np.hstack((iris.data, E)) y = iris.target ############################################################################### plt.figure(1) plt.clf() X_indices = np.arange(X.shape[-1]) ############################################################################### # Univariate feature selection with F-test for feature scoring # We use the default selection function: the 10% most significant features selector = SelectPercentile(f_classif, percentile=10) selector.fit(X, y) scores = -np.log10(selector.pvalues_) scores /= scores.max() plt.bar(X_indices - .45, scores, width=.2, label=r'Univariate score ($-Log(p_{value})$)', color='g') ############################################################################### # Compare to the weights of an SVM clf = svm.SVC(kernel='linear') clf.fit(X, y) svm_weights = (clf.coef_ ** 2).sum(axis=0) svm_weights /= svm_weights.max() plt.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight', color='r') clf_selected = svm.SVC(kernel='linear') clf_selected.fit(selector.transform(X), y) svm_weights_selected = (clf_selected.coef_ ** 2).sum(axis=0) svm_weights_selected /= svm_weights_selected.max() plt.bar(X_indices[selector.get_support()] - .05, svm_weights_selected, width=.2, label='SVM weights after selection', color='b') plt.title("Comparing feature selection") plt.xlabel('Feature number') plt.yticks(()) plt.axis('tight') plt.legend(loc='upper right') plt.show()
bsd-3-clause
cl4rke/scikit-learn
benchmarks/bench_20newsgroups.py
377
3555
from __future__ import print_function, division from time import time import argparse import numpy as np from sklearn.dummy import DummyClassifier from sklearn.datasets import fetch_20newsgroups_vectorized from sklearn.metrics import accuracy_score from sklearn.utils.validation import check_array from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB ESTIMATORS = { "dummy": DummyClassifier(), "random_forest": RandomForestClassifier(n_estimators=100, max_features="sqrt", min_samples_split=10), "extra_trees": ExtraTreesClassifier(n_estimators=100, max_features="sqrt", min_samples_split=10), "logistic_regression": LogisticRegression(), "naive_bayes": MultinomialNB(), "adaboost": AdaBoostClassifier(n_estimators=10), } ############################################################################### # Data if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-e', '--estimators', nargs="+", required=True, choices=ESTIMATORS) args = vars(parser.parse_args()) data_train = fetch_20newsgroups_vectorized(subset="train") data_test = fetch_20newsgroups_vectorized(subset="test") X_train = check_array(data_train.data, dtype=np.float32, accept_sparse="csc") X_test = check_array(data_test.data, dtype=np.float32, accept_sparse="csr") y_train = data_train.target y_test = data_test.target print("20 newsgroups") print("=============") print("X_train.shape = {0}".format(X_train.shape)) print("X_train.format = {0}".format(X_train.format)) print("X_train.dtype = {0}".format(X_train.dtype)) print("X_train density = {0}" "".format(X_train.nnz / np.product(X_train.shape))) print("y_train {0}".format(y_train.shape)) print("X_test {0}".format(X_test.shape)) print("X_test.format = {0}".format(X_test.format)) print("X_test.dtype = {0}".format(X_test.dtype)) print("y_test {0}".format(y_test.shape)) print() print("Classifier Training") print("===================") accuracy, train_time, test_time = {}, {}, {} for name in sorted(args["estimators"]): clf = ESTIMATORS[name] try: clf.set_params(random_state=0) except (TypeError, ValueError): pass print("Training %s ... " % name, end="") t0 = time() clf.fit(X_train, y_train) train_time[name] = time() - t0 t0 = time() y_pred = clf.predict(X_test) test_time[name] = time() - t0 accuracy[name] = accuracy_score(y_test, y_pred) print("done") print() print("Classification performance:") print("===========================") print() print("%s %s %s %s" % ("Classifier ", "train-time", "test-time", "Accuracy")) print("-" * 44) for name in sorted(accuracy, key=accuracy.get): print("%s %s %s %s" % (name.ljust(16), ("%.4fs" % train_time[name]).center(10), ("%.4fs" % test_time[name]).center(10), ("%.4f" % accuracy[name]).center(10))) print()
bsd-3-clause