Saltar al contenido principal

Shopper Purchase Prediction with MLflow and scikit-learn

Entrena, evalúa, registra y sirve un modelo de predicción de compras con MLflow: un control de calidad, un alias champion y una API REST que también funciona en Docker.

  • Python
  • uv
  • MLflow
  • scikit-learn
  • pandas

Capturas de pantalla

Captura 1 de 7: Portada: Shopper Purchase Prediction, código fuente en Python para MLflow, con su stack y una terminal donde la versión 1 aprueba el control de calidad y pasa a ser el champion.

Portada: Shopper Purchase Prediction, código fuente en Python para MLflow, con su stack y una terminal donde la versión 1 aprueba el control de calidad y pasa a ser el champion.

Pago único

  • 449 INR+ GST, 529,82 INR en total
  • 9 US$
  • Descárgalo desde tu biblioteca en cuanto se confirme tu pago.
  • Incluye todas las versiones futuras de este proyecto, sin costo adicional.
Última versión
1.0.0 · 28 nov 2026

Descripción general

El código fuente completo de la vida entera de un modelo en MLflow 3.18, en Python. Entrena un modelo de scikit-learn que predice qué sesiones de una tienda online terminan en compra, evalúalo frente a un control de calidad, promuévelo a champion en el Model Registry solo si supera a la versión en uso, y puntúa sesiones desde la línea de comandos, con una API REST o desde un contenedor Docker.

Entrenar un modelo es la parte fácil. Saber qué versión está en uso, por qué llegó ahí y servir exactamente esa versión es para lo que existe Shopper Purchase Prediction with MLflow and scikit-learn, con cada paso registrado en MLflow.

La vida entera de un modelo

  • Entrenar y registrar. Un modelo de scikit-learn registrado con su firma, un ejemplo de entrada, las versiones exactas de sus paquetes y su ROC AUC de prueba: 0,9258 en la primera ejecución.
  • Pasarlo por un control de calidad. ROC AUC de al menos 0,90 y exactitud balanceada de al menos 0,75 y, cuando ya hay un champion, 0,01 más de exactitud balanceada que él. Cada control es una ejecución de MLflow.
  • Promoverlo. promote registra cada modelo como una versión nueva y mueve el alias champion solo si la versión aprueba. Una versión que no aprueba conserva la etiqueta quality_gate: failed, y el champion se queda donde estaba.
  • Puntuar con el champion. predict carga la versión que sea el champion y rechaza archivos que no coinciden con la firma del modelo.
  • Servirlo. mlflow models serve pone el champion detrás de una API REST, call-api le envía sesiones, y el mismo modelo funciona en una imagen de Docker creada por MLflow. Los tres dieron las mismas probabilidades.
  • Demostrar que viaja. validate predice el ejemplo de entrada del modelo en un entorno nuevo creado con los requisitos del propio modelo.

Seguro y trazable

  • Un formato de modelo seguro. El modelo se guarda con skops, que solo carga los tipos en los que confía el proyecto, en lugar de pickle.
  • El código detrás de cada modelo. Cada ejecución guarda el commit de Git de su código.
  • Una descarga verificada. Los datos se descargan una vez y se comprueba su huella SHA-256 antes de leerlos.

Código sobre el que construir

  • Un paquete de Python limpio. Una estructura src gestionada con uv, con seis comandos: train, evaluate, promote, predict, validate y call-api.
  • La configuración en un solo sitio. pydantic-settings lee .env, y .env.example documenta cada ajuste.
  • Versiones exactas. uv.lock fija cada paquete: MLflow 3.18.0, scikit-learn 1.9.1, skops 0.16.0 y Python 3.15.
  • Sin datos en el archivo. El proyecto descarga el dataset público en la primera ejecución.

Lo que no incluye

  • Sin hosting. Se ejecuta en tu propio equipo: un servidor de seguimiento que inicias con un solo comando, y un servidor de modelos o un contenedor en el mismo equipo.
  • Sin proyecto de pruebas. Los resultados de arriba vienen de ejecuciones reales, no de pruebas automáticas incluidas en el archivo.

