- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在构建一个多标签分类器来根据文本字段预测标签。例如,根据电影标题预测类型。我想使用 MultiLabelBinarizer()
对包含所有适用流派标签的列进行二值化。例如,['action','comedy','drama']
被分成具有 0/1 值的三列。
我使用 MultiLabelBinarizer()
的原因是我可以使用内置的 inverse_transform()
函数来转换输出数组(例如 array([0, 0, 1, 0, 1])
直接转换为用户友好的文本输出 (['action','drama']
)。
分类器可以工作,但我在预测新数据时遇到问题。我找不到将 MultiLabelBinarizer()
集成到我的管道中的方法,以便可以保存并重新加载它以推断新数据。一种解决方案是将其单独保存为 pickle 对象并每次加载回来,但我想避免在生产中出现这种依赖关系。
我知道这与我在管道中内置的 tf-idf 向量类似,但不同之处在于它应用于目标列(流派标签)而不是我的自变量(文本注释)。这是我训练多标签 SVM 的代码:
def svm_train(df):
mlb = MultiLabelBinarizer()
y = mlb.fit_transform(df['Genres'])
with mlflow.start_run():
x_train, x_test, y_train, y_test = train_test_split(df['Movie Title'], y, test_size=0.3)
# Instantiate TF-IDF Vectorizer and SVM Model
tfidf_vect = TfidfVectorizer()
mdl = OneVsRestClassifier(LinearSVC(loss='hinge'))
svm_pipeline = Pipeline([('tfidf', tfidf_vect), ('clf', mdl)])
svm_pipeline.fit(x_train, y_train)
prediction = svm_pipeline.predict(x_test)
report = classification_report(y_test, prediction, target_names=mlb.classes_)
mlflow.sklearn.log_model(svm_pipeline, "Multilabel Classifier")
mlflow.log_artifact(mlb, "MLB")
return(report)
svm_train(df)
推理包括在单独的 Databricks 笔记本中从 MLflow 重新加载保存的模型(与加载回 pickle 文件相同)并使用管道进行预测:
def predict_labels(new_data):
model_uri = '...MLflow path...'
model = mlflow.sklearn.load_model(model_uri)
predictions = model.predict(new_data)
# If I can't package the MultiLabelBinarizer() into the Pipeline, this
# is where I'd have to load the pickle object mlb
# so that I can inverse_transform()
return mlb.inverse_transform(predictions)
new_data = ['Some movie title']
predict_labels(new_data)
['action','comedy']
这是我正在使用的所有库:
import pandas as pd
import numpy as np
import mlflow
import mlflow.sklearn
import glob, os
from pyspark.sql import DataFrame
from sklearn.pipeline import Pipeline
from sklearn import preprocessing
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.multiclass import OneVsRestClassifier
from sklearn import svm
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score, precision_score, recall_score
最佳答案
对于您的用例,您可能需要考虑使用 MLflow's functionality for persisting custom models 。根据the docs :
While MLflow’s built-in model persistence utilities are convenient for packaging models from various popular ML libraries in MLflow Model format, they do not cover every use case. For example, you may want to use a model from an ML library that is not explicitly supported by MLflow’s built-in flavors. Alternatively, you may want to package custom inference code and data to create an MLflow Model. Fortunately, MLflow provides two solutions that can be used to accomplish these tasks: Custom Python Models and Custom Flavors.
特别是,您应该能够以类似于链接示例中的 XGBoost 模型的方式将 MultiLabelIndexer 作为工件与 Sklearn 模型一起记录,然后在预测时将其加载回来,如下所示:
# Save sklearn model & multilabel indexer to paths on the local filesystem
sklearn_model_path = "some/local/path"
labelindexer_path = "another/local/path"
# ... save your models objects here to sklearn_model_path and labelindexer_path
# Define the custom model class
import mlflow.pyfunc
class SklearnWrapper(mlflow.pyfunc.PythonModel):
def load_context(self, context):
import pickle, mlflow
with open(context["indexer_path"], 'rb') as handle:
self.indexer = pickle.load(handle)
self.pipeline = mlflow.sklearn.load_model("pipeline_path")
def predict(self, context, model_input):
pipeline_preds = self.pipeline.predict(model_input)
return self.indexer.inverse_transform(pipeline_preds)
# Create a Conda environment for the new MLflow Model that contains the XGBoost library
# as a dependency, as well as the required CloudPickle library
import cloudpickle
import sklearn
conda_env = {
'channels': ['defaults'],
'dependencies': [
'sklearn={}'.format(sklearn.__version__),
'cloudpickle={}'.format(cloudpickle.__version__),
],
'name': 'sklearn_env'
}
# Save the MLflow Model
artifacts = {
"pipeline_path": sklearn_model_path,
"indexer_path": labelindexer_path,
}
mlflow_pyfunc_model_path = "sklearn_mlflow_pyfunc"
mlflow.pyfunc.save_model(
path=mlflow_pyfunc_model_path, python_model=XGBWrapper(), artifacts=artifacts,
conda_env=conda_env)
# Load the model in `python_function` format
loaded_model = mlflow.pyfunc.load_model(mlflow_pyfunc_model_path)
# Predict on a pandas DataFrame
import pandas as pd
loaded_model.predict(pd.DataFrame(...))
请注意,我们的自定义模型仍会加载回 MultiLabelIndexer,但 MLflow 会将索引器与您的管道和自定义模型逻辑一起保留,以便您可以将模型视为用于生产部署的单个连贯单元。
关于python - 将 MultiLabelBinarizer 打包到 scikit-learn Pipeline 中以推理新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57924929/
基本上,我的问题是,由于无监督学习是机器学习的一种,是否需要机器“学习”的某些方面并根据其发现进行改进?例如,如果开发了一种算法来获取未标记的图像并找到它们之间的关联,那么它是否需要根据这些关联来改进
生成模型和判别模型似乎可以学习条件 P(x|y) 和联合 P(x,y) 概率分布。但从根本上讲,我无法说服自己“学习概率分布”意味着什么。 最佳答案 这意味着您的模型要么充当训练样本的分布估计器,要么
是否有类似于 的 scikit-learn 方法/类元成本 在 Weka 或其他实用程序中实现的算法以执行常量敏感分析? 最佳答案 不,没有。部分分类器提供 class_weight和 sample_
是否Scikit-learn支持迁移学习?请检查以下代码。 型号 clf由 fit(X,y) 获取 jar 头型号clf2在clf的基础上学习和转移学习 fit(X2,y2) ? >>> from s
我发现使用相同数据的两种交叉验证技术之间的分类性能存在差异。我想知道是否有人可以阐明这一点。 方法一:cross_validation.train_test_split 方法 2:分层折叠。 具有相同
我正在查看 scikit-learn 文档中的这个示例:http://scikit-learn.org/0.18/auto_examples/model_selection/plot_nested_c
我想训练一个具有很多标称属性的数据集。我从一些帖子中注意到,要转换标称属性必须将它们转换为重复的二进制特征。另外据我所知,这样做在概念上会使数据集稀疏。我也知道 scikit-learn 使用稀疏矩阵
我正在尝试在 scikit-learn (sklearn.feature_selection.SelectKBest) 中通过卡方方法进行特征选择。当我尝试将其应用于多标签问题时,我收到此警告: 用户
有几种算法可以构建决策树,例如 CART(分类和回归树)、ID3(迭代二分法 3)等 scikit-learn 默认使用哪种决策树算法? 当我查看一些决策树 python 脚本时,它神奇地生成了带有
我正在尝试在 scikit-learn (sklearn.feature_selection.SelectKBest) 中通过卡方方法进行特征选择。当我尝试将其应用于多标签问题时,我收到此警告: 用户
有几种算法可以构建决策树,例如 CART(分类和回归树)、ID3(迭代二分法 3)等 scikit-learn 默认使用哪种决策树算法? 当我查看一些决策树 python 脚本时,它神奇地生成了带有
有没有办法让 scikit-learn 中的 fit 方法有一个进度条? 是否可以包含自定义的类似 Pyprind 的内容? ? 最佳答案 如果您使用 verbose=1 初始化模型调用前 fit你应
我正在使用基于 rlglue 的 python-rl q 学习框架。 我的理解是,随着情节的发展,算法会收敛到一个最优策略(这是一个映射,说明在什么状态下采取什么行动)。 问题 1:这是否意味着经过若
我正在尝试使用 grisSearchCV 在 scikit-learn 中拟合一些模型,并且我想使用“一个标准错误”规则来选择最佳模型,即从分数在 1 以内的模型子集中选择最简约的模型最好成绩的标准误
我正在尝试离散数据以进行分类。它们的值是字符串,我将它们转换为数字 0,1,2,3。 这就是数据的样子(pandas 数据框)。我已将数据帧拆分为 dataLabel 和 dataFeatures L
每当我开始拥有更多的类(1000 或更多)时,MultinominalNB 就会变得非常慢并且需要 GB 的 RAM。对于所有支持 .partial_fit()(SGDClassifier、Perce
我需要使用感知器算法来研究一些非线性可分数据集的学习率和渐近误差。 为了做到这一点,我需要了解构造函数的一些参数。我花了很多时间在谷歌上搜索它们,但我仍然不太明白它们的作用或如何使用它们。 给我带来更
我知道作为功能 ordinal data could be assigned arbitrary numbers and OneHotEncoding could be done for catego
这是一个示例,其中有逐步的过程使系统学习并对输入数据进行分类。 它对给定的 5 个数据集域进行了正确分类。此外,它还对停用词进行分类。 例如 输入:docs_new = ['上帝就是爱', '什么在哪
我有一个 scikit-learn 模型,它简化了一点,如下所示: clf1 = RandomForestClassifier() clf1.fit(data_training, non_binary
我是一名优秀的程序员,十分优秀!