Machine Learning-modellen ontwikkelen voor productie
Sinan Ozdemir
Data Scientist, Entrepreneur, and Author
Verpakkingsmethoden
Serialisatie: een ML-model opslaan en laden
Omgeving verpakken: consistente, reproduceerbare omgeving voor het ML-model
Containerization: model, dependencies en omgeving samen in één “container”
Een sklearn-model serialiseren met pickle:
import pickle
model = ... # Train the scikit-learn model
# Serialize the model to a file
with open('model.pkl', 'wb') as f:
pickle.dump(model, f)
# Load the serialized model from the file
with open('model.pkl', 'rb') as f:
model = pickle.load(f)
Een sklearn-model serialiseren in HDF5-formaat:
import h5py
import numpy as np
from sklearn.externals import joblib
model = ... # Train the scikit-learn model
# Serialize the model to an HDF5 file
with h5py.File('model.h5', 'w') as f:
f.create_dataset('model_weights',
data=joblib.dump(model))
# Load the serialized model from the HDF5 file
with h5py.File('model.h5', 'r') as f:
model = joblib.load(f['model_weights'][:])
Een PyTorch-model serialiseren:
import torch
# Train a PyTorch model and store it in a variable
trained_model = ...
# Serialize the trained model to a file
serialized_model_path = 'model.pt'
torch.save(trained_model.state_dict(), serialized_model_path)
# Load the serialized model from a file
loaded_model = ... # Initialize the model
loaded_model.load_state_dict(
torch.load(serialized_model_path))
Een TensorFlow-model serialiseren:
import tensorflow as tf
# Train a Tensorflow model
trained_model = ...
# Save the trained model to a directory
saved_model_directory = 'model/'
tf.saved_model.save
(trained_model, saved_model_directory)
# Load the saved model from the directory
loaded_model = tf.saved_model.load(
saved_model_directory)

# Use an existing image as the base image
FROM python:3.8-slim
# Set the working directory
WORKDIR /app
# Copy the requirements file to the image
COPY requirements.txt .
# Install the required dependencies
RUN pip install -r requirements.txt
# Copy the ML model and its dependencies to the image
COPY model/ .
# Set the entrypoint to run the model
ENTRYPOINT ["python", "run_model.py"]
<---- Gebruik Python 3.8 als base image
<---- Stel de werkmap in
<---- Kopieer het bestand requirements.txt
<---- Installeer de afhankelijkheden van het model
<---- Kopieer het model in de container
<---- Geef aan hoe de container start
Serialize het getrainde ML-model met bv. pickle, HDF5 of PyTorch.
Containerize het geserialiseerde model, de dependencies en de omgeving
Deploy de Docker-image naar een doelomgeving, bv. een cloudplatform
Run de Docker-container vanaf de gedeployde image en draai het ML-model.
Use het model in de container via een API of ander toegangspunt.

Machine Learning-modellen ontwikkelen voor productie