Calling python script from C#

前端 未结 3 1095
一整个雨季
一整个雨季 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:08

    Why don't you actually use Python to run the code instead of embedding in C#? How are you going to deploy on another machine with Python dependencies?

    If you would like to build machine learning models there are many frameworks like http://accord-framework.net/ for classic machine learning algorithms

    Also try my project as well: deepakkumar1984/SiaNet (https://github.com/deepakkumar1984/SiaNet) Its a C# wrapper with CNTK backend. Trying to implement keras like wrapper. Hope it helps!

    0 讨论(0)
  • 2021-02-10 20:11

    You'll need to create a new process in order to call your program.

    look at this : C# equivalent to fork()/exec()

    0 讨论(0)
  • 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:

    0 讨论(0)
提交回复
热议问题