Solution
To fit a random forest model to data with both numerical and categorical variables, you can use scikit-learn's Pipeline and ColumnTransformer to apply different preprocessing steps to different types of features. Here's how you can do it:
- Identify Feature Types: Separate numerical and categorical features.
- Preprocessing:
- For numerical features: Impute missing values and standardize.
- For categorical features: Impute missing values and one-hot encode.
- Combine Transformers: Use
ColumnTransformer to apply different transformations to different columns.
- Create Pipeline: Chain the preprocessing steps and the model together in a
Pipeline.
- Fit and Evaluate: Fit the pipeline on the training data and evaluate on the test data.
Here's an example code snippet that demonstrates this process:
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score
# Example data with missing values
data = {
'age': [25, 30, np.nan, 40, 45],
'gender': ['M', 'F', 'M', None, 'M'],
'education': ['High School', 'Bachelor', 'Master', 'PhD', None],
'target': [0, 1, 0, 1, 0]
}
df = pd.DataFrame(data)
X = df.drop('target', axis=1)
y = df['target']
# Define numerical and categorical features
numerical_features = ['age']
categorical_features = ['gender', 'education']
# Create transformers for numerical features
numerical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())
])
# Create transformers for categorical features
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
# Combine transformers using ColumnTransformer
preprocessor = ColumnTransformer(
transformers=[
('num', numerical_transformer, numerical_features),
('cat', categorical_transformer, categorical_features)
])
# Create the pipeline
pipeline = Pipeline(steps=[
('preprocessor', preprocessor),
('classifier', RandomForestClassifier())
])
# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Fit the pipeline
pipeline.fit(X_train, y_train)
# Predict on the test set
y_pred = pipeline.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")