Calling python script from C#

前端 未结 3 1092
一整个雨季
一整个雨季 2021-02-10 19:22

I have a C# code which helps to run python environment first and then it executes my python process. But the problem is it takes a lot of time to execute.

Actually i j

3条回答
  •  名媛妹妹
    2021-02-10 20:14

    I would suggest you to use REST API to call python code from C# application. To achieve that you need to use two libraries: CPickle and flask

    1. Expose line of code as a function and annotate
    2. Serialise your model after training and load when predicting

    Please refer to this code, I have created in python 3.5

    from sklearn import datasets
    from sklearn.ensemble import RandomForestClassifier
    import pickle
    from flask import Flask, abort, jsonify, request
    import numpy as np
    import json
    
    app = Flask(__name__)
    
    @app.route('/api/create', methods=['GET'])
    
    def create_model():
        iris = datasets.load_iris()
        x = iris.data
        y = iris.target
        model = RandomForestClassifier(n_estimators=100, n_jobs=2)
        model.fit(x, y)
        pickle.dump(model, open("iris_model.pkl", "wb"))
        return "done"
    
    
    def default(o):
        if isinstance(o, np.integer):
            return int(o)
        raise TypeError
    
    
    @app.route('/api/predict', methods=['POST'])
    def make_predict():
        my_rfm = pickle.load(open("iris_model.pkl", "rb"))
        data = request.get_json(force=True)
        predict_request = [data['sl'], data['sw'], data['pl'], data['pw']]
        predict_request = np.array(predict_request)
        output = my_rfm.predict(predict_request)[0]
        return json.dumps({'result': np.int32(output)}, default=default)
    
    
    if __name__ == '__main__':
        app.run(port=8000, debug=True)
    

    you can run it as:

提交回复
热议问题