在 C 中的嵌入式 python 中导入 keras 时出错
Error when Importing keras in embedded python in C
我正在尝试将 python 嵌入到我的 C 应用程序中。我在 python 官方网站下载了这个包,并设法做了一个简单的 Hello World。
现在我想更深入地使用 python 的一些库,例如 numpy、keras、tensorflow...
我正在使用 Python 3.5.4,我使用 pip3 在我的 PC 上安装了所有需要的包:
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)
但是当我在 C 环境中使用嵌入 python 执行相同的脚本时,它不起作用:
起初,我直接用 PyRun_SimpleFile 执行我的脚本,但运气不好,所以我用 [=55= 将它分成多条指令]检测问题:
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 但我刚得到:
"Here's the output: (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 中时,import 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.
>>>
我现在很茫然,我不知道去哪里看,因为没有堆栈跟踪。
当你导入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
我正在尝试将 python 嵌入到我的 C 应用程序中。我在 python 官方网站下载了这个包,并设法做了一个简单的 Hello World。
现在我想更深入地使用 python 的一些库,例如 numpy、keras、tensorflow...
我正在使用 Python 3.5.4,我使用 pip3 在我的 PC 上安装了所有需要的包:
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)
但是当我在 C 环境中使用嵌入 python 执行相同的脚本时,它不起作用:
起初,我直接用 PyRun_SimpleFile 执行我的脚本,但运气不好,所以我用 [=55= 将它分成多条指令]检测问题:
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 但我刚得到:
"Here's the output: (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 中时,import 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.
>>>
我现在很茫然,我不知道去哪里看,因为没有堆栈跟踪。
当你导入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