java - 从 java 运行 python sklearn 分类器

标签 java python scikit-learn

我使用 Sklearn 和其他库在 python 中训练了一个 SVC 分类器。我通过构建管道(sklearn)做到了 我能够将经过训练的模型转储到 pickle 文件中,并制作另一个 python 脚本,该脚本将加载 pickle 文件并从命令行获取输入来进行预测。我可以从 java 调用这个 python 脚本并且它工作正常。 唯一的问题是它需要花费很多时间,因为我在 python 脚本中调用了 nltk、numpy、panda 库,需要对输入参数进行预处理。我多次调用这个 python 脚本,这增加了时间。 我该如何解决这个问题。

这就是我的管道的样子

pipeline = Pipeline([

# Use FeatureUnion to combine the features from dataset
('union', FeatureUnion(
    transformer_list=[

        # Pipeline for getting POS 
       ('ngrams', Pipeline([
            ('selector', ItemSelector(key='Sentence')),
            ('vect', CountVectorizer(analyzer='word')),
            ('tfidf', TfidfTransformer()),
        ])),


    ],

    # weight components in FeatureUnion
    transformer_weights={
        'ngrams': 0.7,
    },
)),

# Use a SVC classifier on the combined features
('clf', LinearSVC()),
])

最佳答案

以下是为 scikit 模型设置简单的 FLASK 服务 REST API 的示例。

import sys
import os
import time
import traceback

from flask import Flask, request, jsonify
from sklearn.externals import joblib

app = Flask(__name__)


model_directory = 'model'
model_file_name = '%s/model.pkl' % model_directory

# These will be populated at training time
clf = None


@app.route('/predict', methods=['POST'])
def predict():
    if clf:
        try:
            json_ = request.json
            # query = get the payload from the json and feed it to your model 
            prediction = list(clf.predict(query))

            return jsonify({'prediction': prediction})

        except Exception, e:

            return jsonify({'error': str(e), 'trace': traceback.format_exc()})
    else:
        return 'no model here'



if __name__ == '__main__':
    try:
        port = int(sys.argv[1])
    except Exception, e:
        port = 80

    try:
        clf = joblib.load(model_file_name)
        print 'model loaded'

    app.run(host='0.0.0.0', port=port, debug=True)

关于java - 从 java 运行 python sklearn 分类器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50454871/

相关文章:

Python、iOS - 我可以用 python 编写应用程序的模型吗

python - MLPRegressor 工作但结果没有任何意义

python - Sklearn.KMeans : how to avoid Memory or Value Error?

java - 由于使用两个消息驱动器Bean更新同一表而导致的超时导致事务结束

java - 如何在Spring中使用Tomcat 7提供的JNDI DataSource?

java - 使用 Java 匹配具有指定属性的对象

python - 字典在 pd.DataFrame 的循环中

java - 如何通过 BOT 的 Ajax 调用进行保护?

python - 是什么使得可选参数是可选的而位置参数是必需的?

python - GridSearch 'UndefinedMetricWarning' 和错误结果