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

Sklearn Application Cases

Sklearn Application Cases

The Iris Dataset is one of the most classic introductory datasets in machine learning.

The Iris dataset contains three species of iris (Setosa, Versicolor, Virginica), each with 4 features: sepal length, sepal width, petal length, and petal width.

Our next task is to predict the species of iris based on these features.

This chapter's case will cover steps such as data loading, visualization, feature selection, data preprocessing, building a classification model, model evaluation, and optimization.


1. Data Loading and Visualization

Data loading

First, load the Iris dataset; scikit-learn provides an interface to load the Iris dataset directly.

Example

from

sklearn.

datasets

import

load_iris

import

pandas

as

pd

Load the Iris dataset

data

=

load_iris

(

)

Convert to a DataFrame for easy viewing

df

=

pd.

DataFrame

(

data.

data

,

columns

=

data.

feature_names

)

df

[

'target'

]

=

data.

target

df

[

'species'

]

=

df

[

'target'

]

.

apply

(

lambda

x: data.

target_names

[

x

]

)

View the first few rows of data

print

(

df.

head

(

)

)

Output result:



   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  target species

0                 5.1               3.5                1.4               0.2       0   setosa

1                 4.9               3.0                1.4               0.2       0   setosa

2                 4.7               3.2                1.3               0.2       0   setosa

3                 4.6               3.1                1.5               0.2       0   setosa

4                 5.0               3.6                1.4               0.2       0   setosa

At this point, the data has been loaded successfully, and we can see the features and corresponding flower species of each record.

Data visualization

To better understand the data, we can view the relationships between different features through visualization; we can use the matplotlib and seaborn libraries for visualization.

Example

from

sklearn.

datasets

import

load_iris

import

pandas

as

pd

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

Load the Iris dataset

data

=

load_iris

(

)

Convert to a DataFrame for easy viewing

df

=

pd.

DataFrame

(

data.

data

,

columns

=

data.

feature_names

)

df

[

'target'

]

=

data.

target

df

[

'species'

]

=

df

[

'target'

]

.

apply

(

lambda

x: data.

target_names

[

x

]

)

Plot the relationships between features

sns.

pairplot

(

df

,

hue

=

"species"

)

plt.

show

(

)

pairplot draws a scatter plot matrix between features, using different colors to mark different iris species, which helps us understand the distribution of each feature and their relationships.

The displayed figure is as follows:

Heatmap to visualize correlations between features

Through a heatmap we can view the correlations between features; strong correlations can help us make better choices when modeling.

Example

from

sklearn.

datasets

import

load_iris

import

pandas

as

pd

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

Load the Iris dataset

data

=

load_iris

(

)

Convert to a DataFrame for easy viewing

df

=

pd.

DataFrame

(

data.

data

,

columns

=

data.

feature_names

)

df

[

'target'

]

=

data.

target

df

[

'species'

]

=

df

[

'target'

]

.

apply

(

lambda

x: data.

target_names

[

x

]

)

Plot the relationships between features

correlation_matrix

=

df.

drop

(

columns

=

[

'target'

,

'species'

]

)

.

corr

(

)

sns.

heatmap

(

correlation_matrix

,

annot

=

True

,

cmap

=

"coolwarm"

,

fmt

=

".2f"

)

plt.

title

(

"Correlation Heatmap"

)

plt.

show

(

)

The displayed figure is as follows:


2. Feature Selection and Data Preprocessing

Data preprocessing

In machine learning, data preprocessing is a very important step.

For the Iris dataset, the feature values are already numerical data and require little preprocessing. However, we can standardize the data to improve model training effectiveness.

Example

from

sklearn.

preprocessing

import

StandardScaler

Extract features and labels

X

=

df.

drop

(

columns

=

[

'target'

,

'species'

]

)

y

=

df

[

'target'

]

Standardize features

scaler

=

StandardScaler

(

)

X_scaled

=

scaler.

fit_transform

(

X

)

The purpose of standardization is to make each feature have a mean of 0 and a variance of 1, which is very important for some distance-based models (such as KNN, SVM).

Feature selection

Although the Iris dataset's features are relatively simple, in real problems we sometimes need to reduce feature dimensions through feature selection to improve model performance.

We can use methods such as SelectKBest or Recursive Feature Elimination (RFE).

For example, use SelectKBest to select the 2 features most correlated with the labels:

Example

from

sklearn.

feature_selection

import

SelectKBest

,

f_classif

Use the chi-square test to select the 2 most relevant features

selector

=

SelectKBest

(

f_classif

,

k

=

2

)

X_new

=

selector.

