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
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
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: