-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraining.py
More file actions
54 lines (51 loc) · 1.81 KB
/
Copy pathtraining.py
File metadata and controls
54 lines (51 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
training.py
Fonctions d'entraînement pour sklearn et Keras, sauvegarde en bytes pour téléchargement.
"""
from sklearn.base import clone
from sklearn.metrics import accuracy_score
import joblib
import io
import tempfile
import numpy as np
import streamlit as st
from tensorflow.keras.callbacks import EarlyStopping
def train_sklearn_model(model, X_train, y_train, X_test=None, y_test=None):
"""
Entraîne un modèle sklearn et retourne (model, history_dict)
"""
model.fit(X_train, y_train)
history = {}
if X_test is not None and y_test is not None:
try:
preds = model.predict(X_test)
acc = accuracy_score(y_test, preds)
history['test_accuracy'] = float(acc)
except Exception:
pass
return model, history
def train_keras_model(model, X_train, y_train, X_val, y_val, epochs=10, batch_size=32):
cb = [EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)]
history = model.fit(X_train, y_train, validation_data=(X_val, y_val),
epochs=epochs, batch_size=batch_size, callbacks=cb, verbose=0)
return history.history, model
def save_model_to_bytes(model, model_type="sklearn"):
"""
Retourne un buffer bytes prêt pour st.download_button
"""
buffer = io.BytesIO()
if model_type == "sklearn":
joblib.dump(model, buffer)
buffer.seek(0)
elif model_type == "keras":
# save model to temporary file then read bytes
import tempfile
tmp = tempfile.NamedTemporaryFile(suffix=".h5", delete=False)
model.save(tmp.name)
tmp.close()
with open(tmp.name, "rb") as f:
buffer.write(f.read())
buffer.seek(0)
else:
raise ValueError("model_type must be 'sklearn' or 'keras'")
return buffer.getvalue()