fit_transform

(

X_scaled

,

y

)

Print the selected features

selected_features

=

selector.

get_support

(

indices

=

True

)

print

(

"Selected features:"

,

X.

columns

[

selected_features

]

)

This will select the 2 features most correlated with the target label.


3. Build a Classification Model: Use Decision Tree or SVM for Classification

Use a decision tree classifier

We will first try using a Decision Tree model for classification.

Example

from

sklearn.

model_selection

import

train_test_split

from

sklearn.

tree

import

DecisionTreeClassifier

from

sklearn.

metrics

import

accuracy_score

Split the dataset

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X_scaled

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Initialize the decision tree classifier

model_dt

=

DecisionTreeClassifier

(

random_state

=

42

)

Train the model

model_dt.

fit

(

X_train

,

y_train

)

Predict

y_pred_dt

=

model_dt.

predict

(

X_test

)

Evaluate the model

accuracy_dt

=

accuracy_score

(

y_test

,

y_pred_dt

)

print

(

f

"Decision Tree Accuracy: {accuracy_dt:.4f}"

)

Use Support Vector Machine (SVM) for classification

Next, we can try using Support Vector Machine (SVM) for classification.

Example

from

sklearn.

svm

import

SVC

Initialize the SVM classifier

model_svm

=

SVC

(

kernel

=

'linear'

,

random_state

=

42

)

Train the model

model_svm.

fit

(

X_train

,

y_train

)

Predict

y_pred_svm

=

model_svm.

predict

(

X_test

)

Evaluate the model

accuracy_svm

=

accuracy_score

(

y_test

,

y_pred_svm

)

print

(

f

"SVM Accuracy: {accuracy_svm:.4f}"

)


4. Evaluate the Model and Optimize

Model evaluation

Besides accuracy, we can also use other evaluation metrics such as confusion matrix, precision, recall, and F1 score.

Example

from

sklearn.

metrics

import

classification_report

,

confusion_matrix

Confusion matrix

cm

=

confusion_matrix

(

y_test

,

y_pred_dt

)

print

(

"Confusion Matrix (Decision Tree):"

)

print

(

cm

)

Precision, recall, F1 score

report

=

classification_report

(

y_test

,

y_pred_dt

)

print

(

"Classification Report (Decision Tree):"

)

print

(

report

)

Grid search tuning

To optimize the model, we can use grid search (GridSearchCV) to tune the model's hyperparameters and find the best parameter combination.

Example

from

sklearn.

model_selection

import

GridSearchCV

Define the parameter grid for the decision tree

param_grid

=

{

   

'max_depth'

:

[

3

,

5

,

10

,

None

]

,

   

'min_samples_split'

:

[

2

,

5

,

10

]

,

   

'min_samples_leaf'

:

[

1

,

2

,

4

]

}

Initialize GridSearchCV

grid_search

=

GridSearchCV

(

estimator

=

DecisionTreeClassifier

(

random_state

=

42

)

,

param_grid

=

param_grid

,

cv

=

5

)

Train the grid search

grid_search.

fit

(

X_train

,

y_train

)

Get the best parameters and best model

print

(

"Best Parameters:"

,

grid_search.

best_params_

)

best_model

=

grid_search.

best_estimator_

Predict and evaluate

y_pred_optimized

=

best_model.

predict

(

X_test

)

accuracy_optimized

=

accuracy_score

(

y_test

,

y_pred_optimized

)

print

(

f

"Optimized Decision Tree Accuracy: {accuracy_optimized:.4f}"

)

Through grid search, we can find the decision tree parameters most suitable for the current data and improve the model's prediction accuracy.

Cross-validation

To further evaluate the model's stability, we can use cross-validation to assess the model's performance.

Example

from

sklearn.

model_selection

import

cross_val_score

Perform 5-fold cross-validation

cross_val_scores

=

cross_val_score

(

best_model

,

X_scaled

,

y

,

cv

=

5

)

print

(

f

"Cross-validation Scores: {cross_val_scores}"

)

print

(

f

"Mean CV Accuracy: {cross_val_scores.mean():.4f}"

)

Cross-validation helps us evaluate the model's performance on different data subsets and avoid overfitting.


5. Complete Code

The following is a complete code example covering the loading of the Iris dataset, data preprocessing, feature selection, building a classification model, model evaluation, and optimization. We will use decision tree and SVM classifiers and optimize the model hyperparameters via grid search.

Example

Import the necessary libraries

import

numpy

as

np

import

pandas

as

pd

import

seaborn

as

sns

import

matplotlib.

pyplot

as

plt

from

sklearn.

