在C中嵌入python中导入keras时出错

时间:2018-03-05 12:22:03

标签: c keras python-embedding

我试图在我的C应用程序中嵌入python。我在python官方网站上下载了这个软件包并设法做一个简单的Hello World。

现在我想更深入地使用一些python库,如numpy,keras,tensorflow ......

我正在使用Python 3.5.4,我使用pip3在我的电脑上安装了所有需要的软件包:

pip3 install keras
pip3 install tensorflow
...

然后我创建了我的脚本并在python环境中启动它,它工作正常:

的Python:

# Importing the libraries
#
import numpy as np
import pandas as pd

dataset2 = pd.read_csv('I:\RNA\dataset19.csv')
X_test = dataset2.iloc[:, 0:228].values
y_test = dataset2.iloc[:, 228].values

# 2.
import pickle
sc = pickle.load(open('I:\RNA\isVerb_sc', 'rb'))
X_test = sc.transform(X_test)

# 3. 
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout

classifier = Sequential()

classifier.add(Dense(units = 114, kernel_initializer = 'uniform', activation = 'relu', input_dim = 228))
classifier.add(Dropout(p = 0.3))

classifier.add(Dense(units = 114, kernel_initializer = 'uniform', activation = 'relu'))
classifier.add(Dropout(p = 0.3))

classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

classifier.load_weights('I:\RNA\isVerb_weights.h5')

y_pred = classifier.predict(X_test)
y_pred1 = (y_pred > 0.5)

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred1)

但是当我在嵌入python的C环境中执行相同的脚本时,它没有工作:

首先,我直接用 PyRun_SimpleFile 执行我的脚本,但没有运气,所以我用 PyRun_SimpleString 在多个指令中将其切片以检测问题:

C:

result = PyRun_SimpleString("import numpy as np"); // result = 0 (ok)
result = PyRun_SimpleString("import pandas as pd"); // result = 0 (ok)
...
result = PyRun_SimpleString("import pickle"); // result = 0 (ok)
... (all insctruction above works)
result = PyRun_SimpleString("import keras"); // result = -1 !!
... (all under this failed)

但是没有关于此错误的单个堆栈跟踪,我尝试this但我得到了:

"输出:(null)"

我在C中初始化Python似乎是正确的,因为其他库导入正常:

    // Python
    wchar_t *stdProgramName = L"I:\\LIBs\\cpython354";
    Py_SetProgramName(stdProgramName);

    wchar_t *stdPythonHome = L"I:\\LIBs\\cpython354";
    Py_SetPythonHome(stdPythonHome);

    wchar_t *stdlib = L"I:\\LIBs\\cpython354;I:\\LIBs\\cpython354\\Lib\\python35.zip;I:\\LIBs\\cpython354\\Lib;I:\\LIBs\\cpython354\\DLLs;I:\\LIBs\\cpython354\\Lib\\site-packages";
    Py_SetPath(stdlib);

    // Initialize Python 
    Py_Initialize();

当在Python cmd中时,导入keras 行需要一些时间(3秒)但是有效(警告但我没有发现任何伤害):

>>> import keras
I:\LIBs\cpython354\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
Using TensorFlow backend.
>>>

我现在很遗憾,我不知道在哪里可以看到,因为没有堆栈跟踪。

1 个答案:

答案 0 :(得分:0)

似乎在导入keras时,它会执行以下行:

sys.stderr.write('Using TensorFlow backend.\n')

或sys.stderr未在嵌入在Windows上的python中定义

一个简单的修正是定义sys.stderr,例如:

import sys
class CatchOutErr:
    def __init__(self):
        self.value = ''
    def write(self, txt):
       self.value += txt

catchOutErr = CatchOutErr()
sys.stderr = catchOutErr