feature_selection模块

Univariate feature selection:单变量的特征选择
单变量特征选择的原理是分别单独的计算每个变量的某个统计指标,根据该指标来判断哪些指标重要。剔除那些不重要的指标。
 
sklearn.feature_selection模块中主要有以下几个方法:
SelectKBest和SelectPercentile比较相似,前者选择排名排在前n个的变量,后者选择排名排在前n%的变量。而他们通过什么指标来给变量排名呢?这需要二外的指定。
对于regression问题,可以使用f_regression指标。对于classification问题,可以使用chi2或者f_classif变量。
使用的例子:
from sklearn.feature_selection import SelectPercentile, f_classif
selector = SelectPercentile(f_classif, percentile=10)
 
还有其他的几个方法,似乎是使用其他的统计指标来选择变量:using common univariate statistical tests for each feature: false positive rate SelectFpr, false discovery rate SelectFdr, or family wise error SelectFwe.
 
文档中说,如果是使用稀疏矩阵,只有chi2指标可用,其他的都必须转变成dense matrix。但是我实际使用中发现f_classif也是可以使用稀疏矩阵的。
 
Recursive feature elimination:循环特征选择
不单独的检验某个变量的价值,而是将其聚集在一起检验。它的基本思想是,对于一个数量为d的feature的集合,他的所有的子集的个数是2的d次方减1(包含空集)。指定一个外部的学习算法,比如SVM之类的。通过该算法计算所有子集的validation error。选择error最小的那个子集作为所挑选的特征。
 
这个算法相当的暴力啊。由以下两个方法实现:sklearn.feature_selection.RFE,sklearn.feature_selection.RFECV
 
L1-based feature selection:
该思路的原理是:在linear regression模型中,有的时候会得到sparse solution。意思是说很多变量前面的系数都等于0或者接近于0。这说明这些变量不重要,那么可以将这些变量去除。
 
Tree-based feature selection:决策树特征选择
基于决策树算法做出特征选择
 

1.13. Feature selection

The classes in the sklearn.feature_selection module can be used for feature selection/dimensionality reduction on sample sets, either to improve estimators’ accuracy scores or to boost their performance on very high-dimensional datasets.

1.13.1. Removing features with low variance

VarianceThreshold is a simple baseline approach to feature selection. It removes all features whose variance doesn’t meet some threshold. By default, it removes all zero-variance features, i.e. features that have the same value in all samples.

As an example, suppose that we have a dataset with boolean features, and we want to remove all features that are either one or zero (on or off) in more than 80% of the samples. Boolean features are Bernoulli random variables, and the variance of such variables is given by

so we can select using the threshold .8 * (1 - .8):

>>>

>>> from sklearn.feature_selection import VarianceThreshold
>>> X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]]
>>> sel = VarianceThreshold(threshold=(.8 * (1 - .8)))
>>> sel.fit_transform(X)
array([[0, 1],
[1, 0],
[0, 0],
[1, 1],
[1, 0],
[1, 1]])

As expected, VarianceThreshold has removed the first column, which has a probability  of containing a zero.

1.13.2. Univariate feature selection

Univariate feature selection works by selecting the best features based on univariate statistical tests. It can be seen as a preprocessing step to an estimator. Scikit-learn exposes feature selection routines as objects that implement the transformmethod:

  • SelectKBest removes all but the  highest scoring features

  • SelectPercentile removes all but a user-specified highest scoring percentage of features

  • using common univariate statistical tests for each feature: false positive rate SelectFpr, false discovery rateSelectFdr, or family wise error SelectFwe.

  • GenericUnivariateSelect allows to perform univariate feature

    selection with a configurable strategy. This allows to select the best univariate selection strategy with hyper-parameter search estimator.

For instance, we can perform a  test to the samples to retrieve only the two best features as follows:

>>>