datasets

import

load_iris

from

sklearn.

model_selection

import

train_test_split

,

GridSearchCV

,

cross_val_score

from

sklearn.

preprocessing

import

StandardScaler

from

sklearn.

tree

import

DecisionTreeClassifier

from

sklearn.

svm

import

SVC

from

sklearn.

metrics

import

accuracy_score

,

classification_report

,

confusion_matrix

1. Data Loading

Load the Iris dataset

data

=

load_iris

(

)

Convert to a DataFrame for easy viewing

df

=

pd.

DataFrame

(

data.

data

,

columns

=

data.

feature_names

)

df

[

'target'

]

=

data.

target

df

[

'species'

]

=

df

[

'target'

]

.

apply

(

lambda

x: data.

target_names

[

x

]

)

View the first few rows of data

print

(

"Data preview:"

)

print

(

df.

head

(

)

)

2. Data Visualization

Plot the relationships between features

sns.

pairplot

(

df

,

hue

=

"species"

)

plt.

show

(

)

Draw a heatmap to view correlations between features

correlation_matrix

=

df.

drop

(

columns

=

[

'target'

,

'species'

]

)

.

corr

(

)

sns.

heatmap

(

correlation_matrix

,

annot

=

True

,

cmap

=

"coolwarm"

,

fmt

=

".2f"

)

plt.

title

(

"Correlation Heatmap"

)

plt.

show

(

)

3. Feature Selection and Data Preprocessing

Extract features and labels

X

=

df.

drop

(

columns

=

[

'target'

,

'species'

]

)

y

=

df

[

'target'

]

Data standardization

scaler

=

StandardScaler

(

)

X_scaled

=

scaler.

fit_transform

(

X

)

4. Build the Classification Model

Split the dataset

X_train

,

X_test

,

y_train

,

y_test

=

train_test_split

(

X_scaled

,

y

,

test_size

=

0.2

,

random_state

=

42

)

Use a decision tree classifier

model_dt

=

DecisionTreeClassifier

(

random_state

=

42

)

model_dt.

fit

(

X_train

,

y_train

)

Predict

y_pred_dt

=

model_dt.

predict

(

X_test

)

Output the accuracy of the decision tree

accuracy_dt

=

accuracy_score

(

y_test

,

y_pred_dt

)

print

(

f

"Decision Tree Accuracy: {accuracy_dt:.4f}"

)

Use the Support Vector Machine (SVM) classifier

model_svm

=

SVC

(

kernel

=

'linear'

,

random_state

=

42

)

model_svm.

fit

(

X_train

,

y_train

)

Predict

y_pred_svm

=

model_svm.

predict

(

X_test

)

Output the accuracy of the SVM

accuracy_svm

=

accuracy_score

(

y_test

,

y_pred_svm

)

print

(

f

"SVM Accuracy: {accuracy_svm:.4f}"

)

5. Model Evaluation

Decision tree model evaluation

print

(

"\nDecision Tree Classification Report:"

)

print

(

classification_report

(

y_test

,

y_pred_dt

)

)

print

(

"\nDecision Tree Confusion Matrix:"

)

print

(

confusion_matrix

(

y_test

,

y_pred_dt

)

)

SVM model evaluation

print

(

"\nSVM Classification Report:"

)

print

(

classification_report

(

y_test

,

y_pred_svm

)

)

print

(

"\nSVM Confusion Matrix:"

)

print

(

confusion_matrix

(

y_test

,

y_pred_svm

)

)

6. Grid Search Tuning

Define the parameter grid for the decision tree

param_grid

=

{

   

'max_depth'

:

[

3

,

5

,

10

,

None

]

,

   

'min_samples_split'

:

[

2

,

5

,

10

]

,

   

'min_samples_leaf'

:

[

1

,

2

,

4

]

}

Initialize GridSearchCV

grid_search

=

GridSearchCV

(

estimator

=

DecisionTreeClassifier

(

random_state

=

42

)

,

param_grid

=

param_grid

,

cv

=

5

)

grid_search.

fit

(

X_train

,

y_train

)

Get the best parameters and best model

print

(

"\nBest Parameters from GridSearchCV (Decision Tree):"

)

print

(

grid_search.

best_params_

)

Use the best model for prediction

best_model

=

grid_search.

best_estimator_

y_pred_optimized

=

best_model.

predict

(

X_test

)

Output the optimized decision tree accuracy

accuracy_optimized

=

accuracy_score

(

y_test

,

y_pred_optimized

)

print

(

f

"Optimized Decision Tree Accuracy: {accuracy_optimized:.4f}"

)

