Problem Link

This code uses passenger details to predict who survived the Titanic disaster. It prepares the data, trains a neural network, and saves the predictions for a Kaggle submission.

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical
 
# Load the dataset
data = pd.read_csv("/kaggle/input/titanic/train.csv")
 
# Prepare the data
def preprocess_data(df, is_train=True):
    df = df.drop(["PassengerId", "Name", "Ticket", "Cabin"], axis=1)
    # Fill missing values
    df.fillna({"Age": df["Age"].median()}, inplace=True)
    df.fillna({"Embarked": df["Embarked"].mode()[0]}, inplace=True)
    df.fillna({"Fare": df["Fare"].median()}, inplace=True)
    # Convert categorical variables to numerical
    df["Sex"] = df["Sex"].map({"male": 0, "female": 1})
    df["Embarked"] = df["Embarked"].map({"S": 0, "C": 1, "Q": 2})
    # Feature engineering
    df["FamilySize"] = df["SibSp"] + df["Parch"] + 1
    df["IsAlone"] = (df["FamilySize"] == 1).astype(int)
    return df
 
# Preprocess train data
train = preprocess_data(data)
X = train.drop(["Survived"], axis=1)
y = to_categorical(train["Survived"]) # Convert labels to one-hot encoding
 
# Split the data
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=1)
 
# Standardize the features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
 
# Define the model
model = Sequential([
    Dense(128, activation="relu", input_shape=(X_train.shape[1],)),
    Dropout(0.2),
    Dense(64, activation="relu"),
    Dropout(0.2),
    Dense(32, activation="relu"),
    Dense(2, activation="softmax")
])
 
# Compile the model
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
 
# Early stopping to prevent overfitting
early_stopping = EarlyStopping(monitor="val_loss", patience=20, restore_best_weights=True)
 
# Train the model
model.fit(X_train, y_train, epochs=200, batch_size=32, validation_data=(X_val, y_val), callbacks=[early_stopping])
 
# Predict on the test set
test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
test_data_preprocessed = preprocess_data(test_data, is_train=False)
X_test = scaler.transform(test_data_preprocessed)
predictions = model.predict(X_test)
predictions_classes = np.argmax(predictions, axis=1)
 
# Prepare the submission file
output = pd.DataFrame({"PassengerId": test_data["PassengerId"], "Survived": predictions_classes})
output.to_csv("submission.csv", index=False)
print("Completed.")