scikit-learn 1 cheatsheet

scikit-learn 1: Data and splitting

4 common scikit-learn 1 tasks.

Install scikit-learn

Install scikit-learn, which needs NumPy and SciPy (pip installs them for you).

pip install scikit-learn

Load a built-in dataset

Load a small practice dataset as a feature matrix X and target vector y.

from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)

Generate a synthetic dataset

Create a random classification problem, good for testing code quickly.

from sklearn.datasets import make_classification

X, y = make_classification(n_samples=500, n_features=8, n_informative=4, random_state=42)

Split into train and test sets

Hold out 20% of the data for testing. stratify keeps class proportions, and random_state makes it repeatable.

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, stratify=y, random_state=42)

Was this page helpful?