>>> from sklearn.datasets import load_iris
>>> from sklearn.feature_selection import SelectKBest
>>> from sklearn.feature_selection import chi2
>>> iris = load_iris()
>>> X, y = iris.data, iris.target
>>> X.shape
(150, 4)
>>> X_new = SelectKBest(chi2, k=2).fit_transform(X, y)
>>> X_new.shape
(150, 2)

These objects take as input a scoring function that returns univariate p-values:

Feature selection with sparse data

If you use sparse data (i.e. data represented as sparse matrices), only chi2 will deal with the data without making it dense.

Warning

Beware not to use a regression scoring function with a classification problem, you will get useless results.

1.13.3. Recursive feature elimination

Given an external estimator that assigns weights to features (e.g., the coefficients of a linear model), recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features. First, the estimator is trained on the initial set of features and weights are assigned to each one of them. Then, features whose absolute weights are the smallest are pruned from the current set features. That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached.

RFECV performs RFE in a cross-validation loop to find the optimal number of features.

Examples:

1.13.4. L1-based feature selection

1.13.4.1. Selecting non-zero coefficients

Linear models penalized with the L1 norm have sparse solutions: many of their estimated coefficients are zero. When the goal is to reduce the dimensionality of the data to use with another classifier, they expose a transform method to select the non-zero coefficient. In particular, sparse estimators useful for this purpose are the linear_model.Lasso for regression, and oflinear_model.LogisticRegression and svm.LinearSVC for classification:

>>>

>>> from sklearn.svm import LinearSVC
>>> from sklearn.datasets import load_iris
>>> iris = load_iris()
>>> X, y = iris.data, iris.target
>>> X.shape
(150, 4)
>>> X_new = LinearSVC(C=0.01, penalty="l1", dual=False).fit_transform(X, y)
>>> X_new.shape
(150, 3)

With SVMs and logistic-regression, the parameter C controls the sparsity: the smaller C the fewer features selected. With Lasso, the higher the alpha parameter, the fewer features selected.

Examples:

L1-recovery and compressive sensing

For a good choice of alpha, the Lasso can fully recover the exact set of non-zero variables using only few observations, provided certain specific conditions are met. In particular, the number of samples should be “sufficiently large”, or L1 models will perform at random, where “sufficiently large” depends on the number of non-zero coefficients, the logarithm of the number of features, the amount of noise, the smallest absolute value of non-zero coefficients, and the structure of the design matrix X. In addition, the design matrix must display certain specific properties, such as not being too correlated.

There is no general rule to select an alpha parameter for recovery of non-zero coefficients. It can by set by cross-validation (LassoCV or LassoLarsCV), though this may lead to under-penalized models: including a small number of non-relevant variables is not detrimental to prediction score. BIC (LassoLarsIC) tends, on the opposite, to set high values of alpha.

Reference Richard G. Baraniuk “Compressive Sensing”, IEEE Signal Processing Magazine [120] July 2007http://dsp.rice.edu/files/cs/baraniukCSlecture07.pdf

1.13.4.2. Randomized sparse models

The limitation of L1-based sparse models is that faced with a group of very correlated features, they will select only one. To mitigate this problem, it is possible to use randomization techniques, reestimating the sparse model many times perturbing the design matrix or sub-sampling data and counting how many times a given regressor is selected.

RandomizedLasso implements this strategy for regression settings, using the Lasso, while RandomizedLogisticRegressionuses the logistic regression and is suitable for classification tasks. To get a full path of stability scores you can uselasso_stability_path.

Note that for randomized sparse models to be more powerful than standard F statistics at detecting non-zero features, the ground truth model should be sparse, in other words, there should be only a small fraction of features non zero.

Examples:

References:

1.13.5. Tree-based feature selection

Tree-based estimators (see the sklearn.tree module and forest of trees in the sklearn.ensemble module) can be used to compute feature importances, which in turn can be used to discard irrelevant features:

>>>

