Google Cloud ML-engine scikit-learn 预测概率“predict_proba()”

Posted

技术标签:

【中文标题】Google Cloud ML-engine scikit-learn 预测概率“predict_proba()”【英文标题】:Google Cloud ML-engine scikit-learn prediction probability 'predict_proba()' 【发布时间】:2019-02-08 14:48:23 【问题描述】:

Google Cloud ML-engine 支持部署 scikit-learn Pipeline 对象的能力。例如,文本分类Pipeline 可能如下所示,

classifier = Pipeline([
('vect', CountVectorizer()), 
('clf', naive_bayes.MultinomialNB())])

可以训练分类器,

classifier.fit(train_x, train_y)

然后分类器可以上传到谷歌云存储,

model = 'model.joblib'
joblib.dump(classifier, model)
model_remote_path = os.path.join('gs://', bucket_name, datetime.datetime.now().strftime('model_%Y%m%d_%H%M%S'), model)
subprocess.check_call(['gsutil', 'cp', model, model_remote_path], stderr=sys.stdout)

然后可以通过Google Cloud Console 或programmatically 创建ModelVersion,将'model.joblib' 文件链接到Version

然后可以通过调用已部署的模型predict 端点来使用此分类器来预测新数据,

ml = discovery.build('ml','v1')
project_id = 'projects//models/'.format(project_name, model_name)
if version_name is not None:
    project_id += '/versions/'.format(version_name)
request_dict = 'instances':['Test data']
ml_request = ml.projects().predict(name=project_id, body=request_dict).execute()

Google Cloud ML 引擎调用分类器的predict 函数并返回预测的类。但是,我希望能够返回置信度分数。通常这可以通过调用分类器的predict_proba 函数来实现,但是似乎没有更改被调用函数的选项。我的问题是:使用 Google Cloud ML 引擎时是否可以返回 scikit-learn 分类器的置信度分数?如果没有,您对如何实现这一结果有什么建议吗?

更新: 我找到了一个 hacky 解决方案。它涉及用自己的predict_proba函数覆盖分类器的predict函数,

nb = naive_bayes.MultinomialNB()
nb.predict = nb.predict_proba
classifier = Pipeline([
('vect', CountVectorizer()), 
('clf', nb)])

令人惊讶的是,这有效。如果有人知道更简洁的解决方案,请告诉我。

更新:Google 发布了一项名为 Custom prediction routines 的新功能(目前处于测试阶段)。这允许您定义当预测请求进来时运行什么代码。它为解决方案添加了更多代码,但它肯定不那么hacky。

【问题讨论】:

【参考方案1】:

您使用的 ML Engine API 只有 predict 方法,正如您在 documentation 中看到的那样,因此它只会进行预测(除非您使用您提到的 hack 强制它执行其他操作)。

如果您想对经过训练的模型执行其他操作,则必须加载并正常使用它。如果您想使用存储在 Cloud Storage 中的模型,您可以执行以下操作:

from google.cloud import storage
from sklearn.externals import joblib

bucket_name = "<BUCKET_NAME>"
gs_model = "path/to/model.joblib"  # path in your Cloud Storage bucket
local_model = "/path/to/model.joblib"  # path in your local machine

client = storage.Client()
bucket = client.get_bucket(bucket_name)
blob = bucket.blob(gs_model)
blob.download_to_filename(local_model)

model = joblib.load(local_model)
model.predict_proba(test_data)

【讨论】:

感谢您的回复。我已经根据 Google 此后发布的一项新功能,使用更简洁的解决方案更新了原始帖子。

以上是关于Google Cloud ML-engine scikit-learn 预测概率“predict_proba()”的主要内容,如果未能解决你的问题,请参考以下文章

google.cloud.pubsub_v1 和 google.cloud.pubsub 有啥区别?

google cloud sdk 怎么安装

Google Cloud Function - ImportError:无法从“google.cloud”(未知位置)导入名称“pubsub”

setQueryParameters 不是“com.google.cloud”的一部分,名称:“google-cloud-bigquery”,版本:“0.4.0”

Spring + google cloud:没有可用的“com.google.cloud.storage.Storage”类型的合格bean

Google Cloud Dataflow 和 Google Cloud Dataproc 有啥区别?