Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Automazione della Pre-Elaborazione con Pipeline | Ingegneria delle Caratteristiche per l'Apprendimento Automatico
Preprocessing dei Dati e Feature Engineering

bookAutomazione della Pre-Elaborazione con Pipeline

Automatizza la pre-elaborazione e l'ingegneria delle caratteristiche con le pipeline di scikit-learn per garantire risultati di machine learning coerenti e riproducibili. Le pipeline consentono di concatenare passaggi come la normalizzazione, la codifica e la selezione delle caratteristiche, assicurando che ogni trasformazione avvenga sempre nello stesso ordine.

Per costruire una pipeline in scikit-learn, definire un elenco di passaggi, dove ciascun passaggio è una tupla contenente un nome univoco per il passaggio (come stringa) e un oggetto trasformatore (ad esempio StandardScaler o SelectKBest). Ad esempio:

steps = [
    ("scaler", StandardScaler()),
    ("feature_selection", SelectKBest(score_func=f_classif, k=2))
]

Si passa quindi questo elenco all'oggetto Pipeline:

pipeline = Pipeline(steps)

La pipeline applica ogni trasformatore in ordine, passando l'output di un passaggio come input al successivo. Questo approccio non solo fa risparmiare tempo, ma riduce anche il rischio di leakage dei dati, rendendo gli esperimenti più affidabili e facili da riprodurre.

Utilizzo di ColumnTransformer per sottoinsiemi di caratteristiche

Con ColumnTransformer, è possibile applicare diverse pipeline di pre-elaborazione a diversi sottoinsiemi di caratteristiche all'interno dei dati. Ad esempio:

# Define column types
numeric_features = ['age', 'fare']
categorical_features = ['embarked', 'sex']

# Preprocessing for numeric features: impute missing values and scale
numeric_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='mean')),
    ('scaler', StandardScaler())
])

# Preprocessing for categorical features: impute missing values and encode
categorical_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OneHotEncoder(handle_unknown='ignore'))
])

Questo consente di costruire una pipeline unificata che gestisce correttamente sia i dati numerici che quelli categorici, mantenendo il codice di pre-elaborazione organizzato e assicurando che ogni trasformazione venga applicata alle colonne previste.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
import numpy as np import pandas as pd import seaborn as sns from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.compose import ColumnTransformer from sklearn.feature_selection import SelectKBest, f_classif # Load the Titanic dataset from seaborn (no warnings!) df = sns.load_dataset('titanic') # Select features and target features = ['age', 'fare', 'embarked', 'sex'] X = df[features] y = df['survived'] # Target variable # Define column types numeric_features = ['age', 'fare'] categorical_features = ['embarked', 'sex'] # Preprocessing for numeric features: impute missing values and scale numeric_transformer = Pipeline([ ('imputer', SimpleImputer(strategy='mean')), ('scaler', StandardScaler()) ]) # Preprocessing for categorical features: impute missing values and encode categorical_transformer = Pipeline([ ('imputer', SimpleImputer(strategy='most_frequent')), ('encoder', OneHotEncoder(handle_unknown='ignore')) ]) # Combine preprocessing steps preprocessor = ColumnTransformer([ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features) ]) # Build the full pipeline with preprocessing and feature selection pipeline = Pipeline([ ('preprocessing', preprocessor), ('feature_selection', SelectKBest(score_func=f_classif, k=3)) ]) # Fit and transform the data X_transformed = pipeline.fit_transform(X, y) print(f"Original shape: {X.shape}") print(f"Reduced from {X.shape[1]} features to {X_transformed.shape[1]} selected features")
copy
Note
Nota

Integrare la pre-elaborazione nella pipeline di addestramento garantisce trasformazioni coerenti e aiuta a prevenire il leakage dei dati sia durante l'addestramento che in fase di previsione.

question mark

Quale dei seguenti è un vantaggio chiave nell'utilizzo delle pipeline sklearn per il preprocessing e il feature engineering?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 3

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Awesome!