>>> from sklearn.ensemble import ExtraTreesClassifier
>>> from sklearn.datasets import load_iris
>>> iris = load_iris()
>>> X, y = iris.data, iris.target
>>> X.shape
(150, 4)
>>> clf = ExtraTreesClassifier()
>>> X_new = clf.fit(X, y).transform(X)
>>> clf.feature_importances_
array([ 0.04..., 0.05..., 0.4..., 0.4...])
>>> X_new.shape
(150, 2)

Examples:

1.13.6. Feature selection as part of a pipeline

Feature selection is usually used as a pre-processing step before doing the actual learning. The recommended way to do this in scikit-learn is to use a sklearn.pipeline.Pipeline:

clf = Pipeline([
('feature_selection', LinearSVC(penalty="l1")),
('classification', RandomForestClassifier())
])
clf.fit(X, y)

In this snippet we make use of a sklearn.svm.LinearSVC to evaluate feature importances and select the most relevant features. Then, a sklearn.ensemble.RandomForestClassifier is trained on the transformed output, i.e. using only relevant features. You can perform similar operations with the other feature selection methods and also classifiers that provide a way to evaluate feature importances of course. See the sklearn.pipeline.Pipeline examples for more details.

 
cross_validation模块
cross validation大概的意思是:对于原始数据我们要将其一部分分为train data,一部分分为test data。train data用于训练,test data用于测试准确率。在test data上测试的结果叫做validation error。将一个算法作用于一个原始数据,我们不可能只做出随机的划分一次train和test data,然后得到一个validation error,就作为衡量这个算法好坏的标准。因为这样存在偶然性。我们必须好多次的随机的划分train data和test data,分别在其上面算出各自的validation error。这样就有一组validation error,根据这一组validation error,就可以较好的准确的衡量算法的好坏。
cross validation是在数据量有限的情况下的非常好的一个evaluate performance的方法。
而对原始数据划分出train data和test data的方法有很多种,这也就造成了cross validation的方法有很多种。
 
sklearn中的cross validation模块,最主要的函数是如下函数:
sklearn.cross_validation.cross_val_score。他的调用形式是scores = cross_validation.cross_val_score(clf, raw data, raw target, cv=5, score_func=None)
参数解释:
clf是不同的分类器,可以是任何的分类器。比如支持向量机分类器。clf = svm.SVC(kernel='linear', C=1)
cv参数就是代表不同的cross validation的方法了。如果cv是一个int数字的话,并且如果提供了raw target参数,那么就代表使用StratifiedKFold分类方式,如果没有提供raw target参数,那么就代表使用KFold分类方式。
cross_val_score函数的返回值就是对于每次不同的的划分raw data时,在test data上得到的分类的准确率。至于准确率的算法可以通过score_func参数指定,如果不指定的话,是用clf默认自带的准确率算法。
还有其他的一些参数不是很重要。
cross_val_score具体使用例子见下:
>>> clf = svm.SVC(kernel='linear', C=1)
>>> scores = cross_validation.cross_val_score(
...    clf, raw data, raw target, cv=5)
...
>>> scores                                            
array([ 1.  ...,  0.96...,  0.9 ...,  0.96...,  1.        ])
 
除了刚刚提到的KFold以及StratifiedKFold这两种对raw data进行划分的方法之外,还有其他很多种划分方法。但是其他的划分方法调用起来和前两个稍有不同(但是都是一样的),下面以ShuffleSplit方法为例说明:
>>> n_samples = raw_data.shape[0]
>>> cv = cross_validation.ShuffleSplit(n_samples, n_iter=3,
...     test_size=0.3, random_state=0)
 
>>> cross_validation.cross_val_score(clf, raw data, raw target, cv=cv)
...                                                     
array([ 0.97...,  0.97...,  1.        ])
 
还有的其他划分方法如下:
cross_validation.Bootstrap
cross_validation.LeaveOneLabelOut
cross_validation.LeaveOneOut
cross_validation.LeavePLabelOut
cross_validation.LeavePOut
cross_validation.StratifiedShuffleSplit
 
他们的调用方法和ShuffleSplit是一样的,但是各自有各自的参数。至于这些方法具体的意义,见machine learning教材。
 
