python - 将一个观察结果传递给 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]
解决方案
确保您确实需要双精度并使用
fromstring = np.fromstring
# ...
fromstring(string, 'f', -1, '|')
它会比它快3-4 倍
np.array(string.split('|')).astype(float)
推荐阅读
- oracle - 已删除记录的副本 - 触发器或其他方式
- javascript - JS && HTML5 如何在不同宽度和高度的画布中动态打开图片
- powershell - 使用 Get-ADUser 过滤掉包含单词或字符的用户
- oracle - 如何在多列上的 oracle 行之间查找重复项?
- java - 无法通过 Java 检索存储过程返回值
- spring-boot - spring-boot-starter-freemarker 动态循环示例
- javascript - 在后台打开新标签,将注意力集中在当前标签上 - Chrome
- neo4j - 由于 PicklingError,Pyspark 操作未执行
- javascript - 根据我输入的 id 显示自动完成选择
- node.js - sinon mocking GET, POST, PUT and DELETE methods assertions fail everytime. no idea why