repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
mlflow | examples/spark_udf/spark_udf_with_prebuilt_env.py | .py | """
This example code shows how to use `mlflow.pyfunc.spark_udf` with Databricks Connect
outside Databricks runtime.
"""
import os
from databricks.connect import DatabricksSession
from databricks.sdk import WorkspaceClient
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
import mlflow
... | 45 | 1,465 |
mlflow | examples/spacy/train.py | .py | import random
import spacy
from packaging.version import Version
from spacy.training import Example
from spacy.util import compounding, minibatch
import mlflow.spacy
IS_SPACY_VERSION_NEWER_THAN_OR_EQUAL_TO_3_0_0 = Version(spacy.__version__).major >= 3
# training data
TRAIN_DATA = [
("Who is Shaka Khan?", {"enti... | 66 | 2,246 |
mlflow | examples/quickstart/mlflow_tracking.py | .py | import os
from random import randint, random
from mlflow import log_artifacts, log_metric, log_param
if __name__ == "__main__":
print("Running mlflow_tracking.py")
log_param("param1", randint(0, 100))
log_metric("foo", random())
log_metric("foo", random() + 1)
log_metric("foo", random() + 2)
... | 21 | 494 |
mlflow | examples/gemini/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for Gemini.
For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html
"""
import os
import mlflow
# Turn on auto tracing for Gemini by calling mlflow.gemini.autolog()
mlflow.gemini.autolog()
# Impo... | 40 | 1,328 |
mlflow | examples/sklearn_elasticnet_wine/train.py | .py | # The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality
# P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.
# Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009.
import logging
import sys
i... | 93 | 3,286 |
mlflow | examples/pyspark_ml_autologging/pipeline.py | .py | from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.feature import StandardScaler, VectorAssembler
from pyspark.sql import SparkSession
from sklearn.datasets import load_iris
import mlflow
with SparkSession.builder.getOrCreate() as spark:
mlflow.pyspark.ml.auto... | 34 | 1,250 |
mlflow | examples/pyspark_ml_autologging/logistic_regression.py | .py | from pyspark.ml.classification import LogisticRegression
from pyspark.ml.feature import VectorAssembler
from pyspark.sql import SparkSession
from sklearn.datasets import load_iris
import mlflow
with SparkSession.builder.getOrCreate() as spark:
df = load_iris(as_frame=True).frame.rename(columns={"target": "label"}... | 22 | 718 |
mlflow | examples/pyspark_ml_autologging/one_vs_rest.py | .py | from pyspark.ml.classification import LogisticRegression, OneVsRest
from pyspark.ml.feature import VectorAssembler
from pyspark.sql import SparkSession
from sklearn.datasets import load_iris
import mlflow
with SparkSession.builder.getOrCreate() as spark:
df = load_iris(as_frame=True).frame.rename(columns={"target... | 23 | 765 |
mlflow | examples/ray_serve/train_model.py | .py | from sklearn.datasets import load_iris
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import mean_squared_error
from sklearn.utils import shuffle
import mlflow
if __name__ == "__main__":
# Enable auto-logging
mlflow.set_tracking_uri("sqlite:///mlruns.db")
mlflow.sklearn.autol... | 42 | 1,252 |
mlflow | examples/strands/tracing.py | .py | import mlflow
mlflow.strands.autolog()
mlflow.set_experiment("Strand Agent")
from strands import Agent
from strands.models.openai import OpenAIModel
from strands_tools import calculator
model = OpenAIModel(
client_args={"api_key": "<api-key>"},
# **model_config
model_id="gpt-4o",
params={
"ma... | 23 | 470 |
mlflow | examples/diffusers/demo_diffusers_adapter.py | .py | """
Demo: MLflow Diffusers Adapter Flavor (LoRA)
This script demonstrates the full workflow of logging and loading a diffusion
model LoRA adapter using the native mlflow.diffusers flavor.
No GPU or real model weights required — uses a fake adapter for validation.
"""
import tempfile
from pathlib import Path
import ... | 114 | 4,203 |
mlflow | examples/tracing/multithreading.py | .py | """
This example demonstrates how to create a trace to track the execution of a multi-threaded application.
To trace a multi-threaded operation, you need to use the low-level MLflow client APIs to create a trace and spans, because the high-level fluent APIs are not thread-safe.
"""
import contextvars
from concurrent.... | 65 | 1,818 |
mlflow | examples/tracing/langchain_auto.py | .py | """
This example demonstrates how to enable automatic tracing for LangChain.
Note: this example requires the `langchain` and `langchain-openai` package to be installed.
"""
import json
import os
from langchain.prompts import PromptTemplate
from langchain.schema.output_parser import StrOutputParser
from langchain_ope... | 51 | 1,810 |
mlflow | examples/tracing/client.py | .py | """
This example demonstrates how to create a trace with multiple spans using the low-level MLflow client APIs.
"""
import mlflow
exp = mlflow.set_experiment("mlflow-tracing-example")
exp_id = exp.experiment_id
# Initialize MLflow client.
client = mlflow.MlflowClient()
def run(x: int, y: int) -> int:
# Create ... | 102 | 2,995 |
mlflow | examples/tracing/fluent.py | .py | """
This example demonstrates how to create a trace with multiple spans using the high-level MLflow fluent APIs.
"""
import mlflow
mlflow.set_experiment("mlflow-tracing-example")
# Decorating the function with `@mlflow.trace` decorator is the easiest way to trace your function.
# MLflow will create a trace for func... | 59 | 1,705 |
mlflow | examples/pytorch/mnist_tensorboard_artifact.py | .py | #
# Trains an MNIST digit recognizer using PyTorch, and uses tensorboardX to log training metrics
# and weights in TensorBoard event format to the MLflow run's artifact directory. This stores the
# TensorBoard events in MLflow for later access using the TensorBoard command line tool.
#
# NOTE: This example requires you... | 253 | 8,353 |
mlflow | examples/pytorch/torchscript/IrisClassification/iris_classification.py | .py | import argparse
import torch
import torch.nn.functional as F
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from torch import nn
import mlflow.pytorch
from mlflow.models import infer_signature
class IrisClassifier(nn.Module):
... | 106 | 3,339 |
mlflow | examples/pytorch/torchscript/MNIST/mnist_torchscript.py | .py | import argparse
import torch
import torch.nn.functional as F
from torch import nn, optim
from torch.optim.lr_scheduler import StepLR
from torchvision import datasets, transforms
import mlflow
import mlflow.pytorch
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2... | 197 | 6,202 |
mlflow | examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | .py | """
Getting started with Captum - Titanic Data Analysis
"""
# Initial imports
import os
from argparse import ArgumentParser
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from captum.attr import IntegratedGradients, LayerConductance, NeuronConductance
from prettytable import Prett... | 347 | 14,340 |
mlflow | examples/pytorch/HPOExample/hpo_mnist.py | .py | """
Hyperparameter Optimization Example with Pure PyTorch and MLflow
This example demonstrates:
- Using MLflow to track hyperparameter optimization trials
- Parent/child run structure for organizing HPO experiments
- Pure PyTorch training (no Lightning dependencies)
- Simple MNIST classification with configurable hype... | 158 | 5,410 |
mlflow | examples/pytorch/MNIST/mnist_autolog_example.py | .py | #
# Trains an MNIST digit recognizer using PyTorch Lightning,
# and uses MLflow to log metrics, params and artifacts
# NOTE: This example requires you to first install
# pytorch-lightning (using pip install pytorch-lightning)
# and mlflow (using pip install mlflow).
#
import os
import lightning as L
import tor... | 261 | 7,388 |
mlflow | examples/multistep_workflow/etl_data.py | .py | """
Converts the raw CSV form to a Parquet form with just the columns we want
"""
import os
import tempfile
import click
import pyspark
import mlflow
@click.command(
help="Given a CSV file (see load_raw_data), transforms it into Parquet "
"in an mlflow artifact called 'ratings-parquet-dir'"
)
@click.option... | 45 | 1,412 |
mlflow | examples/multistep_workflow/main.py | .py | """
Downloads the MovieLens dataset, ETLs it into Parquet, trains an
ALS model, and uses the ALS model to train a Keras neural network.
See README.md for more details.
"""
import os
import click
import mlflow
from mlflow.entities import RunStatus
from mlflow.tracking import MlflowClient
from mlflow.tracking.fluent ... | 108 | 4,405 |
mlflow | examples/multistep_workflow/load_raw_data.py | .py | """
Downloads the MovieLens dataset and saves it as an artifact
"""
import os
import tempfile
import zipfile
import click
import requests
import mlflow
@click.command(
help="Downloads the MovieLens dataset and saves it as an mlflow artifact "
"called 'ratings-csv-dir'."
)
@click.option("--url", default="ht... | 44 | 1,292 |
mlflow | examples/multistep_workflow/als.py | .py | """
Trains an Alternating Least Squares (ALS) model for user/movie ratings.
The input is a Parquet ratings dataset (see etl_data.py), and we output
an mlflow artifact called 'als-model'.
"""
import click
import pyspark
from pyspark.ml import Pipeline
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.m... | 71 | 2,369 |
mlflow | examples/multistep_workflow/train_keras.py | .py | """
Trains a Keras model for user/movie ratings. The input is a Parquet
ratings dataset (see etl_data.py) and an ALS model (see als.py), which we
will use to supplement our input and train using.
"""
from itertools import chain
import click
import numpy as np
import pandas as pd
import pyspark
import tensorflow as tf... | 118 | 4,436 |
mlflow | examples/demos/mlflow-3/genai.py | .py | # MLflow 3 GenAI Example
# In this example, we will create an agent and then evaluate its performance. First, we will define the agent and log it to MLflow.
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
import mlflow
# Define the chain
chat_model = ChatOpenAI(name="gpt... | 47 | 1,955 |
mlflow | examples/demos/mlflow-3/ml.py | .py | # MLflow 3 Traditional ML Example
# In this example, we will first run a model training job, which is tracked as
# an MLflow Run, to produce a trained model, which is tracked as an MLflow Logged Model.
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.linear_model import ElasticNet
from sklearn.me... | 114 | 4,450 |
mlflow | examples/demos/mlflow-3/deep_learning.py | .py | # # MLflow 3 Deep Learning Example
# In this example, we will first run a model training job, which is tracked as an MLflow Run.
# Every 10 epochs, we will store model checkpoints, which are tracked as MLflow Logged Models.
# We will then select the best checkpoint for production deployment.
import pandas as pd
import ... | 126 | 4,575 |
mlflow | examples/databricks/multipart.py | .py | """
Benchmark for multi-part upload and download of artifacts.
"""
import hashlib
import json
import os
import pathlib
import tempfile
from concurrent.futures import ThreadPoolExecutor, as_completed
import pandas as pd
import psutil
from tqdm.auto import tqdm
import mlflow
from mlflow.environment_variables import (
... | 149 | 4,167 |
mlflow | examples/databricks/dbconnect.py | .py | """
python examples/databricks/dbconnect.py --cluster-id <cluster-id>
"""
import argparse
from databricks.connect import DatabricksSession
from databricks.sdk import WorkspaceClient
from pyspark.sql.types import DoubleType
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
import mlflow
... | 57 | 1,532 |
mlflow | examples/databricks/log_runs.py | .py | """
Logs MLflow runs in Databricks from an external host.
How to run:
$ python examples/databricks/log_runs.py --host <host> --token <token> --user <user> [--experiment-id 123]
See also:
https://docs.databricks.com/dev-tools/api/latest/authentication.html#generate-a-personal-access-token
"""
import argparse
import o... | 57 | 1,756 |
mlflow | examples/paddle/train_high_level_api.py | .py | import numpy as np
import paddle
import mlflow.paddle
train_dataset = paddle.text.datasets.UCIHousing(mode="train")
eval_dataset = paddle.text.datasets.UCIHousing(mode="test")
class UCIHousing(paddle.nn.Layer):
def __init__(self):
super().__init__()
self.fc_ = paddle.nn.Linear(13, 1, None)
... | 35 | 965 |
mlflow | examples/paddle/train_low_level_api.py | .py | import numpy as np
import paddle
import paddle.nn.functional as F
from paddle.nn import Linear
from sklearn import preprocessing
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
import mlflow.paddle
def load_data():
X, y = load_diabetes(return_X_y=True)
min_max... | 82 | 2,542 |
mlflow | examples/ag2/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for AutoGen.
For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html
"""
import os
from typing import Annotated, Literal
from autogen import ConversableAgent
import mlflow
# Turn on auto tracing ... | 64 | 1,913 |
mlflow | examples/langchain/retrieval_qa_chain_azure_openai.py | .py | import os
import tempfile
from langchain.chains import RetrievalQA
from langchain.document_loaders import TextLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import FAISS
from langchain_openai import AzureOpenAI, AzureOpenAIEmbeddings
import mlflow
# Set this to `azure`
o... | 64 | 2,472 |
mlflow | examples/langchain/chain_as_code_driver.py | .py | # This is an example for logging a Langchain model from code using the
# mlflow.langchain.log_model API. When a path to a valid Python script is submitted to the
# lc_model argument, the model code itself is serialized instead of the model object.
# Within the targeted script, the model implementation must be defined a... | 40 | 1,267 |
mlflow | examples/langchain/retriever_chain.py | .py | import os
import tempfile
from langchain.document_loaders import TextLoader
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import FAISS
import mlflow
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY e... | 43 | 1,620 |
mlflow | examples/langchain/chain_autolog.py | .py | import os
from operator import itemgetter
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnableLambda
import mlflow
# Uncomment the following to use the full abilities of langchain autol... | 71 | 2,122 |
mlflow | examples/langchain/chain_as_code.py | .py | # This example demonstrates defining a model directly from code.
# This feature allows for defining model logic within a python script, module, or notebook that is stored
# directly as serialized code, as opposed to object serialization that would otherwise occur when saving
# or logging a model object.
# This script d... | 65 | 2,123 |
mlflow | examples/langchain/retrieval_qa_chain.py | .py | import os
import tempfile
from langchain.chains import RetrievalQA
from langchain.document_loaders import TextLoader
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.llms import OpenAI
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import FAISS
import mlfl... | 47 | 1,696 |
mlflow | examples/langchain/simple_chain.py | .py | import os
from langchain.chains import LLMChain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
import mlflow
# Ensure the OpenAI API key is set in the environment
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
# Initialize the OpenAI mode... | 31 | 979 |
mlflow | examples/langchain/chain_stream_output.py | .py | import os
from langchain.llms import OpenAI
from langchain_core.output_parsers import StrOutputParser
import mlflow
# Ensure the OpenAI API key is set in the environment
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
# Initialize the OpenAI model and the prompt template... | 24 | 692 |
mlflow | examples/langchain/simple_agent.py | .py | import os
from langchain.agents import AgentType, initialize_agent, load_tools
from langchain.llms import OpenAI
import mlflow
# Note: Ensure that the package 'google-search-results' is installed via pypi to run this example
# and that you have a accounts with SerpAPI and OpenAI to use their APIs.
# Ensuring necess... | 37 | 1,463 |
mlflow | examples/groq/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for Groq.
For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html
"""
import groq
import mlflow
# Turn on auto tracing for Groq by calling mlflow.groq.autolog()
mlflow.groq.autolog()
client = gro... | 28 | 631 |
mlflow | examples/sklearn_elasticnet_diabetes/osx/train_diabetes.py | .py | #
# train_diabetes.py
#
# MLflow model using ElasticNet (sklearn) and Plots ElasticNet Descent Paths
#
# Uses the sklearn Diabetes dataset to predict diabetes progression using ElasticNet
# The predicted "progression" column is a quantitative measure of disease progression one year after baseline
# http... | 126 | 4,087 |
mlflow | examples/tensorflow/train.py | .py | # tensorflow 2.x core api
import tensorflow as tf
from sklearn.datasets import load_diabetes
import mlflow
from mlflow.models import infer_signature
class Normalize(tf.Module):
"""Data Normalization class"""
def __init__(self, x):
# Initialize the mean and standard deviation for normalization
... | 168 | 5,925 |
mlflow | examples/docker/train.py | .py | # The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality
# P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.
# Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009.
import argparse
import os
i... | 71 | 2,316 |
mlflow | examples/system_metrics/collect_system_metrics.py | .py | import time
import mlflow
if __name__ == "__main__":
mlflow.enable_system_metrics_logging()
with mlflow.start_run() as run:
time.sleep(11)
client = mlflow.MlflowClient()
mlflow_run = client.get_run(run.info.run_id)
print(mlflow_run.data.metrics)
| 13 | 277 |
mlflow | examples/mlflow_artifacts/example.py | .py | import os
import tempfile
from pprint import pprint
import mlflow
from mlflow.artifacts import download_artifacts
from mlflow.tracking import MlflowClient
def save_text(path, text):
with open(path, "w") as f:
f.write(text)
def log_artifacts():
# Upload artifacts
with mlflow.start_run() as run, ... | 54 | 1,475 |
mlflow | examples/smolagents/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for Smolagents.
For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html
"""
from smolagents import CodeAgent, LiteLLMModel
import mlflow
# Turn on auto tracing for Smolagents by calling mlflow.smol... | 19 | 591 |
mlflow | examples/lightgbm/lightgbm_sklearn/utils.py | .py | from mlflow.tracking import MlflowClient
def yield_artifacts(run_id, path=None):
"""Yield all artifacts in the specified run"""
client = MlflowClient()
for item in client.list_artifacts(run_id, path):
if item.is_dir:
yield from yield_artifacts(run_id, item.path)
else:
... | 27 | 863 |
mlflow | examples/lightgbm/lightgbm_sklearn/train.py | .py | from pprint import pprint
import lightgbm as lgb
from sklearn.datasets import load_iris
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from utils import fetch_logged_data
import mlflow
import mlflow.lightgbm
def main():
# prepare example dataset
X, y = load_iris(re... | 37 | 1,034 |
mlflow | examples/lightgbm/lightgbm_native/train.py | .py | import argparse
import lightgbm as lgb
import matplotlib as mpl
from sklearn import datasets
from sklearn.metrics import accuracy_score, log_loss
from sklearn.model_selection import train_test_split
import mlflow
import mlflow.lightgbm
mpl.use("Agg")
def parse_args():
parser = argparse.ArgumentParser(descripti... | 80 | 2,107 |
mlflow | examples/model_config/simple.py | .py | import mlflow
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
python_model="model.py",
model_config={"timeout": 10},
input_example=["hello"],
)
# model = mlflow.pyfunc.load_model(model_info.model_uri, model_config={"timeout": 10})
# print(model.pre... | 14 | 335 |
mlflow | examples/model_config/model.py | .py | from mlflow.models import ModelConfig, set_model
def predict(model_input):
model_config = ModelConfig()
timeout = model_config.get("timeout")
return [timeout] * len(model_input)
set_model(predict)
| 11 | 213 |
mlflow | examples/mistral/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for Mistral AI.
For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html
"""
import os
from mistralai import Mistral
import mlflow
# Turn on auto tracing for Mistral AI by calling mlflow.mistral.a... | 30 | 762 |
mlflow | examples/haystack/tracing.py | .py | import os
from getpass import getpass
from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.components.routers import Condition... | 150 | 5,807 |
mlflow | examples/deployments/databricks/databricks.py | .py | """
Usage
-----
databricks secrets create-scope <scope>
databricks secrets put-secret <scope> openai-api-key --string-value $OPENAI_API_KEY
python examples/deployments/databricks.py --secret <scope>/openai-api-key
-----
"""
import argparse
import uuid
from mlflow.deployments import get_deploy_client
def parse_args(... | 113 | 3,165 |
mlflow | examples/rest_api/mlflow_tracking_rest_api.py | .py | """
This simple example shows how you could use MLflow REST API to create new
runs inside an experiment to log parameters/metrics. Using MLflow REST API
instead of MLflow library might be useful to embed in an application where
you don't want to depend on the whole MLflow library, or to make
your own HTTP requests in ... | 142 | 4,353 |
mlflow | examples/auth/auth.py | .py | import os
import uuid
import mlflow.server
class User:
MLFLOW_TRACKING_USERNAME = "MLFLOW_TRACKING_USERNAME"
MLFLOW_TRACKING_PASSWORD = "MLFLOW_TRACKING_PASSWORD"
def __init__(self, username, password) -> None:
self.username = username
self.password = password
self.env = {}
... | 67 | 1,883 |
mlflow | examples/evaluation/evaluate_on_regressor.py | .py | from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import mlflow
diabetes_dataset = load_diabetes()
X_train, X_test, y_train, y_test = train_test_split(
diabetes_dataset.data, diabetes_dataset.target, test_size=0.33, r... | 29 | 848 |
mlflow | examples/evaluation/evaluate_with_qa_metrics.py | .py | import openai
import pandas as pd
import mlflow
eval_df = pd.DataFrame({
"inputs": [
"What is MLflow?",
"What is Spark?",
"What is Python?",
],
"ground_truth": [
"MLflow is an open-source platform for managing the end-to-end machine learning (ML) lifecycle. It was developed... | 42 | 2,117 |
mlflow | examples/evaluation/evaluate_with_static_dataset.py | .py | import shap
import xgboost
from sklearn.model_selection import train_test_split
import mlflow
# Load the UCI Adult Dataset
X, y = shap.datasets.adult()
# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# Fit an XGBoost binary clas... | 34 | 908 |
mlflow | examples/evaluation/evaluate_with_llm_judge.py | .py | import os
import openai
import pandas as pd
import mlflow
from mlflow.metrics.genai import EvaluationExample, answer_similarity
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
# testing with OpenAI gpt-4o-mini
example = EvaluationExample(
input="What is MLflow?",
... | 68 | 3,304 |
mlflow | examples/evaluation/evaluate_with_custom_metrics.py | .py | import os
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import mlflow
from mlflow.models import infer_signature, make_metric
# loading the diabetes dataset
diabetes_d... | 86 | 2,699 |
mlflow | examples/evaluation/evaluate_with_model_validation.py | .py | import shap
import xgboost
from sklearn.dummy import DummyClassifier
from sklearn.model_selection import train_test_split
import mlflow
from mlflow.models import MetricThreshold, infer_signature, make_metric
# load UCI Adult Data Set; segment it into training and test sets
X, y = shap.datasets.adult()
X_train, X_test... | 111 | 3,974 |
mlflow | examples/evaluation/evaluate_with_custom_metrics_comprehensive.py | .py | import numpy as np
import pandas as pd
from matplotlib.figure import Figure
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import mlflow
from mlflow.models import infer_signature, make_metric
# loading the diabetes data... | 85 | 2,642 |
mlflow | examples/evaluation/evaluate_on_binary_classifier.py | .py | import shap
import xgboost
from sklearn.model_selection import train_test_split
import mlflow
from mlflow.models import infer_signature
# Load the UCI Adult Dataset
X, y = shap.datasets.adult()
# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, rand... | 42 | 1,169 |
mlflow | examples/evaluation/evaluate_with_function.py | .py | import shap
import xgboost
from sklearn.model_selection import train_test_split
import mlflow
# Load the UCI Adult Dataset
X, y = shap.datasets.adult()
# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# Fit an XGBoost binary clas... | 38 | 928 |
mlflow | examples/evaluation/evaluate_on_multiclass_classifier.py | .py | from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import mlflow
X, y = make_classification(n_samples=10000, n_classes=10, n_informative=5, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, ... | 26 | 881 |
mlflow | examples/evaluation/evaluate_with_custom_code_metrics.py | .py | import os
import openai
import pandas as pd
import mlflow
from mlflow.metrics import make_metric
from mlflow.metrics.base import MetricValue, standard_aggregations
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
# Helper function to check if a string is valid python cod... | 68 | 1,783 |
mlflow | examples/catboost/train.py | .py | # Based on the official regression example:
# https://catboost.ai/docs/concepts/python-usages-examples.html#regression
import numpy as np
from catboost import CatBoostRegressor
import mlflow
from mlflow.models import infer_signature
# Initialize data
train_data = np.array([[1, 4, 5, 6], [4, 5, 6, 7], [30, 40, 50, 60... | 39 | 1,057 |
mlflow | examples/statsmodels/train.py | .py | import argparse
import numpy as np
import statsmodels.api as sm
from sklearn.metrics import mean_squared_error
import mlflow
import mlflow.statsmodels
def parse_args():
parser = argparse.ArgumentParser(description="Statsmodels example")
parser.add_argument(
"--inverse-method",
type=str,
... | 56 | 1,332 |
mlflow | examples/pyfunc/custom_code.py | .py | flower_classes = ["setosa", "versicolor", "virginica"]
def iris_classes(preds):
return [flower_classes[x] for x in preds]
| 6 | 128 |
mlflow | examples/pyfunc/infer_model_code_paths.py | .py | from typing import Any
from custom_code import iris_classes
import mlflow
class CustomPredict(mlflow.pyfunc.PythonModel):
"""Custom pyfunc class used to create customized mlflow models"""
def predict(self, context, model_input, params: dict[str, Any] | None = None):
prediction = [x % 3 for x in mod... | 24 | 666 |
mlflow | examples/pyfunc/train.py | .py | import os
from typing import Any
from custom_code import iris_classes
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
import mlflow
from mlflow.models import infer_signature
class CustomPredict(mlflow.pyfunc.PythonModel):
"""Custom pyfunc class used to create customize... | 44 | 1,467 |
mlflow | examples/pyfunc/model_as_code.py | .py | # This example demonstrates defining a model directly from code.
# This feature allows for defining model logic within a python script, module, or notebook that is stored
# directly as serialized code, as opposed to object serialization that would otherwise occur when saving
# or logging a model object.
# This script d... | 53 | 1,998 |
mlflow | examples/pyfunc/model_as_code_driver.py | .py | # This is an example for logging a Python model from code using the
# mlflow.pyfunc.log_model API. When a path to a valid Python script is submitted to the
# python_model argument, the model code itself is serialized instead of the model object.
# Within the targeted script, the model implementation must be defined and... | 29 | 1,013 |
mlflow | examples/openai/embeddings.py | .py | import os
import numpy as np
import openai
import mlflow
from mlflow.models.signature import ModelSignature
from mlflow.types.schema import ColSpec, ParamSchema, ParamSpec, Schema, TensorSpec
assert "OPENAI_API_KEY" in os.environ, " OPENAI_API_KEY environment variable must be set"
print(
"""
# ****************... | 54 | 1,543 |
mlflow | examples/openai/chat_completions.py | .py | import logging
import os
import openai
import pandas as pd
import mlflow
from mlflow.models.signature import ModelSignature
from mlflow.types.schema import ColSpec, ParamSchema, ParamSpec, Schema
logging.getLogger("mlflow").setLevel(logging.ERROR)
# Uncomment the following lines to run this script without using a r... | 189 | 4,976 |
mlflow | examples/openai/completions.py | .py | import os
import openai
import mlflow
from mlflow.models.signature import ModelSignature
from mlflow.types.schema import ColSpec, ParamSchema, ParamSpec, Schema
assert "OPENAI_API_KEY" in os.environ, " OPENAI_API_KEY environment variable must be set"
print(
"""
# ************************************************... | 57 | 1,869 |
mlflow | examples/openai/azure_openai.py | .py | import openai
import pandas as pd
import mlflow
"""
Set environment variables for Azure OpenAI service
export OPENAI_API_KEY="<AZURE OPENAI KEY>"
# OPENAI_API_BASE should be the endpoint of your Azure OpenAI resource
# e.g. https://<service-name>.openai.azure.com/
export OPENAI_API_BASE="<AZURE OPENAI BASE>"
# OPENAI... | 64 | 1,663 |
mlflow | examples/openai/spark_udf.py | .py | import os
import openai
from pyspark.sql import SparkSession
import mlflow
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
with mlflow.start_run():
model_info = mlflow.openai.log_model(
model="gpt-4o-mini",
task=openai.chat.completions,
messag... | 31 | 855 |
mlflow | examples/openai/autologging/module_client.py | .py | import os
import openai
import mlflow
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
mlflow.openai.autolog(
log_input_examples=True,
log_model_signatures=True,
log_models=True,
registered_model_name="openai_model",
)
messages = [
{
"role": "... | 36 | 848 |
mlflow | examples/openai/autologging/instantiated_client.py | .py | import argparse
import os
import openai
import mlflow
mlflow.openai.autolog(
log_input_examples=True,
log_model_signatures=True,
log_models=True,
registered_model_name="openai_model",
)
parser = argparse.ArgumentParser()
parser.add_argument("--api-key", type=str, help="OpenAI API key")
args = parser... | 45 | 1,176 |
mlflow | examples/anthropic/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for Anthropic.
For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html
"""
import os
import anthropic
import mlflow
# Turn on auto tracing for Anthropic by calling mlflow.anthropic.autolog()
mlfl... | 28 | 684 |
mlflow | examples/sentence_transformers/simple.py | .py | from sentence_transformers import SentenceTransformer
import mlflow
import mlflow.sentence_transformers
model = SentenceTransformer("all-MiniLM-L6-v2")
example_sentences = ["This is a sentence.", "This is another sentence."]
# Define the signature
signature = mlflow.models.infer_signature(
model_input=example_s... | 43 | 1,360 |
mlflow | examples/remote_store/remote_server.py | .py | import os
import random
import shutil
import sys
import tempfile
from mlflow import (
MlflowClient,
active_run,
get_artifact_uri,
get_tracking_uri,
log_artifact,
log_artifacts,
log_metric,
log_param,
)
if __name__ == "__main__":
print(f"Running {sys.argv[0]} with tracking URI {get_... | 43 | 1,198 |
mlflow | examples/sklearn_logistic_regression/train.py | .py | import numpy as np
from sklearn.linear_model import LogisticRegression
import mlflow
import mlflow.sklearn
from mlflow.models import infer_signature
if __name__ == "__main__":
X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)
y = np.array([0, 0, 1, 1, 1, 0])
lr = LogisticRegression()
lr.fit(X, y)
... | 20 | 642 |
mlflow | examples/gateway/gemini/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Gemini endpoints: {client.list_endpoints()}\n")
print(f"Gemini completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Chat example
response_chat = clie... | 63 | 1,885 |
mlflow | examples/gateway/bedrock/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Bedrock endpoints: {client.list_endpoints()}\n")
print(f"Bedrock completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions example
response_co... | 24 | 683 |
mlflow | examples/gateway/ai21_labs/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"AI21 Labs endpoints: {client.list_endpoints()}\n")
print(f"AI21 Labs completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
respons... | 23 | 659 |
mlflow | examples/gateway/mistral/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Mistral endpoints: {client.list_endpoints()}\n")
print(f"Mistral completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
response_co... | 35 | 1,037 |
mlflow | examples/gateway/huggingface/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Hugging Face TGI endpoints: {client.list_endpoints()}\n")
print(
f"Hugging Face completions endpoint info: {client.get_endpoint(endpoint='completions')}\n"
)
# Complet... | 26 | 645 |
mlflow | examples/gateway/openai/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"OpenAI endpoints: {client.list_endpoints()}\n")
print(f"OpenAI endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions example
response_completions = cl... | 48 | 1,414 |
mlflow | examples/gateway/anthropic/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Anthropic endpoints: {client.list_endpoints()}\n")
print(f"Anthropic completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
respons... | 24 | 696 |
mlflow | examples/gateway/togetherai/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Togetherai endpoints: {client.list_endpoints()}\n")
print(f"Togetherai completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
print(f"Togetherai chat endpoint... | 44 | 1,314 |
mlflow | examples/gateway/plugin/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://127.0.0.1:7000")
print(f"Plugin endpoints: {client.list_endpoints()}\n")
print(f"Plugin chat endpoint info: {client.get_endpoint(endpoint='chat')}\n")
# Chat request
response_chat = client.predict(
... | 27 | 634 |
mlflow | examples/gateway/plugin/my-llm/my_llm/config.py | .py | import os
from pydantic import field_validator
from mlflow.gateway.base_models import ConfigModel
class MyLLMConfig(ConfigModel):
my_llm_api_key: str
@field_validator("my_llm_api_key", mode="before")
def validate_my_llm_api_key(cls, value):
if value.startswith("$"):
# This resolves ... | 21 | 610 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.