Q：では，機械学習モデルを構築したいです．
今回はtest rateを0.3に設定し，train test splitしてください．

また，ラベルは`Survived`とし，カテゴリ変数はOne-Hotでエンコードしてください，この時，カラム名は「特徴量_カテゴリ名」のようにしてください．例えば`Sex`の`male`は`Sex_male`となります．

予測に用いるライブラリはお任せします．

前処理として，あまりに欠損値の多いもの(割合的に0.5以上)のものについてはdropnaしてください．それ以外については，平均値で穴埋めしてください．

A：
```python
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier

# Features and target
X = titanic.drop(columns=['Survived'])
y = titanic['Survived']

# Find the categorical columns and numerical columns
categorical_cols = X.select_dtypes(include=['object', 'bool']).columns
numerical_cols = X.select_dtypes(include=['int64', 'float64']).columns

# Define the preprocessing steps
numerical_transformer = SimpleImputer(strategy='mean')  # Fill missing values with the mean

categorical_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='most_frequent')),  # Fill missing values with the most frequent value
    ('onehot', OneHotEncoder(handle_unknown='ignore'))  # Apply one-hot encoding
])

# Combine the preprocessing steps
preprocessor = ColumnTransformer(
    transformers=[
        ('num', numerical_transformer, numerical_cols),
        ('cat', categorical_transformer, categorical_cols)
    ])

# Define the model
model = RandomForestClassifier(random_state=0)

# Create and evaluate the pipeline
pipeline = Pipeline(steps=[('preprocessor', preprocessor),
                           ('model', model)])

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

# Fit the model
pipeline.fit(X_train, y_train)

# Score the model
score = pipeline.score(X_test, y_test)
score
```

データの前処理とモデルの訓練が完了しました．テストデータに対するモデルの精度は約83.2%です．つまり，このモデルはテストデータの83.2%を正しく分類できました．

具体的な前処理の手順は以下の通りです：

1.	数値型の特徴量について，欠損値があればその特徴量の平均値で補完しました．
2.	カテゴリ型の特徴量について，欠損値があれば最頻値で補完し，その後，One-Hotエンコーディングを適用しました．

モデルの選択については，ランダムフォレストを使用しました．ランダムフォレストは，多数の決定木を組み合わせることで高い予測性能を実現するアンサンブル学習の一つです．
