Enter the passenger's data to predict whether they would have survived the sinking.
The prediction result will appear here.
# List of required packages for your code to run in the browser.
# PyScript will download and install them.
packages = ["pandas", "scikit-learn", "joblib"]
import pandas as pd
import joblib
from pyodide.http import pyfetch
from js import document, console
import io
# Global variable to store the loaded pipeline and avoid reloading it
pipeline = None
async def load_model():
"""Asynchronously loads the .joblib model file."""
global pipeline
if pipeline is None:
console.log("Loading the model...")
try:
response = await pyfetch('./titanic_pipeline.joblib')
if response.ok:
model_bytes = await response.bytes()
pipeline = joblib.load(io.BytesIO(model_bytes))
console.log("Model loaded successfully!")
else:
console.error(f"Error fetching the model: {response.status}")
except Exception as e:
console.error(f"An error occurred while loading the model: {e}")
async def predict_survival(*args, **kwargs):
"""Function called by the button to make a prediction."""
# Ensure the model is loaded before predicting
await load_model()
if pipeline is None:
output_div = document.getElementById('output-div')
output_div.innerText = "Error: Model could not be loaded."
output_div.className = "not-survived"
return
console.log("Collecting data from the form...")
# Collect data from the HTML form
# The IDs must match those defined in the HTML tags
data = {
'Pclass': str(document.getElementById('pclass').value), # Converted to string, as in the notebook
'Sex': document.getElementById('sex').value,
'Age': float(document.getElementById('age').value),
'SibSp': int(document.getElementById('sibsp').value),
'Parch': int(document.getElementById('parch').value),
'Fare': float(document.getElementById('fare').value),
'Embarked': document.getElementById('embarked').value
}
# Create a pandas DataFrame with the data, as the pipeline expects this format
input_df = pd.DataFrame([data])
console.log("Input DataFrame created:")
console.log(str(input_df))
# Make the prediction
prediction = pipeline.predict(input_df)[0]
console.log(f"Prediction result: {prediction}")
# Display the result on the screen
output_div = document.getElementById('output-div')
if prediction == '1':
output_div.innerText = "Result: Likely to Survive"
output_div.className = "survived" # Add class to style the background
else:
output_div.innerText = "Result: Unlikely to Survive"
output_div.className = "not-survived" # Add class to style the background