text_plain_output_1.png
from sklearn.compose import ColumnTransformer

from sklearn.datasets import fetch_openml

from sklearn.ensemble import RandomForestClassifier

from sklearn.impute import SimpleImputer

from sklearn.model_selection import train_test_split

from sklearn.pipeline import Pipeline

from sklearn.preprocessing import OrdinalEncoder

import numpy as np # linear algebra

from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
X, y = fetch_openml('titanic', version=1, as_frame=True, return_X_y=True)
rng = np.random.RandomState(seed=42)
X['random_cat'] = rng.randint(3, size=X.shape[0])
X['random_num'] = rng.randn(X.shape[0])
categorical_columns = ['pclass', 'sex', 'embarked', 'random_cat']
numerical_columns = ['age', 'sibsp', 'parch', 'fare', 'random_num']
X = X[categorical_columns + numerical_columns]
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)

from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OrdinalEncoder
categorical_encoder = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)
numerical_pipe = SimpleImputer(strategy='mean')
preprocessing = ColumnTransformer([('cat', categorical_encoder, categorical_columns), ('num', numerical_pipe, numerical_columns)], verbose_feature_names_out=True)
rf = Pipeline([('preprocess', preprocessing), ('classifier', RandomForestClassifier(random_state=42))])
rf.fit(X_train, y_train)

print(f'RF train accuracy: {rf.score(X_train, y_train):.3f}')
print(f'RF test accuracy: {rf.score(X_test, y_test):.3f}')