AamerAkhter's picture
Create app.py
9e8c62d verified
Raw
History Blame Contribute Delete
2.17 kB
import gradio as gr
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
# 1. Load the cleaned dataset
df = pd.read_csv('cleaned_titanic_dataset.csv')
# Encode the 'Sex' column into numbers (Male=1, Female=0) so the model can read it
le = LabelEncoder()
df['Sex'] = le.fit_transform(df['Sex'])
# 2. Define features and target
features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']
X = df[features]
y = df['Survived']
# 3. Train a quick Random Forest model
model = RandomForestClassifier(random_state=42)
model.fit(X, y)
# 4. Define the prediction function that Gradio will use
def predict_survival(pclass, sex, age, sibsp, parch, fare):
# Convert inputs to match the model's expectations
sex_encoded = 1 if sex == "Male" else 0
input_data = pd.DataFrame([[pclass, sex_encoded, age, sibsp, parch, fare]], columns=features)
# Make prediction
prediction = model.predict(input_data)[0]
probability = model.predict_proba(input_data)[0][prediction]
result = "Survived" if prediction == 1 else "Did Not Survive"
return f"Prediction: {result}\nConfidence: {probability:.2%}"
# 5. Build the Gradio Interface
interface = gr.Interface(
fn=predict_survival,
inputs=[
gr.Radio(choices=[1, 2, 3], label="Passenger Class (1=1st, 2=2nd, 3=3rd)"),
gr.Radio(choices=["Male", "Female"], label="Sex"),
# Note: Since we normalized Age and Fare in Colab, the inputs here should be between 0 and 1
gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Normalized Age (0 to 1)"),
gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Normalized SibSp (0 to 1)"),
gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Normalized Parch (0 to 1)"),
gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label="Normalized Fare (0 to 1)")
],
outputs=gr.Text(label="Survival Prediction"),
title="Titanic Survival Predictor",
description="Enter normalized passenger details to predict if they would have survived the Titanic disaster."
)
# Launch the app
if __name__ == "__main__":
interface.launch()