Ponlo en marcha en siete pasos

  1. Descomprime el archivo.
  2. Inicia un servidor de seguimiento de MLflow.
  3. Copia .env.example a .env.
  4. Instala los paquetes con uv sync.
  5. Pon el proyecto en Git.
  6. Entrena con uv run train.
  7. Promueve el modelo con uv run promote.

El README tiene todos los comandos, para macOS y Linux y para PowerShell, además del servidor de modelos y Docker. How to Set Up and Run the Shopper Purchase Prediction Project (se abre en una pestaña nueva) (en inglés) muestra cada paso con lo que debería imprimir. Se probó desde una copia limpia del archivo en macOS.

Cómo se construyó

Las partes 6 a 9 de la serie de tutoriales gratuita MLflow Tutorial for Machine Learning in Python (se abre en una pestaña nueva) (en inglés) explican cómo registrar y validar modelos, la evaluación y los controles de calidad, el Model Registry y cómo servir modelos, con este código.

Serie de tutoriales gratuita

MLflow Tutorial for Machine Learning in Python

¿Prefieres aprender construyéndolo? Esta guía gratuita y paso a paso en nuestro blog muestra cómo se hace el proyecto.

Leer la serie (se abre en una pestaña nueva)

Qué te llevas

Todo lo que hay en el archivo, de un vistazo.

  • Versión 1.0.0 del código fuente completo: un paquete de Python gestionado con uv
  • El comando train: un modelo de scikit-learn registrado en MLflow con su firma, ejemplo de entrada, requisitos y ROC AUC de prueba
  • El comando evaluate y un control de calidad sobre ROC AUC y exactitud balanceada, con comparación frente a un modelo de referencia
  • El comando promote, que registra cada modelo y mueve el alias champion solo si la versión nueva aprueba
  • El comando predict, que puntúa un CSV de sesiones con el champion y lo valida con la firma del modelo
  • El comando validate, que predice en un entorno nuevo creado con los requisitos del modelo
  • El comando call-api para un modelo servido con mlflow models serve o desde la imagen de Docker de MLflow
  • Tres sesiones de ejemplo en CSV y como cuerpo de una petición REST
  • Configuración en .env con pydantic-settings y un .env.example documentado
  • Un README con la instalación para macOS, Linux y PowerShell, el servidor de modelos, Docker, cada ajuste y la cita del dataset

Construido con

Los entornos y las versiones exactos con los que se creó y se probó.

  • Python3.15.2
  • uv0.13.10
  • MLflow3.18.0
  • scikit-learn1.9.1
  • pandas3.1.1
  • NumPy2.5.5
  • skops0.16.0
  • pydantic-settings2.16.3
  • Requests2.34.2
  • Docker Engine29.9.3

Qué contiene el archivo

El árbol de carpetas que obtienes al descomprimirlo.

shopper-purchase-prediction-mlflow-scikit-learn/

  • src/
    • shopper_purchase_prediction/
      • __init__.py
      • call_api.py
      • code_version.py
      • config.py
      • data.py
      • evaluate.py
      • model.py
      • predict.py
      • promote.py
      • registry.py
      • train.py
      • validate.py
  • examples/
    • sessions.csv
    • sessions.json
  • .env.example
  • .gitignore
  • .python-version
  • pyproject.toml
  • uv.lock
  • README.md

Qué necesita de ti

Las cuentas y los servicios que espera encontrar, para que nada te sorprenda.

  • uv, que instala Python 3.15 y los paquetes por ti
  • Git, para que cada ejecución guarde el commit de su código
  • Un servidor de seguimiento de MLflow: el README inicia uno en tu equipo con un solo comando
  • Conexión a internet para la primera instalación, unos 580 MB de paquetes, y la primera ejecución, que descarga los datos
  • Opcional: Docker, para ejecutar el modelo en un contenedor

Versiones

