Below is a comprehensive Python program that demonstrates how to use a genetic algorithm to optimize the parameters of a machine learning model for predicting the survival of passengers aboard the Titanic. Given the complexity of implementing genetic algorithms and due to the limitations of executable code here, this example will lay out the approach without running. Import the necessary libraries, parse the dataset, perform exploratory data analysis with visualizations in orange, preprocess the data, define a genetic algorithm for optimization, and evaluate the results.
You would first need to install the required modules if you don't have them already installed, for this specific task, we require tpot, which can be installed using pip:
pip install numpy pandas matplotlib seaborn sklearn tpot
Now we can write the full program step by step.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from tpot import TPOTClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing import LabelEncoder, StandardScaler
# Load datasets
train_data = pd.read_csv('train.csv')
test_data = pd.read_csv('test.csv')
# Data exploration with visualizations
# Plotting the distribution of the 'Survived' feature
sns.countplot(x='Survived', data=train_data, palette=['#FFA500', '#FF4500'])
plt.title('Survival Counts')
plt.show()
# Plotting the survival rate by class
sns.barplot(x='Pclass', y='Survived', data=train_data, palette=['#FFA500'])
plt.title('Survival Rate by Class')
plt.show()
# Preprocessing: Filling missing values, encoding categorical variables, and scaling
def preprocess_data(data):
data['Age'].fillna(data['Age'].median(), inplace=True)
data['Fare'].fillna(data['Fare'].median(), inplace=True)
data['Embarked'].fillna(data['Embarked'].mode()[0], inplace=True)
data.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True)
le = LabelEncoder()
data['Sex'] = le.fit_transform(data['Sex'])
data['Embarked'] = le.fit_transform(data['Embarked'])
scaler = StandardScaler()
numerical_features = ['Age', 'Fare']
data[numerical_features] = scaler.fit_transform(data[numerical_features])
return data
train_data = preprocess_data(train_data)
test_data = preprocess_data(test_data)
# Defining features and target
X = train_data.drop('Survived', axis=1)
y = train_data['Survived']
# Splitting data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Using TPOTClassifier to optimize a machine learning pipeline using genetic algorithm
tpot = TPOTClassifier(generations=5, population_size=50, verbosity=2, scoring='accuracy', random_state=42, color=True)
tpot.fit(X_train, y_train)
# Evaluating the final pipeline on the test data
y_pred = tpot.predict(X_test)
print(f"Test Accuracy: {accuracy_score(y_test, y_pred)}")
print(classification_report(y_test, y_pred))
# Export the optimized pipeline as Python code
tpot.export('titanic_survival_model.py')
This script does the following:
- Imports required libraries.
- Loads the training and testing sets (you need to put the path to your dataset files).
- Performs initial data exploration with visualizations, making sure the plots use shades of orange.
- Preprocesses the data by handling missing values, encoding categorical variables, and feature scaling.
- Splits the data into training and test sets.
- Applies the TPOT genetic algorithm to optimize a machine learning pipeline.
- Evaluates the resulting optimized model on the test set.
- Exports the best pipeline, as found by TPOT, to a Python file.
Remember to have your dataset files (train.csv and test.csv) within the same directory where you're running this script, or provide the full path to the files instead. TPOT will take care of the complexity of finding the best model, and it uses genetic algorithms under the hood to do so.
Before running this script, please make sure you have enough computational resources available as genetic algorithms and automated machine learning (AutoML) with TPOT can be computationally intensive and may take a long