Nestorthera commited on
Commit
f8fdedb
·
verified ·
1 Parent(s): f884bc9

Upload 2 files

Browse files
Files changed (2) hide show
  1. titanic_model.pkl +3 -0
  2. titanic_prediction_api.py +206 -0
titanic_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84aa5b5513c063ef2d782c50fc763056b1eb8d5b408be763ff4f249d08e10342
3
+ size 34683
titanic_prediction_api.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Titanic Prediction API.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1LI8plf1ij77jYk8LUV0j-jw3ktr3DkCS
8
+ """
9
+
10
+ !pip install fastapi uvicorn
11
+
12
+ """Installer et configurer le token ngrok"""
13
+
14
+ !pip install pyngrok
15
+ !ngrok authtoken 2KEmulzOzABtZxb1pHULmIVC21k_5F4nAYQBQjgHvAz2FgcRx
16
+
17
+ """Chargement des données
18
+
19
+ """
20
+
21
+ import pandas as pd
22
+ import joblib
23
+ # Charger le dataset Titanic
24
+ url = "https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv"
25
+ titanic_data = pd.read_csv(url)
26
+
27
+ # Afficher les premières lignes du dataset
28
+ print(titanic_data.head())
29
+
30
+ """Exploration et Préparation des données"""
31
+
32
+ import numpy as np
33
+ import matplotlib.pyplot as plt
34
+ import seaborn as sns
35
+ import pandas as pd
36
+
37
+ # Charger le dataset Titanic
38
+ url = "https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv"
39
+ titanic_data = pd.read_csv(url)
40
+
41
+ # Analyse des données
42
+ print(titanic_data.info())
43
+ print(titanic_data.describe())
44
+
45
+ # Traitement des valeurs manquantes pour 'Age' (si elles existent)
46
+ if 'Age' in titanic_data.columns:
47
+ titanic_data['Age'].fillna(titanic_data['Age'].median(), inplace=True)
48
+
49
+ # Traitement des valeurs manquantes pour 'Embarked' (si elle existe)
50
+ if 'Embarked' in titanic_data.columns:
51
+ titanic_data['Embarked'].fillna(titanic_data['Embarked'].mode()[0], inplace=True)
52
+
53
+ # Encodage des variables catégorielles (si elles existent)
54
+ if 'Sex' in titanic_data.columns:
55
+ titanic_data = pd.get_dummies(titanic_data, columns=['Sex'], drop_first=True)
56
+ if 'Embarked' in titanic_data.columns:
57
+ titanic_data = pd.get_dummies(titanic_data, columns=['Embarked'], drop_first=True)
58
+
59
+ # Suppression des colonnes inutiles (si elles existent)
60
+ columns_to_drop = ['Name', 'Ticket', 'Cabin']
61
+ for column in columns_to_drop:
62
+ if column in titanic_data.columns:
63
+ titanic_data.drop(column, axis=1, inplace=True)
64
+
65
+ # Afficher les premières lignes du DataFrame nettoyé
66
+ print(titanic_data.head())
67
+
68
+ """Modélisation"""
69
+
70
+ from sklearn.model_selection import train_test_split
71
+ from sklearn.linear_model import LogisticRegression
72
+ from sklearn.ensemble import RandomForestClassifier
73
+ from sklearn.svm import SVC
74
+
75
+ # Séparation des caractéristiques et de la cible
76
+ X = titanic_data.drop('Survived', axis=1)
77
+ y = titanic_data['Survived']
78
+
79
+ # Division en ensembles d'entraînement et de test
80
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
81
+
82
+ # Entraînement de différents modèles
83
+ models = {
84
+ 'Logistic Regression': LogisticRegression(),
85
+ 'Random Forest': RandomForestClassifier(),
86
+ 'Support Vector Machine': SVC()
87
+ }
88
+
89
+ for name, model in models.items():
90
+ model.fit(X_train, y_train)
91
+ score = model.score(X_test, y_test)
92
+ print(f"{name} Accuracy: {score:.2f}")
93
+
94
+ # Enregistrer le modèle
95
+ joblib.dump(model, 'titanic_model.pkl')
96
+
97
+ """Évaluation des modèles"""
98
+
99
+ from sklearn.metrics import classification_report, confusion_matrix
100
+
101
+ # Sélection du meilleur modèle (par exemple, Random Forest)
102
+ best_model = models['Random Forest']
103
+ y_pred = best_model.predict(X_test)
104
+
105
+ # Rapport de classification
106
+ print(classification_report(y_test, y_pred))
107
+
108
+ # Matrice de confusion
109
+ conf_matrix = confusion_matrix(y_test, y_pred)
110
+ sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
111
+ plt.xlabel('Prédiction')
112
+ plt.ylabel('Réalité')
113
+ plt.show()
114
+
115
+ """Déploiement"""
116
+
117
+ import joblib
118
+
119
+ # Enregistrer le modèle
120
+ joblib.dump(best_model, 'titanic_model.pkl')
121
+
122
+ """Créer une API avec FastAPI"""
123
+
124
+ from fastapi import FastAPI
125
+ import joblib
126
+ import pandas as pd
127
+
128
+ app = FastAPI()
129
+
130
+ # Charger le modèle
131
+ model = joblib.load('titanic_model.pkl')
132
+
133
+ @app.post("/predict")
134
+ def predict(data: dict):
135
+ df = pd.DataFrame([data])
136
+ prediction = model.predict(df)
137
+ return {"prediction": int(prediction[0])}
138
+
139
+ """Utilisation de ngrok
140
+
141
+ Mise à jour du schéma de la requête
142
+ """
143
+
144
+ from pydantic import BaseModel
145
+
146
+ class Passenger(BaseModel):
147
+ Pclass: int
148
+ Sex_male: int
149
+ Age: float
150
+ Siblings_Spouses_Aboard: int
151
+ Parents_Children_Aboard: int
152
+ Fare: float
153
+
154
+ @app.post("/predict")
155
+ def predict(data: Passenger):
156
+ df = pd.DataFrame([data.dict()])
157
+ prediction = model.predict(df)
158
+ return {"prediction": int(prediction[0])}
159
+
160
+ !pip install fastapi uvicorn nest-asyncio pyngrok
161
+
162
+ # Importer les modules nécessaires
163
+ import nest_asyncio
164
+ from pyngrok import ngrok
165
+ import uvicorn
166
+ from fastapi import FastAPI
167
+ from pydantic import BaseModel
168
+ import joblib
169
+ import pandas as pd
170
+
171
+ # Appliquer nest_asyncio pour éviter les erreurs liées aux boucles d'événements
172
+ nest_asyncio.apply()
173
+
174
+ # Créer une instance FastAPI
175
+ app = FastAPI()
176
+
177
+ # Charger le modèle
178
+ model = joblib.load('titanic_model.pkl')
179
+
180
+ # Classe Pydantic pour le schéma de la requête
181
+ class Passenger(BaseModel):
182
+ Pclass: int
183
+ Sex_male: int
184
+ Age: float
185
+ Siblings_Spouses_Aboard: int
186
+ Parents_Children_Aboard: int
187
+ Fare: float
188
+
189
+ # Route de base pour vérifier le bon fonctionnement
190
+ @app.get("/")
191
+ def read_root():
192
+ return {"message": "Welcome to the Titanic prediction API!"}
193
+
194
+ # Route pour les prédictions
195
+ @app.post("/predict")
196
+ def predict(data: Passenger):
197
+ df = pd.DataFrame([data.dict()])
198
+ prediction = model.predict(df)
199
+ return {"prediction": int(prediction[0])}
200
+
201
+ # Configurer et démarrer ngrok
202
+ ngrok_tunnel = ngrok.connect(8000)
203
+ print('Public URL:', ngrok_tunnel.public_url)
204
+
205
+ # Démarrer le serveur Uvicorn
206
+ uvicorn.run(app, host='0.0.0.0', port=8000)