还有一个比较有用的函数是train_test_split
功能:从样本中随机的按比例选取train data和test data。调用形式为:
X_train, X_test, y_train, y_test = cross_validation.train_test_split(train_data, train_target, test_size=0.4, random_state=0)
test_size是样本占比。如果是整数的话就是样本的数量。random_state是随机数的种子。不同的种子会造成不同的随机采样结果。相同的种子采样结果相同。

3.1. Cross-validation: evaluating estimator performance

Learning the parameters of a prediction function and testing it on the same data is a methodological mistake: a model that would just repeat the labels of the samples that it has just seen would have a perfect score but would fail to predict anything useful on yet-unseen data. This situation is called overfitting. To avoid it, it is common practice when performing a (supervised) machine learning experiment to hold out part of the available data as a test set X_test, y_test. Note that the word “experiment” is not intended to denote academic use only, because even in commercial settings machine learning usually starts out experimentally.

In scikit-learn a random split into training and test sets can be quickly computed with the train_test_split helper function. Let’s load the iris data set to fit a linear support vector machine on it:

>>>

>>> import numpy as np
>>> from sklearn import cross_validation
>>> from sklearn import datasets
>>> from sklearn import svm >>> iris = datasets.load_iris()
>>> iris.data.shape, iris.target.shape
((150, 4), (150,))

We can now quickly sample a training set while holding out 40% of the data for testing (evaluating) our classifier:

>>>

>>> X_train, X_test, y_train, y_test = cross_validation.train_test_split(
... iris.data, iris.target, test_size=0.4, random_state=0) >>> X_train.shape, y_train.shape
((90, 4), (90,))
>>> X_test.shape, y_test.shape
((60, 4), (60,)) >>> clf = svm.SVC(kernel='linear', C=1).fit(X_train, y_train)
>>> clf.score(X_test, y_test)
0.96...

When evaluating different settings (“hyperparameters”) for estimators, such as the C setting that must be manually set for an SVM, there is still a risk of overfitting on the test set because the parameters can be tweaked until the estimator performs optimally. This way, knowledge about the test set can “leak” into the model and evaluation metrics no longer report on generalization performance. To solve this problem, yet another part of the dataset can be held out as a so-called “validation set”: training proceeds on the training set, after which evaluation is done on the validation set, and when the experiment seems to be successful, final evaluation can be done on the test set.

However, by partitioning the available data into three sets, we drastically reduce the number of samples which can be used for learning the model, and the results can depend on a particular random choice for the pair of (train, validation) sets.

A solution to this problem is a procedure called cross-validation (CV for short). A test set should still be held out for final evaluation, but the validation set is no longer needed when doing CV. In the basic approach, called k-fold CV, the training set is split into k smaller sets (other approaches are described below, but generally follow the same principles). The following procedure is followed for each of the k “folds”:

  • A model is trained using  of the folds as training data;
  • the resulting model is validated on the remaining part of the data (i.e., it is used as a test set to compute a performance measure such as accuracy).

The performance measure reported by k-fold cross-validation is then the average of the values computed in the loop. This approach can be computationally expensive, but does not waste too much data (as it is the case when fixing an arbitrary test set), which is a major advantage in problem such as inverse inference where the number of samples is very small.

3.1.1. Computing cross-validated metrics

The simplest way to use cross-validation is to call the cross_val_score helper function on the estimator and the dataset.

The following example demonstrates how to estimate the accuracy of a linear kernel support vector machine on the iris dataset by splitting the data, fitting a model and computing the score 5 consecutive times (with different splits each time):

>>>

>>> clf = svm.SVC(kernel='linear', C=1)
>>> scores = cross_validation.cross_val_score(
... clf, iris.data, iris.target, cv=5)
...
>>> scores
array([ 0.96..., 1. ..., 0.96..., 0.96..., 1. ])

The mean score and the 95% confidence interval of the score estimate are hence given by:

>>>

