Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Sklearn Basic Concepts

Sklearn Basic Concepts

When using Sklearn for machine learning, you need to understand some basic concepts.

Sklearn provides a unified and concise API to implement various machine learning algorithms and pipelines, helping us quickly accomplish machine learning tasks.

Next, we expand on the following concepts:Data representation, model types, preprocessing methods, evaluation metrics, model tuning, etc.


1. Data representation: datasets and features

A dataset is one of the most basic concepts in Sklearn.

The core task of machine learning is to learn patterns from data, and how data is represented is crucial.

Dataset

In scikit-learn, data is usually represented by two main objects: the feature matrix and the target vector.

Feature matrix: each row represents a data sample and each column represents a feature (i.e., an input variable). It is a two-dimensional array or matrix, usually stored as a NumPy array or pandas DataFrame.

Suppose we have 3 samples, each with 2 features.

Example

import

numpy

as

np

X

=

np.

array

(

[

[

1.0

,

2.0

]

,

[

2.0

,

3.0

]

,

[

3.0

,

4.0

]

]

)

Target vector: it represents the target of each sample (i.e., the output label), usually a one-dimensional array.

For example, in a classification task, the target is the class label of each sample.

The corresponding target vector:



y = np.array([0, 1, 0])  # 0 类别和 1 类别

Features and labels

Dataset splitting

In practice, you usually need to split the dataset into a training set and a test set.

scikit-learn provides a convenient function train_test_split() to do this:

Example

from

sklearn.

model_selection

import

train_test_split

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X

,

y

,

test_size

=

0.3

,

random_state

=

42

)


2. Models and algorithms

Supervised learning and unsupervised learning

In scikit-learn, machine learning models are roughly divided into two categories: supervised learning and unsupervised learning.

Supervised learning: in supervised learning, the model learns from labeled data during training, and these labels are the results we want the model to predict.

Common supervised learning tasks include classification and regression.

Use a decision tree for a classification task:

Example

from

sklearn.

tree

import

DecisionTreeClassifier

clf

=

DecisionTreeClassifier

(

)

clf.

fit

(

X_train

,

y_train

)

y_pred

=

clf.

predict

(

X_test

)

Unsupervised learning: unsupervised learning means there are no label data, and the model learns only from the features of the input data itself.

Common unsupervised learning tasks include clustering and dimensionality reduction.

Use K-Means clustering:

Example

from

sklearn.

cluster

import

KMeans

kmeans

=

KMeans

(

n_clusters

=

3

)

kmeans.

fit

(

X_train

)

y_pred

=

kmeans.

predict

(

X_test

)

Preprocessing and feature engineering

Before using scikit-learn for machine learning, you usually need to preprocess the data, which includes the following common tasks:

1. Standardization: unify the scale of features so that each feature has zero mean and unit variance.

Example

from

sklearn.

preprocessing

import

StandardScaler

scaler

=

StandardScaler

(

)

X_scaled

=

scaler.

fit_transform

(

X

)

2. Normalization: scale feature values to a fixed range (usually 0 to 1).

Example

from

sklearn.

preprocessing

import

MinMaxScaler

scaler

=

MinMaxScaler

(

)

X_normalized

=

scaler.

fit_transform

(

X

)

3. Categorical variable encoding: convert categorical data into numeric data (such as one-hot encoding).


3. Model evaluation and validation

After training a machine learning model, you must evaluate its performance to ensure its generalization ability.

scikit-learn provides some tools for evaluating model performance.

Cross-validation

Cross-validation is a common model evaluation method, especially when the amount of data is limited.

By splitting the data into multiple subsets, using one subset as the validation set each time and the rest as the training set, and repeating training and evaluation multiple times, the model's average performance is finally computed.

Example

from

sklearn.

model_selection

import

cross_val_score

scores

=

cross_val_score

(

clf

,

X

,

y

,

cv

=

5

)

 

5-fold cross-validation

print

(

"Cross-validation scores:"

,

scores

)

Common evaluation metrics

Evaluation metrics for classification tasks:

Example

from

sklearn.

metrics

import

accuracy_score

,

classification_report

print

(

"Accuracy:"

,

accuracy_score

(

y_test

,

y_pred

)

)

print

(

"Classification Report:\n"

,

classification_report

(

y_test

,

y_pred

)

)

Evaluation metrics for regression tasks:

Example

from

sklearn.

metrics

import

mean_squared_error

,

r2_score

print

(

"MSE:"

,

mean_squared_error

(

y_test

,

y_pred

)

)

print

(

"R²:"

,

r2_score

(

y_test

,

y_pred

)

)

4. Model Selection and Tuning

Grid Search

Grid Searchis a commonly used hyperparameter tuning method that searches for the best hyperparameter combination by iterating through all possible parameter combinations.

Example

from

sklearn.

model_selection

import

GridSearchCV

param_grid

=

{

'max_depth'

:

[

3

,

5

,

7

]

,

'min_samples_split'

:

[

2

,

5

,

10

]

}

grid_search

=

GridSearchCV

(

DecisionTreeClassifier

(

)

,

param_grid

,

cv

=

5

)

grid_search.

fit

(

X_train

,

y_train

)

print

(

"Best parameters:"

,

grid_search.

best_params_

)

Random Search

Random Searchis a method that searches for the optimal hyperparameters by randomly selecting combinations of hyperparameters, and it is more efficient than grid search.

Example

from

sklearn.

model_selection

import

RandomizedSearchCV

from

scipy.

stats

import

randint

param_dist

=

{

'max_depth'

:

[

3

,

5

,

7

]

,

'min_samples_split'

: randint

(

2

,

10

)

}

random_search

=

RandomizedSearchCV

(

DecisionTreeClassifier

(

)

,

param_dist

,

n_iter

=

10

,

cv

=

5

)

random_search.

fit

(

X_train

,

y_train

)

print

(

"Best parameters:"

,

random_search.

best_params_

)