首页 > 解决方案 > 将一个观察结果传递给 sklearn 分类器的最有效方法

问题描述

所以经过一年的艰苦努力,我的模型终于在我公司的生产服务器上实现了。

在这个生产环境中,我的模型加载到 Python 脚本中,并从另一台服务器中提取了一个字符串。我现在必须解析这个字符串并将其传递给模型,以便它可以进行预测并将该输出返回给最终用户。

我目前关心的是效率。我正在寻找一种非常快速的方法来将字符串转换为可以传递给我的模型的类似数组的对象。

这是一个可复制的示例:

# Load modules
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier

# Load dummy data and target
X = load_breast_cancer()['data']
y = load_breast_cancer()['target']

# Initialize and fit classifier
clf = GradientBoostingClassifier(random_state=0)
clf.fit(X, y)

# [1] New string is received
string = '17.99|10.38|122.8|1001.0|0.1184|0.2776|0.3001|0.1471|0.2419|0.07871|1.095|0.9053|8.589|153.4|0.006399|0.04904|0.05373|0.01587|0.03003|0.006193|25.38|17.33|184.6|2019.0|0.1622|0.6656|0.7119|0.2654|0.4601|0.1189'

# [2] Convert string to array-like structure
import numpy as np
x = np.array(string.split('|')).astype(float)

# [3] Pass `x` to `clf` and predict probability
clf.predict_proba(x.reshape(-1, 30)).item(0)

> 0.9987537665581022

我的问题

有没有更有效的方法来解析字符串并将其传递给 sklearn 模型?

我认为跳过import numpy会加快速度。但是,我愿意接受任何可以改善 steps[1]和.[2][3]

标签: pythonnumpyparsingscikit-learn

解决方案


确保您确实需要双精度并使用

fromstring = np.fromstring
# ...
fromstring(string, 'f', -1, '|')

它会比它快3-4 倍

np.array(string.split('|')).astype(float)

推荐阅读