>>> print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
Accuracy: 0.98 (+/- 0.03)

By default, the score computed at each CV iteration is the score method of the estimator. It is possible to change this by using the scoring parameter:

>>>

>>> from sklearn import metrics
>>> scores = cross_validation.cross_val_score(clf, iris.data, iris.target,
... cv=5, scoring='f1_weighted')
>>> scores
array([ 0.96..., 1. ..., 0.96..., 0.96..., 1. ])

See The scoring parameter: defining model evaluation rules for details. In the case of the Iris dataset, the samples are balanced across target classes hence the accuracy and the F1-score are almost equal.

When the cv argument is an integer, cross_val_score uses the KFold or StratifiedKFold strategies by default, the latter being used if the estimator derives from ClassifierMixin.

It is also possible to use other cross validation strategies by passing a cross validation iterator instead, for instance:

>>>

>>> n_samples = iris.data.shape[0]
>>> cv = cross_validation.ShuffleSplit(n_samples, n_iter=3,
... test_size=0.3, random_state=0) >>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=cv)
...
array([ 0.97..., 0.97..., 1. ])

Data transformation with held out data

Just as it is important to test a predictor on data held-out from training, preprocessing (such as standardization, feature selection, etc.) and similar data transformations similarly should be learnt from a training set and applied to held-out data for prediction:

>>>

>>> from sklearn import preprocessing
>>> X_train, X_test, y_train, y_test = cross_validation.train_test_split(
... iris.data, iris.target, test_size=0.4, random_state=0)
>>> scaler = preprocessing.StandardScaler().fit(X_train)
>>> X_train_transformed = scaler.transform(X_train)
>>> clf = svm.SVC(C=1).fit(X_train_transformed, y_train)
>>> X_test_transformed = scaler.transform(X_test)
>>> clf.score(X_test_transformed, y_test)
0.9333...

Pipeline makes it easier to compose estimators, providing this behavior under cross-validation:

>>>

>>> from sklearn.pipeline import make_pipeline
>>> clf = make_pipeline(preprocessing.StandardScaler(), svm.SVC(C=1))
>>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=cv)
...
array([ 0.97..., 0.93..., 0.95...])

See Pipeline and FeatureUnion: combining estimators.

3.1.1.1. Obtaining predictions by cross-validation

The function cross_val_predict has a similar interface to cross_val_score, but returns, for each element in the input, the prediction that was obtained for that element when it was in the test set. Only cross-validation strategies that assign all elements to a test set exactly once can be used (otherwise, an exception is raised).

These prediction can then be used to evaluate the classifier:

>>>

>>> predicted = cross_validation.cross_val_predict(clf, iris.data,
... iris.target, cv=10)
>>> metrics.accuracy_score(iris.target, predicted)
0.966...

Note that the result of this computation may be slightly different from those obtained using cross_val_score as the elements are grouped in different ways.

The available cross validation iterators are introduced in the following section.

3.1.2. Cross validation iterators

The following sections list utilities to generate indices that can be used to generate dataset splits according to different cross validation strategies.

3.1.2.1. K-fold

KFold divides all the samples in  groups of samples, called folds (if , this is equivalent to the Leave One Out strategy), of equal sizes (if possible). The prediction function is learned using  folds, and the fold left out is used for test.

Example of 2-fold cross-validation on a dataset with 4 samples:

>>>

>>> import numpy as np
>>> from sklearn.cross_validation import KFold >>> kf = KFold(4, n_folds=2)
>>> for train, test in kf:
... print("%s %s" % (train, test))
[2 3] [0 1]
[0 1] [2 3]

Each fold is constituted by two arrays: the first one is related to the training set, and the second one to the test set. Thus, one can create the training/test sets using numpy indexing:

>>>

>>> X = np.array([[0., 0.], [1., 1.], [-1., -1.], [2., 2.]])
>>> y = np.array([0, 1, 0, 1])
>>> X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]

3.1.2.2. Stratified k-fold

