For AI agents: the complete documentation index is available at https://docs.ovhcloud.com/fr/llms.txt, the full documentation bundle is available at https://docs.ovhcloud.com/fr/llms-full.txt, and this page is available as Markdown at https://docs.ovhcloud.com/fr/guides/public-cloud/ai-machine-learning/ai-training-train-marine_mammal_sound.md.
Découvrez à quel point il est simple d'entraîner un modèle à l'aide d'AI Training
Objectif
L'objectif de ce tutoriel est de comprendre comment entraîner un modèle avec AI Training afin de classifier des sons.
C'est l'étape suivante après avoir conçu le modèle avec AI Notebooks.
Vous pouvez consulter l'étape Notebook dans le tutoriel : Analyse et classification audio avec l'IA.
Info
Il est fortement recommandé de lire le tutoriel Notebook avant de lire ce tutoriel.
Prérequis
Accès au
Un projet Public Cloud créé
L'interface CLI ovhai installée sur votre système (plus d'informations ici)
Docker installé et configuré pour construire des images.
Un registre d'images OCI / Docker. Vous pouvez utiliser un registre public (comme Docker Hub par exemple) ou un registre privé. Consultez la documentation Créer un registre privé pour créer un registre privé basé sur Harbor. Pour rendre votre registre compatible avec l'utilisation d'AI Solutions, suivez le guide Utiliser et gérer vos registres.
Des connaissances sur la construction d'images avec Dockerfile
Pour entraîner le modèle, nous allons utiliser AI Training. Cet outil puissant vous permet d'automatiser vos pipelines et de construire facilement des phases de fine-tuning.
AI Training vous permet d'entraîner des modèles directement à partir de vos propres images Docker.
Tout d'abord, vous devez créer un script Python chargé de réaliser l'entraînement.
Vous pouvez copier-coller le code suivant dans un fichier nommé train-audio-classification.py :
import numpy as npimport pandas as pdimport datetime# preprocessingfrom sklearn.preprocessing import LabelEncoderfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_split# modelimport tensorflow as tf######################################################################################################################################################### The goal of this script is to train a pre-construct model to recognize marine mammal sound. ## See the Notebook "notebook-marine-sound-classification" in the ai-training-examples for ## more details : https://github.com/ovh/ai-training-examples/blob/main/notebooks/audio/audio-classification/notebook-marine-sound-classification.ipynb ## You must mount 2 volumes for the data and the model (the same used for the Notebook for example 😉) : ## - /workspace/saved_model where the model is stored ## - /workspace/data/ where store the data for the training ########################################################################################################################################################## 🗃 Load pre-transform datadf = pd.read_csv('/workspace/data/data.csv')# dataframe shapedf.shape# dataframe typesdf.dtypes# 🔢 Encode the labels (0 => 44) class_list = df.iloc[:,-1]encoder = LabelEncoder()y = encoder.fit_transform(class_list)print("y: ", y)# 🧹 Uniformize data thanks to the initial data input_parameters = df.iloc[:, 1:27]scaler = StandardScaler()X = scaler.fit_transform(np.array(input_parameters))print("X:", X)# ⚗️ Create training and validation setsX_train, X_val, y_train, y_val = train_test_split(X, y, test_size = 0.2)# 🧠 Define model architecturemodel = tf.keras.models.Sequential([ tf.keras.layers.Dense(512, activation='relu', input_shape=(X_train.shape[1],)), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(45, activation='softmax'),])print(model.summary())# 💪 Train the model with datamodel.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = 'accuracy')# 📈 Add the TensorBoard callback (optional)print('Model tracking')log_dir = "/workspace/saved_model/runs/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)model.fit(X_train, y_train, validation_data = (X_val, y_val), epochs = 100, batch_size = 128, callbacks = [tensorboard_callback])# 💿 Save the model for future usagesmodel.save('/workspace/saved_model/my_model2')print('End of training')
Info
L'étape tensorboard n'est pas obligatoire. C'est simplement un moyen de suivre votre entraînement.
Ensuite, créez un fichier requirements.txt pour déclarer les dépendances Python :
tensorflownumpy==1.22.4pandasscikit-learnkeras
Ensuite, créez un Dockerfile compatible avec AI Training.
Vous pouvez copier-coller le code suivant dans un fichier nommé Dockerfile :
FROM --platform=linux/x86_64 python:3.8WORKDIR /workspaceADD . /workspaceRUN pip install -r requirements.txt# Mandatory to run the jobs in rootless modeRUN chown -R 42420:42420 /workspaceCMD [ "python3" , "/workspace/train-audio-classification.py"]
Ensuite, construisez l'image Docker et envoyez-la vers le registre :
Une fois votre image Docker créée et envoyée vers le registre, vous pouvez directement utiliser la commande ovhai pour créer votre entraînement de modèle.
Vous pouvez lancer l'entraînement en spécifiant plus ou moins de GPU selon la vitesse souhaitée pour votre entraînement.