Completion rate improved to 8.33

bookAutomazione della Pre-Elaborazione con Pipeline

Scorri per mostrare il menu

Automatizza la pre-elaborazione e l'ingegneria delle caratteristiche con le pipeline di scikit-learn per garantire risultati di machine learning coerenti e riproducibili. Le pipeline consentono di concatenare passaggi come la normalizzazione, la codifica e la selezione delle caratteristiche, assicurando che ogni trasformazione avvenga sempre nello stesso ordine.

Per costruire una pipeline in scikit-learn, definire un elenco di passaggi, dove ciascun passaggio è una tupla contenente un nome univoco per il passaggio (come stringa) e un oggetto trasformatore (ad esempio StandardScaler o SelectKBest). Ad esempio:

steps = [
    ("scaler", StandardScaler()),
    ("feature_selection", SelectKBest(score_func=f_classif, k=2))
]

Si passa quindi questo elenco all'oggetto Pipeline:

pipeline = Pipeline(steps)

La pipeline applica ogni trasformatore in ordine, passando l'output di un passaggio come input al successivo. Questo approccio non solo fa risparmiare tempo, ma riduce anche il rischio di leakage dei dati, rendendo gli esperimenti più affidabili e facili da riprodurre.

Utilizzo di ColumnTransformer per sottoinsiemi di caratteristiche

Con ColumnTransformer, è possibile applicare diverse pipeline di pre-elaborazione a diversi sottoinsiemi di caratteristiche all'interno dei dati. Ad esempio:

# Define column types
numeric_features = ['age', 'fare']
categorical_features = ['embarked', 'sex']

# Preprocessing for numeric features: impute missing values and scale
numeric_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='mean')),
    ('scaler', StandardScaler())
])

# Preprocessing for categorical features: impute missing values and encode
categorical_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OneHotEncoder(handle_unknown='ignore'))
])

Questo consente di costruire una pipeline unificata che gestisce correttamente sia i dati numerici che quelli categorici, mantenendo il codice di pre-elaborazione organizzato e assicurando che ogni trasformazione venga applicata alle colonne previste.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
import numpy as np import pandas as pd import seaborn as sns from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.compose import ColumnTransformer from sklearn.feature_selection import SelectKBest, f_classif # Load the Titanic dataset from seaborn (no warnings!) df = sns.load_dataset('titanic') # Select features and target features = ['age', 'fare', 'embarked', 'sex'] X = df[features] y = df['survived'] # Target variable # Define column types numeric_features = ['age', 'fare'] categorical_features = ['embarked', 'sex'] # Preprocessing for numeric features: impute missing values and scale numeric_transformer = Pipeline([ ('imputer', SimpleImputer(strategy='mean')), ('scaler', StandardScaler()) ]) # Preprocessing for categorical features: impute missing values and encode categorical_transformer = Pipeline([ ('imputer', SimpleImputer(strategy='most_frequent')), ('encoder', OneHotEncoder(handle_unknown='ignore')) ]) # Combine preprocessing steps preprocessor = ColumnTransformer([ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features) ]) # Build the full pipeline with preprocessing and feature selection pipeline = Pipeline([ ('preprocessing', preprocessor), ('feature_selection', SelectKBest(score_func=f_classif, k=3)) ]) # Fit and transform the data X_transformed = pipeline.fit_transform(X, y) print(f"Original shape: {X.shape}") print(f"Reduced from {X.shape[1]} features to {X_transformed.shape[1]} selected features")
copy
Note
Nota

Integrare la pre-elaborazione nella pipeline di addestramento garantisce trasformazioni coerenti e aiuta a prevenire il leakage dei dati sia durante l'addestramento che in fase di previsione.

question mark

Quale dei seguenti è un vantaggio chiave nell'utilizzo delle pipeline sklearn per il preprocessing e il feature engineering?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 3
some-alt