StratifiedKFold is a variation of k-fold which returns stratified folds: each set contains approximately the same percentage of samples of each target class as the complete set.

Example of stratified 3-fold cross-validation on a dataset with 10 samples from two slightly unbalanced classes:

>>>

>>> from sklearn.cross_validation import StratifiedKFold

>>> labels = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
>>> skf = StratifiedKFold(labels, 3)
>>> for train, test in skf:
... print("%s %s" % (train, test))
[2 3 6 7 8 9] [0 1 4 5]
[0 1 3 4 5 8 9] [2 6 7]
[0 1 2 4 5 6 7] [3 8 9]

3.1.2.3. Leave-One-Out - LOO

LeaveOneOut (or LOO) is a simple cross-validation. Each learning set is created by taking all the samples except one, the test set being the sample left out. Thus, for  samples, we have  different training sets and  different tests set. This cross-validation procedure does not waste much data as only one sample is removed from the training set:

>>>

>>> from sklearn.cross_validation import LeaveOneOut

>>> loo = LeaveOneOut(4)
>>> for train, test in loo:
... print("%s %s" % (train, test))
[1 2 3] [0]
[0 2 3] [1]
[0 1 3] [2]
[0 1 2] [3]

Potential users of LOO for model selection should weigh a few known caveats. When compared with -fold cross validation, one builds  models from  samples instead of  models, where . Moreover, each is trained on  samples rather than . In both ways, assuming  is not too large and , LOO is more computationally expensive than -fold cross validation.

In terms of accuracy, LOO often results in high variance as an estimator for the test error. Intuitively, since  of the samples are used to build each model, models constructed from folds are virtually identical to each other and to the model built from the entire training set.

However, if the learning curve is steep for the training size in question, then 5- or 10- fold cross validation can overestimate the generalization error.

As a general rule, most authors, and empirical evidence, suggest that 5- or 10- fold cross validation should be preferred to LOO.

References:

3.1.2.4. Leave-P-Out - LPO

LeavePOut is very similar to LeaveOneOut as it creates all the possible training/test sets by removing  samples from the complete set. For  samples, this produces  train-test pairs. Unlike LeaveOneOut and KFold, the test sets will overlap for .

Example of Leave-2-Out on a dataset with 4 samples:

>>>

>>> from sklearn.cross_validation import LeavePOut

>>> lpo = LeavePOut(4, p=2)
>>> for train, test in lpo:
... print("%s %s" % (train, test))
[2 3] [0 1]
[1 3] [0 2]
[1 2] [0 3]
[0 3] [1 2]
[0 2] [1 3]
[0 1] [2 3]

3.1.2.5. Leave-One-Label-Out - LOLO

LeaveOneLabelOut (LOLO) is a cross-validation scheme which holds out the samples according to a third-party provided array of integer labels. This label information can be used to encode arbitrary domain specific pre-defined cross-validation folds.

Each training set is thus constituted by all the samples except the ones related to a specific label.

For example, in the cases of multiple experiments, LOLO can be used to create a cross-validation based on the different experiments: we create a training set using the samples of all the experiments except one:

>>>

>>> from sklearn.cross_validation import LeaveOneLabelOut

>>> labels = [1, 1, 2, 2]
>>> lolo = LeaveOneLabelOut(labels)
>>> for train, test in lolo:
... print("%s %s" % (train, test))
[2 3] [0 1]
[0 1] [2 3]

Another common application is to use time information: for instance the labels could be the year of collection of the samples and thus allow for cross-validation against time-based splits.

Warning

Contrary to StratifiedKFoldthe ``labels`` of :class:`LeaveOneLabelOut` should not encode the target class to predict: the goal of StratifiedKFold is to rebalance dataset classes across the train / test split to ensure that the train and test folds have approximately the same percentage of samples of each class while LeaveOneLabelOut will do the opposite by ensuring that the samples of the train and test fold will not share the same label value.

3.1.2.6. Leave-P-Label-Out

