0% found this document useful (0 votes)
14 views5 pages

Train-Test Split in Scikit-Learn

This document describes the sklearn.model_selection.train_test_split function which splits arrays or matrices into random train and test subsets. It allows inputting data, labels, and options to split the data for model training and testing. Examples are given showing how to split sample data for use in machine learning models.

Uploaded by

priyanshu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

Train-Test Split in Scikit-Learn

This document describes the sklearn.model_selection.train_test_split function which splits arrays or matrices into random train and test subsets. It allows inputting data, labels, and options to split the data for model training and testing. Examples are given showing how to split sample data for use in machine learning models.

Uploaded by

priyanshu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

11/7/2019 sklearn.model_selection.train_test_split — scikit-learn 0.21.

3 documentation

Home Installation
Documentation
Examples

sklearn.model_selection.train_test_split

sklearn.model_selection.train_test_split(*arrays, **options) [source]


»

Split arrays or matrices into random train and test subsets

Quick utility that wraps input validation and next(ShuffleSplit().split(X, y)) and application to input
data into a single call for splitting (and optionally subsampling) data in a oneliner.

Read more in the User Guide.


Parameters: *arrays : sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse matrices or pandas
dataframes.

test_size : float, int or None, optional (default=None)


If float, should be between 0.0 and 1.0 and represent the proportion of the dataset
to include in the test split. If int, represents the absolute number of test samples. If
None, the value is set to the complement of the train size. If train_size is also
None, it will be set to 0.25.

train_size : float, int, or None, (default=None)


If float, should be between 0.0 and 1.0 and represent the proportion of the dataset
to include in the train split. If int, represents the absolute number of train samples. If
None, the value is automatically set to the complement of the test size.

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 [Link].

shuffle : boolean, optional (default=True)


Whether or not to shuffle the data before splitting. If shuffle=False then stratify must
be None.

stratify : array-like or None (default=None)


If not None, data is split in a stratified fashion, using this as the class labels.

Returns: splitting : list, length=2 * len(arrays)


List containing train-test split of inputs.

New in version 0.16: If the input is sparse, the output will be a


[Link].csr_matrix. Else, output type is the same as the input type.
Previous Next
[Link] 1/5
11/7/2019 sklearn.model_selection.train_test_split — scikit-learn 0.21.3 documentation

Examples
>>> import numpy as np >>>
>>> from sklearn.model_selection import train_test_split
>>> X, y = [Link](10).reshape((5, 2)), range(5)
>>> X
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
» >>> list(y)
[0, 1, 2, 3, 4]

>>> X_train, X_test, y_train, y_test = train_test_split( >>>


... X, y, test_size=0.33, random_state=42)
...
>>> X_train
array([[4, 5],
[0, 1],
[6, 7]])
>>> y_train
[2, 0, 3]
>>> X_test
array([[2, 3],
[8, 9]])
>>> y_test
[1, 4]

>>> train_test_split(y, shuffle=False) >>>


[[0, 1, 2], [3, 4]]

Examples using sklearn.model_selection.train_test_split

Faces recognition example Prediction Latency Probability Calibration


using eigenfaces and curves
SVMs

Probability calibration of
Previous Classifier comparison Column Transformer with Next
[Link] 2/5
11/7/2019 sklearn.model_selection.train_test_split — scikit-learn 0.21.3 documentation

classifiers Mixed Types

Effect of transforming the Comparing random forests Early stopping of Gradient


targets in regression model and the multi-output meta Boosting
estimator

Feature transformations Gradient Boosting Out-of- Pipeline Anova SVM


with ensembles of trees Bag estimates

Comparing various online MNIST classfification using Multiclass sparse logisitic


solvers multinomial logistic + L1 regression on
newgroups20

Previous Next
[Link] 3/5
11/7/2019 sklearn.model_selection.train_test_split — scikit-learn 0.21.3 documentation

Early stopping of Parameter estimation Confusion matrix


Stochastic Gradient using grid search with
Descent cross-validation

Receiver Operating Precision-Recall Classifier Chain


Characteristic (ROC)

Comparing Nearest Dimensionality Reduction Restricted Boltzmann


Neighbors with and without with Neighborhood Machine features for digit
Neighborhood Components Analysis classification
Components Analysis

Varying regularization in Using FunctionTransformer Importance of Feature


Multi-layer Perceptron to select columns Scaling

