1. Coaching the Machine Studying Mannequin
Step one was to scrub and preprocess the Titanic dataset and prepare a machine studying mannequin:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score# Load dataset
df = pd.read_csv("titanic.csv")
df = df.drop(columns=["Cabin", "Name", "Ticket"])
df = pd.get_dummies(df, columns=["Sex", "Embarked"], drop_first=True)
# Cut up options and labels
X = df.drop("Survived", axis=1)
y = df["Survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Practice mannequin
mannequin = LogisticRegression(max_iter=1000)
mannequin.match(X_train, y_train)
# Consider mannequin
y_pred = mannequin.predict(X_test)
print("Mannequin Accuracy:", accuracy_score(y_test, y_pred))
2. Serving the Mannequin as a Flask API
As soon as the mannequin was skilled, the following step was to make it accessible via a REST API:
from flask import Flask, request, jsonify
import joblib
import numpy as np
from flask_cors import CORSapp = Flask(__name__)
CORS(app)
# Load skilled mannequin
mannequin = joblib.load("mannequin/titanic_model.pkl")
@app.route("/predict", strategies=["POST"])
def predict():
knowledge = request.get_json()
options = np.array([[data["Pclass"], knowledge["Sex"], knowledge["Age"], knowledge["SibSp"], knowledge["Parch"], knowledge["Fare"], knowledge["Embarked_Q"], knowledge["Embarked_S"]]])
likelihood = mannequin.predict_proba(options)[0][1]
prediction = "Survived" if likelihood > 0.5 else "Did Not Survive"
return jsonify({"prediction": prediction, "likelihood": spherical(likelihood * 100, 2)})
if __name__ == "__main__":
app.run(debug=True)
3. Making a Trendy UI for Predictions
A React frontend was constructed to work together with the API and show predictions in a wealthy, user-friendly interface:
import { useState } from "react";
import { ChakraProvider, Field, Button, Enter, Choose, Textual content, VStack } from "@chakra-ui/react";
import axios from "axios";const API_URL = "https://your-api.onrender.com/predict";
perform App() {
const [formData, setFormData] = useState({ Pclass: "3", Intercourse: "male", Age: "", SibSp: "0", Parch: "0", Fare: "", Embarked: "S" });
const [prediction, setPrediction] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
const payload = { ...formData, Intercourse: formData.Intercourse === "feminine" ? 1 : 0 };
const res = await axios.submit(API_URL, payload);
setPrediction(res.knowledge);
};
return (
Titanic Survival Predictor
setFormData({ ...formData, Age: e.goal.worth })} required />
{prediction && {prediction.prediction} ({prediction.likelihood}%) }
);
}
export default App;
3. Undertaking Hyperlinks
This enhanced Medium submit now offers a detailed, partaking walkthrough that showcases each the technical depth and deployment points of the mission.