LeavePLabelOut is similar as Leave-One-Label-Out, but removes samples related to  labels for each training/test set.

Example of Leave-2-Label Out:

>>>

>>> from sklearn.cross_validation import LeavePLabelOut

>>> labels = [1, 1, 2, 2, 3, 3]
>>> lplo = LeavePLabelOut(labels, p=2)
>>> for train, test in lplo:
... print("%s %s" % (train, test))
[4 5] [0 1 2 3]
[2 3] [0 1 4 5]
[0 1] [2 3 4 5]

3.1.2.7. Random permutations cross-validation a.k.a. Shuffle & Split

ShuffleSplit

The ShuffleSplit iterator will generate a user defined number of independent train / test dataset splits. Samples are first shuffled and then split into a pair of train and test sets.

It is possible to control the randomness for reproducibility of the results by explicitly seeding the random_state pseudo random number generator.

Here is a usage example:

>>>

>>> ss = cross_validation.ShuffleSplit(5, n_iter=3, test_size=0.25,
... random_state=0)
>>> for train_index, test_index in ss:
... print("%s %s" % (train_index, test_index))
...
[1 3 4] [2 0]
[1 4 3] [0 2]
[4 0 2] [1 3]

ShuffleSplit is thus a good alternative to KFold cross validation that allows a finer control on the number of iterations and the proportion of samples in on each side of the train / test split.

3.1.2.8. Predefined Fold-Splits / Validation-Sets

For some datasets, a pre-defined split of the data into training- and validation fold or into several cross-validation folds already exists. Using PredefinedSplit it is possible to use these folds e.g. when searching for hyperparameters.

For example, when using a validation set, set the test_fold to 0 for all samples that are part of the validation set, and to -1 for all other samples.

3.1.2.9. See also

StratifiedShuffleSplit is a variation of ShuffleSplit, which returns stratified splits, i.e which creates splits by preserving the same percentage for each target class as in the complete set.

3.1.3. A note on shuffling

If the data ordering is not arbitrary (e.g. samples with the same label are contiguous), shuffling it first may be essential to get a meaningful cross- validation result. However, the opposite may be true if the samples are not independently and identically distributed. For example, if samples correspond to news articles, and are ordered by their time of publication, then shuffling the data will likely lead to a model that is overfit and an inflated validation score: it will be tested on samples that are artificially similar (close in time) to training samples.

Some cross validation iterators, such as KFold, have an inbuilt option to shuffle the data indices before splitting them. Note that:

  • This consumes less memory than shuffling the data directly.
  • By default no shuffling occurs, including for the (stratified) K fold cross- validation performed by specifying cv=some_integerto cross_val_score, grid search, etc. Keep in mind that train_test_split still returns a random split.
  • The random_state parameter defaults to None, meaning that the shuffling will be different every time KFold(..., shuffle=True)is iterated. However, GridSearchCV will use the same shuffling for each set of parameters validated by a single call to its fitmethod.
  • To ensure results are repeatable (on the same platform), use a fixed value for random_state.

3.1.4. Cross validation and model selection

Cross validation iterators can also be used to directly perform model selection using Grid Search for the optimal hyperparameters of the model. This is the topic if the next section: Grid Search: Searching for estimator parameters.

