2017-06-01 209 views
4

我有一個C#代碼,它有助於先運行python環境,然後執行我的python進程。但問題是執行需要很長時間。從C調用python腳本#

其實我只想傳遞我的值並在python腳本中執行單行代碼。但是每次都需要執行所有的python代碼。有沒有辦法運行python進程外側,只是在我想要的時候運行單行。

我連接兩個C#代碼和Python過程與此

C#代碼

public String Insert(float[] values) 

     { 
      // full path of python interpreter 
      string python = @"C:\ProgramData\Anaconda2\python.exe"; 

      // python app to call 
      string myPythonApp = @"C:\classification.py"; 

      // dummy parameters to send Python script 
      //int x = 2; 
      //int y = 5; 

      // Create new process start info 
      ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python); 

      // make sure we can read the output from stdout 
      myProcessStartInfo.UseShellExecute = false; 
      myProcessStartInfo.RedirectStandardOutput = true; 
      myProcessStartInfo.CreateNoWindow = true; 
      myProcessStartInfo.WindowStyle = ProcessWindowStyle.Minimized; 

      // start python app with 3 arguments 
      // 1st arguments is pointer to itself, 2nd and 3rd are actual arguments we want to send 
      myProcessStartInfo.Arguments = myPythonApp + " " + values[0] + " " + values[1] + " " + values[2] + " " + values[3] + " " + values[4] + " " + values[5]; 

      Process myProcess = new Process(); 
      // assign start information to the process 
      myProcess.StartInfo = myProcessStartInfo; 


      myProcess.Start(); 

      // Read the standard output of the app we called. 
      // in order to avoid deadlock we will read output first and then wait for process terminate: 
      StreamReader myStreamReader = myProcess.StandardOutput; 
      string myString = myStreamReader.ReadLine(); 

      /*if you need to read multiple lines, you might use: 
       string myString = myStreamReader.ReadToEnd() */ 

      // wait exit signal from the app we called and then close it. 
      myProcess.WaitForExit(); 

      myProcess.Close(); 

      // write the output we got from python app 
      Console.WriteLine("Value received from script: " + myString); 
      Console.WriteLine("Value received from script: " + myString); 

和Python腳本

import numpy as np 
import sys 

val1 = float(sys.argv[1]) 
val2 = float(sys.argv[2]) 
val3 = float(sys.argv[3]) 
val4 = float(sys.argv[4]) 
val5 = float(sys.argv[5]) 
val6 = float(sys.argv[6]) 



# Load dataset 
url = "F:\FINAL YEAR PROJECT\Amila\data2.csv" 
names = ['JawLower', 'BrowLower', 'BrowRaiser', 'LipCornerDepressor', 'LipRaiser','LipStretcher','Emotion_Id'] 
dataset = pandas.read_csv(url, names=names) 

# shape 
# print(dataset.shape) 


# class distribution 
# print(dataset.groupby('Emotion_Id').size()) 


# Split-out validation dataset 
array = dataset.values 
X = array[:,0:6] 
Y = array[:,6] 
neigh = KNeighborsClassifier(n_neighbors=3) 


neigh.fit(X, Y) 

print(neigh.predict([[val1,val2,val3,val4,val5,val6]])) 

打印(neigh.predict([[VAL1,VAL2,VAL3 ,val4,val5,val6]]))這是我想分離執行的代碼行。

+1

http://python4.net – denfromufa

回答

2

我會建議你使用REST API調用從C#應用程序Python代碼。 爲了實現這一目標,您需要使用兩個庫:cPickle時和瓶

  1. 揭露的代碼行的功能和註釋
  2. 培訓和加載後連載模型預測

時,請參考這個代碼,我在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) 

可以爲運行它: enter image description here

+0

因爲我通過C#進程運行python腳本,它在結束時關閉。當我想運行'預測'需要從頭開始運行它。即使在這裏,如何保持python腳本活着,並每次調用預測?如果您可以請添加C#調用函數,將有助於理解 – Amal

1

爲什麼你不用Python來運行代碼而不是嵌入C#中?你將如何在具有Python依賴關係的另一臺機器上部署?

如果你想建立的機器學習模型有很多框架,如http://accord-framework.net/經典的機器學習算法

也可以嘗試我的項目還有:deepakkumar1984/SiaNet(https://github.com/deepakkumar1984/SiaNet)它是一個C#包裝與CNTK後端。試圖實現像包裝一樣的keras。希望能幫助到你!