7. Cross-Validation

Perform 5-fold cross-validation

cross_val_scores

=

cross_val_score

(

best_model

,

X_scaled

,

y

,

cv

=

5

)

print

(

"\nCross-validation Scores (Optimized Decision Tree):"

)

print

(

cross_val_scores

)

print

(

f

"Mean CV Accuracy: {cross_val_scores.mean():.4f}"

)

Code analysis:

  1. Data loading:

  2. Use load_iris() Load the Iris dataset and convert the data to DataFrame format, so that it can be viewed and analyzed.
  3. - Use `load_iris()` to load the Iris dataset and convert the data to `DataFrame` format for viewing and analysis.
    1. Data visualization:

    2. Use seaborn 's pairplot Plot a scatter plot matrix between features, and use heatmap to draw a correlation heatmap between features.
    3. - Use `seaborn`'s `pairplot` to plot a scatter matrix of features, and use `heatmap` to draw a correlation heatmap between features.
      1. Feature selection and data preprocessing:

      2. Extract features (X) and labels (y), and standardize the feature data so that each feature has a mean of 0 and a variance of 1.
      3. - Extract features (`X`) and labels (`y`), and standardize the feature data so that each feature has a mean of 0 and a variance of 1.
        1. Build a classification model:

        2. Use DecisionTreeClassifier and SVC Train a decision tree classifier and a support vector machine classifier respectively, and evaluate their accuracy on the test set.
        3. - Use `DecisionTreeClassifier` and `SVC` to train a decision tree classifier and a support vector machine classifier respectively, and evaluate their accuracy on the test set.
          1. Model evaluation:

          2. Use classification_report and confusion_matrix Output detailed evaluation metrics of the model, including precision, recall, F1 score, and the confusion matrix.
          3. - Use `classification_report` and `confusion_matrix` to output detailed evaluation metrics of the model, including precision, recall, F1 score, and the confusion matrix.
            1. Grid search tuning:

            2. Use GridSearchCV Perform hyperparameter tuning on the decision tree model, search for the best hyperparameter combination, and output the accuracy of the optimized model.
            3. - Use `GridSearchCV` to perform hyperparameter tuning on the decision tree model, search for the best hyperparameter combination, and output the accuracy of the optimized model.
              1. Cross validation:

              2. Use cross_val_score Perform 5-fold cross validation to evaluate the stability and performance of the optimized decision tree model.
              3. - Use `cross_val_score` to perform 5-fold cross validation to evaluate the stability and performance of the optimized decision tree model.

                The output is as follows:

                数据预览:
                
                   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  target species
                
                0                 5.1               3.5                1.4               0.2       0   setosa
                
                1                 4.9               3.0                1.4               0.2       0   setosa
                
                2                 4.7               3.2                1.3               0.2       0   setosa
                
                3                 4.6               3.1                1.5               0.2       0   setosa
                
                4                 5.0               3.6                1.4               0.2       0   setosa
                
                
                
                Decision Tree Accuracy: 1.0000
                
                SVM Accuracy: 1.0000
                
                
                
                Decision Tree Classification Report:
                
                              precision    recall  f1-score   support
                
                
                
                           0       1.00      1.00      1.00         9
                
                           1       1.00      1.00      1.00         8
                
                           2       1.00      1.00      1.00         8
                
                
                
                    accuracy                           1.00        25
                
                   macro avg       1.00      1.00      1.00        25
                
                weighted avg       1.00      1.00      1.00        25
                
                
                
                Decision Tree Confusion Matrix:
                
                [[9 0 0]
                
                 [0 8 0]
                
                 [0 0 8]]
                
                
                
                SVM Classification Report:
                
                              precision    recall  f1-score   support
                
                
                
                           0       1.00      1.00      1.00         9
                
                           1       1.00      1.00      1.00         8
                
                           2       1.00      1.00      1.00         8
                
                
                
                    accuracy                           1.00        25
                
                   macro avg       1.00      1.00      1.00        25
                
                weighted avg       1.00      1.00      1.00        25
                
                
                
                SVM Confusion Matrix:
                
                [[9 0 0]
                
                 [0 8 0]
                
                 [0 0 8]]
                
                
                
                Best Parameters from GridSearchCV (Decision Tree):
                
                {'max_depth': 5, 'min_samples_leaf': 1, 'min_samples_split': 2}
                
                
                
                Optimized Decision Tree Accuracy: 1.0000
                
                
                
                Cross-validation Scores (Optimized Decision Tree):
                
                [1.         1.         1.         1.         1.        ]
                
                Mean CV Accuracy: 1.0000