Python scikit-learn机器学习工具包学习笔记的更多相关文章

  1. Python scikit-learn机器学习工具包学习笔记:feature_selection模块

    sklearn.feature_selection模块的作用是feature selection,而不是feature extraction.   Univariate feature selecti ...

  2. Python 日期时间处理模块学习笔记

    来自:标点符的<Python 日期时间处理模块学习笔记> Python的时间处理模块在日常的使用中用的不是非常的多,但是使用的时候基本上都是要查资料,还是有些麻烦的,梳理下,便于以后方便的 ...

  3. TensorFlow机器学习框架-学习笔记-001

    # TensorFlow机器学习框架-学习笔记-001 ### 测试TensorFlow环境是否安装完成-----------------------------```import tensorflo ...

  4. 《Think Python》第17章学习笔记

    目录 <Think Python>第17章学习笔记 17.1 面向对象的特性(Object-oriented features) 17.2 打印对象(Printing objects) 1 ...

  5. 《Think Python》第16章学习笔记

    目录 <Think Python>第16章学习笔记 16.1 Time 16.2 纯函数(Pure functions) 16.3 修改器(Modifiers) 16.4 原型 vs. 方 ...

  6. 《Think Python》第15章学习笔记

    目录 <Think Python>第15章学习笔记 15.1 程序员定义的类型(Programmer-defined types) 15.2 属性(Attributes) 15.3 矩形( ...

  7. The Road to learn React书籍学习笔记(第二章)

    The Road to learn React书籍学习笔记(第二章) 组件的内部状态 组件的内部状态也称为局部状态,允许保存.修改和删除在组件内部的属性,使用ES6类组件可以在构造函数中初始化组件的状 ...

  8. The Road to learn React书籍学习笔记(第三章)

    The Road to learn React书籍学习笔记(第三章) 代码详情 声明周期方法 通过之前的学习,可以了解到ES6 类组件中的生命周期方法 constructor() 和 render() ...

  9. Python 图片转字符画 学习笔记

    Python 图片转字符画 学习笔记 标签(空格分隔): Python 声明:此文章和所有代码是学习笔记,非原创,原文教程地址:https://www.shiyanlou.com/courses/37 ...

随机推荐

  1. 《Google软件测试之道》【PDF】下载

    <Google软件测试之道>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230382198 内容介绍 每天,Google都要测试和发布 ...

  2. 微信小程序教学第三章第三节(含视频):小程序中级实战教程:视图与数据关联

    § 视图与数据关联 本文配套视频地址: https://v.qq.com/x/page/z0554wyswib.html 开始前请把 ch3-3 分支中的 code/ 目录导入微信开发工具 首先 首先 ...

  3. 通过SQL创建一个有主键自动递增有默认值不为空有注释的表

    -- create database db_std_mgr_sys; use db_std_mgr_sys; create table student( std_id bigint not null ...

  4. Servlet小总结

    Servlet Servlet(服务器端小程序)是使用Java语言编写的服务器端程序,像JSP一样,生成动态的Web页.Servlet主要运行在服务器端,并由服务器调用执行. Servlet处理的基本 ...

  5. echarts中如何使用timeline组件

    1.吃碗面 这里关于echarts3 官网的示例我不得不吐槽一下,逼格真高!一小部分示例动不动数据就是国家统计局搞出来的,你脸真大.当然他们做的示例的确是很好,这一点毫无疑问.当我看了echarts3 ...

  6. 用js筛选数据排序

    题目 参考以下示例代码,页面加载后,将提供的空气质量数据数组,按照某种逻辑(比如空气质量大于60)进行过滤筛选,最后将符合条件的数据按照一定的格式要求显示 <!DOCTYPE html> ...

  7. JaCoCo 代码覆盖率工具(基于Maven+TestNG)

    JaCoco是一个代码覆盖率库. 官方网站:http://www.jacoco.org/ 安装: 以 Maven(http://www.testclass.net/maven/) 安装为例: < ...

  8. Linux(CentOS6.5)下编译安装MySQL Community Server 5.7.12

      组件 官方网站 直接下载地址 备注 mysql http://dev.mysql.com/downloads/mysql/ http://mirrors.sohu.com/mysql/MySQL- ...

  9. 【http转https】其之二:申请Let's Encrypt颁发SSL证书

    文:铁乐猫 2017年1月12日 申请Let's Encrypt颁发SSL证书 由 ISRG(Internet Security Research Group,互联网安全研究小组)提供服务, ISRG ...

  10. Linux小记

    一.在vim中如何查看正在编辑的文件名 在正常模式下: :f 或 CTRL+G 查看文件的路径 用:!pwd 可以看当前的详细路径. 二.crontab 在crontab中, 命令crontab -e ...