Previous Next
[Link] 4/5
11/7/2019 sklearn.model_selection.train_test_split — scikit-learn 0.21.3 documentation

Map data to a normal Feature discretization Understanding the


distribution decision tree structure

Previous Next
[Link] 5/5

Common questions

Powered by AI

GridSearchCV is effective for hyperparameter tuning as it systematically evaluates all possible combinations of specified parameter values using cross-validation. This exhaustive search reduces the risk of missing the optimal parameter set compared to manual tuning, which relies heavily on the user's intuition and could overlook better settings. However, GridSearchCV can be computationally expensive, especially with large datasets or extensive parameter grids, but it ultimately provides a more robust and unbiased process for finding the best hyperparameters .

A confusion matrix provides comprehensive insights into classifier performance by displaying the count of true positive, true negative, false positive, and false negative predictions. It allows for the calculation of various metrics such as precision, recall, and F1-score, which provide a more nuanced understanding of the model's robustness, particularly for imbalanced datasets where accuracy alone may be misleading. This matrix aids in spotting specific weaknesses, like a model's tendency to misclassify particular classes, and guides further model refinement .

Feature scaling impacts model performance by ensuring that all input features contribute proportionately to the distance calculations used in many algorithms. For instance, models like k-Nearest Neighbors (KNN) and Support Vector Machines (SVM) rely on distance measures, making unscaled features dominate the model's behavior. Scaling can lead to faster convergence and improved model accuracy because algorithms interpret features more uniformly. Moreover, it prevents numerical precision errors in gradient descent-based optimizers, achieving more stable and reliable results .

Not shuffling data before splitting with 'train_test_split' can lead to biased training and testing datasets if the data is ordered in a way that reflects patterns or time sequences. For instance, in time-series data, earlier data may have fundamentally different distributions than later data, resulting in a train-test split that does not generalize well. This can significantly impact the model's ability to learn and generalize effectively, as it may overfit the training patterns and underperform on the test data .

The 'random_state' parameter in the 'train_test_split' function influences reproducibility by setting a seed for the random number generator, ensuring that the split of data into training and testing sets is the same each time the code is run. If 'random_state' is set to an integer value, this seed guarantees that the data splits are consistent across different runs, making results reproducible. If it's set to None, different splits may occur with each execution, as the state is based on the current time or system state .

Stratified sampling with 'train_test_split' is preferred when you want to maintain the same proportion of each class label in the training and test datasets. This is particularly important in imbalanced datasets, where certain classes are underrepresented. Using stratified sampling ensures that the class distribution is consistent across both datasets, which can lead to more robust and unbiased model training and evaluation .

Altering the 'test_size' parameter in 'train_test_split' affects the proportion of data reserved for model evaluation. A smaller test size might not provide a sufficiently representative sample to accurately gauge model performance, leading to overfitting detection. Conversely, too large a test size could result in insufficient data for training, limiting the model's ability to learn patterns effectively. Thus, it is crucial to balance 'test_size' to ensure enough data is available for both effective model training and reliable performance evaluation .

A 'ColumnTransformer' enhances preprocessing by allowing specific transformations to be applied to different types of features within a dataset. It processes numerical and categorical data using methods best suited for each type, such as scaling numerical data and one-hot encoding categorical data. This targeted approach to preprocessing improves model performance by ensuring each feature type is prepared optimally without manually separating and handling different data types, making the preprocessing pipeline more streamlined and efficient .

The 'train_test_split' function accepts various data types such as lists, numpy arrays, scipy-sparse matrices, and pandas dataframes. Using numpy arrays or pandas dataframes can benefit from their efficient data manipulation capabilities and compatibility with other scientific libraries. Scipy-sparse matrices are advantageous for handling large datasets with many zero elements, optimizing memory usage. However, using lists may increase the complexity and decrease the efficiency of the operation, especially with larger datasets. The choice of input type affects computational efficiency, ease of data manipulation, and memory usage, impacting the preprocessing steps in the machine learning pipeline .

Early stopping in Gradient Boosting helps prevent overfitting by terminating the training process once the model's performance ceases to improve on a held-out validation dataset. This allows the algorithm to stop adding new boosting iterations that do not contribute to better generalization, saving computational resources and retaining a simpler, more interpretable model. As a result, early stopping can lead to a more efficient training process and often results in improved performance on unseen data .

You might also like