Todas las versiones hasta ahora, de la más reciente a la más antigua.

  1. 1.0.0Más reciente

    Primera versión del código fuente completo.

    • Entrena un modelo de scikit-learn que predice qué sesiones de una tienda online terminan en compra y lo registra en MLflow 3.18.0.
    • Evalúa los modelos frente a un control de calidad, los registra y promueve una versión a champion solo si aprueba.
    • Puntúa sesiones con el champion desde la línea de comandos, con mlflow models serve y desde una imagen de Docker.
    • Incluye un README que te lleva del archivo a un champion que sirve predicciones.

Source Code Licence

Qué puedes hacer con él

What you may and may not do with the source code you buy.

Leer la licencia completa
  1. What this licence covers

This licence governs every file included in a product you buy from Dewiride Store: source code, configuration, database scripts, sample data, documentation and any other file in the download. It takes effect when your payment is confirmed and applies to every release of that product that reaches your library. Files that reach your library through an annual updates membership are governed in exactly the same way.

It forms part of the Terms of Sale and Use. Where a product page states different or additional licence terms for that product, those terms prevail for that product. The membership page may likewise state different or additional licence terms for the files a membership carries, and those terms then prevail for those files.

  1. The licence we grant you

We grant you a perpetual, worldwide, non-exclusive, non-transferable licence to use, reproduce, adapt, translate and modify the files, and to include the result in your own work, on the conditions set out below.

Perpetual means it does not expire. Worldwide means it is not limited to any country. Non-exclusive means we license the same product to other customers. Non-transferable means you cannot pass it on to someone else.

The licence is granted to you — either you personally, or the organisation you identified when buying. Everyone working within that organisation may use the files for that organisation’s projects. Nobody outside it may.

  1. What you may do
  • Use and change the files in your own projects, commercial or otherwise, with no limit on the number of projects.
  • Build a product or a service on them and charge your own customers for it.
  • Deploy the result for a client, as part of work you are doing for that client.
  • Distribute the result in compiled, deployed or otherwise non-source form.
  • Keep as many back-up copies as you reasonably need.
  • Study, observe and test how the code works, and obtain the information you need to make it work with your own software.

The last two are yours by law under sections 52(1)(aa) to (ac) of the Indian Copyright Act, 1957, and nothing in this licence is intended to take them away.

  1. What you may not do
  • Resell, sublicense, redistribute or publish the files themselves, in whole or in substantial part, in source form.
  • Include them in a template, starter kit, course, tutorial repository or component library that you sell or give away, where the code is the thing being supplied.
  • Share your account, your download links or your invoices with anyone outside your organisation.
  • Publish the files in a public repository, or in any other place where they can be obtained without buying them.
  • Remove or obscure the copyright and attribution notices in the source files.
  • Use the files to build something whose main purpose is to compete with Dewiride Store as a supplier of the same code.

The distinction that matters is simple: you may sell what you build with the code; you may not sell the code.

  1. Third-party components

Our products depend on open-source libraries, frameworks and services that we did not write. Those remain under their own licences, which we do not and cannot change. Where a product includes or requires such a component, its licence is named in the product’s documentation, and complying with it is your responsibility.

  1. Releases

Every release of a product you own is covered by this same licence and appears in your library at no extra cost. A release you have already downloaded remains licensed to you even if we later stop publishing the product. A release that reached your library through an annual updates membership is licensed to you on these same terms, and stays licensed after the period that carried it has ended.

  1. Ownership

We keep ownership of the files and of the copyright in them. You own whatever you create with them: your changes, your additions and the product you build are yours.

  1. If this licence ends

This licence ends if you materially breach it and do not put the breach right within thirty days of us asking you to in writing. It also ends if your payment is reversed or refunded, because the purchase it depends on no longer stands. Where a membership period is refunded or reversed, the licence ends for the releases that period carried and for nothing else: anything you bought separately, or that another period carried, is unaffected.

If it ends, you must stop using the files and delete the copies you hold. Work you had already delivered to a client before that point may continue in use, so that ending this licence never breaks something your own customer relies on.

  1. No warranty beyond the description

The warranties and limits in section 19 and section 20 of the Terms of Sale and Use apply to this licence as well.

  1. Governing law

This licence is governed by the law of India, and section 24 of the Terms of Sale and Use applies to any dispute about it. If a translation and the English version differ in meaning, the English version governs.