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
-
Features: are the input variables used to train the model in the dataset. In the example above,
Xis the feature matrix, containing all input variables. -
Labels: are the target output of the machine learning model. In supervised learning, labels are the results we want the model to predict. In the example above,
yis the label or target vector, containing the class of each sample.
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
)
- The above code calls
train_test_splitthe function and assigns the result to four variables:X_train,X_test,y_trainandy_test. Xandyis passed intotrain_test_splitthe function's parameters, which represent the feature dataset and target variable (label) respectively. UsuallyXis a 2D array,yis a one-dimensional array.test_size=0.3The parameter specifies that the test set size should be 30% of the original dataset. This means 70% of the data is used as the training set and the remaining 30% as the test set.random_state=42The parameter is a random number seed used to ensure the same result each time the dataset is split. This is very useful in experiments and model validation because it ensures reproducibility.
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.
- Classification: assign data points to predefined categories. For example, determining whether an email is spam or not.
- Regression: predict continuous-valued output. For example, predicting house prices, temperature, etc.
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.
- Clustering: group data so that data within the same group are similar. Common clustering algorithms include K-Means, DBSCAN , etc.
- Dimensionality reduction: reduce the number of features in the data, usually for data compression or visualization. Common dimensionality reduction methods include PCA(Principal Component Analysis) and t-SNE(t-distributed Stochastic Neighbor Embedding), etc.
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
(
"Cross-validation scores:"
,
scores
)
Common evaluation metrics
Evaluation metrics for classification tasks:
- Accuracy: the proportion of correctly predicted samples among all samples.
- Precision: among positive-class predictions, the proportion that are actually positive.
- Recall: among actual positive-class samples, the proportion correctly predicted.
- F1 score: the harmonic mean of precision and recall.
Example
from
sklearn.
metrics
import
accuracy_score
,
classification_report
(
"Accuracy:"
,
accuracy_score
(
y_test
,
y_pred
)
)
(
"Classification Report:\n"
,
classification_report
(
y_test
,
y_pred
)
)
Evaluation metrics for regression tasks:
- Mean Squared Error (MSE): the average of the squared differences between predicted and actual values.
- Coefficient of Determination (R²): measures the model's ability to explain the variation in the data.
Example
from
sklearn.
metrics
import
mean_squared_error
,
r2_score
(
"MSE:"
,
mean_squared_error
(
y_test
,
y_pred
)
)
(
"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
)
(
"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
)
(
"Best parameters:"
,
random_search.
best_params_
)