MLflow 入门
Weston Bassler
Senior MLOps Engineer
NLP:分词器
分类:标签编码器
预/后处理
非内置风格

内置风格:python_function
mlflow.pyfunc
save_model()log_model()load_model()自定义模型类
MyClass(mlflow.pyfunc.PythonModel)PythonModel 类
load_context():在调用 mlflow.pyfunc.load_model() 时加载工件predict():接收输入并执行自定义评估# 类 class MyPythonClass:# 打印 Hello! 的函数 def my_func(): print("Hello!")
# 创建新对象 x = MyPythonClass()# 执行 my_func 函数 x.my_func()
"Hello!"
import mlflow.pyfunc # 定义模型类 class CustomPredict(mlflow.pyfunc.PythonModel):# 加载工件 def load_context(self, context): self.model = mlflow.sklearn.load_model(context.artifacts["custom_model"])# 使用 custom_function() 评估输入 def predict(self, context, model_input): prediction = self.model.predict(model_input) return custom_function(prediction)
# 保存到本地文件系统
mlflow.pyfunc.save_model(path="custom_model", python_model=CustomPredict())
# 记录到 MLflow Tracking
mlflow.pyfunc.log_model(artifact_path="custom_model", python_model=CustomPredict())
# 从本地文件系统加载
mlflow.pyfunc.load_model("local")
# 从 MLflow Tracking 加载
mlflow.pyfunc.load_model("runs:/run_id/tracking_path")
mlflow.evaluate():基于数据集评估性能
回归与分类模型
# 训练数据 X_train, X_test, y_train, y_test = \ train_test_split(X, y, train_size=0.7,random_state=0)# 线性回归模型 lr = LinearRegression() lr.fit(X_train, y_train)
# 数据集 eval_data = X_test eval_data["test_label"] = y_test# 使用数据集评估模型 mlflow.evaluate( "runs:/run_id/model", eval_data, targets="test_label", model_type="regressor" )


MLflow 入门