- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在编写一个使用 C++ 作为数据管理后端的程序,可以调用用户创建的 Python 脚本来执行各种任务。尽管与在 python 脚本中导入模块有关,但我遇到了一个问题。我将值从 C++ 传递到 python,并从 sklearn 对这些值执行高斯过程回归,然后简单地将优化模型值或 GPR 不确定性返回到 C++。我将这两种情况(模型优化和模型验证)作为 python 脚本中的两个独立函数,因为它们将从 C++ 的不同位置调用。
当我运行第一个函数(模型优化)时,一切正常,并且我获得了优化的超参数以顺利返回 C++。但是在第二次函数调用期间,脚本失败,因为它无法从 sklearn 导入 GPR 模块(与前一个函数成功导入的模块相同)。我不太熟悉将 python 嵌入到 C++ 中,所以很可能我只是遗漏了一些东西,或者没有完全理解规则。无法从 C++ 端提供可自行运行的代码,因此我将尽我所能提供尽可能多的嵌入代码。下面的 python 脚本完整显示。如果您需要更多信息,请告诉我,我很乐意提供。感谢您提供的任何帮助。
C++:主要
//other stuff
Py_Initialize();
//do more other stuff (embedding happens here)
Py_Finalize();
//do even more other stuff
C++:模型优化
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
pName = PyString_FromString(file.c_str());
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, function.c_str());
pArgs = PyTuple_New(size);
PyTuple_SetItem(pArgs, 0, PyLong_FromLong(gp->getInnerFPSize()));
PyTuple_SetItem(pArgs, 1, PyLong_FromLong(ntrain));
k = 2;
for(i = 0; i < trainingFP[modelNumber].size(); i++){
for(j = 0; j < trainingFP[modelNumber][i].size(); j++){
PyTuple_SetItem(pArgs, k,
PyFloat_FromDouble(trainingFP[modelNumber][i][j]));
k++;
}
}
for(i = 0; i < trainingForces[modelNumber].size(); i++){
PyTuple_SetItem(pArgs, k,
PyFloat_FromDouble(trainingForces[modelNumber][i]));
k++;
}
Py_INCREF(pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
}else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", function.c_str());
return 1;
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
optimalSigma = PyFloat_AsDouble(PyList_GetItem(pValue, 1));
optimalSigmaN = PyFloat_AsDouble(PyList_GetItem(pValue, 0));
optimalSigmaF = PyFloat_AsDouble(PyList_GetItem(pValue, 2));
Py_DECREF(pValue);
C++:模型验证
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
pName = PyString_FromString(file.c_str());
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, function.c_str());
pArgs = PyTuple_New(size);
PyTuple_SetItem(pArgs, 0, PyFloat_FromDouble(testFP[0].size()));
PyTuple_SetItem(pArgs, 1, PyFloat_FromDouble(testFP.size()));
PyTuple_SetItem(pArgs, 2, PyFloat_FromDouble(trainingFP.size()));
PyTuple_SetItem(pArgs, 3, PyFloat_FromDouble(sigma));
PyTuple_SetItem(pArgs, 4, PyFloat_FromDouble(sigmaN));
PyTuple_SetItem(pArgs, 5, PyFloat_FromDouble(sigmaF));
k = 6;
for(i = 0; i < testFP.size(); i++){
for(j = 0; j < testFP[i].size(); j++){
PyTuple_SetItem(pArgs, k, PyFloat_FromDouble(testFP[i][j]));
k++;
}
}
for(i = 0; i < trainingFP.size(); i++){
for(j = 0; j < trainingFP[i].size(); j++){
PyTuple_SetItem(pArgs, k, PyFloat_FromDouble(trainingFP[i][j]));
k++;
}
}
for(i = 0; i < trainingFP.size(); i++){
PyTuple_SetItem(pArgs, k, PyFloat_FromDouble(trainingForces[i]));
k++;
}
Py_INCREF(pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
}else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", function.c_str());
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
for(i = 0; i < testFP.size(); i++)
prediction[i] = PyFloat_AsDouble(PyList_GetItem(pValue, i));
Py_DECREF(pValue);
python
def GPR(*X):
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel
import re
#initialize local variables
counter = 0
sigma_l_initial = 1
sigma_n_initial = 1
sigma_f_initial = 2
innerFPSize = int(X[0])
ntrain = int(X[1])
optimized_hyperparameters = []
forces = []
fp = []
sigma_l_bounds = [.01,100]
sigma_n_bounds = [.001,.1]
fp.append([])
#pass values from c++ conversion tuple to local lists
for x in X:
if counter > 1 and counter < 2 + innerFPSize * ntrain:
fp[len(fp) - 1].append(x)
elif counter >= 2 + innerFPSize * ntrain:
forces.append(x)
counter += 1
if len(fp[len(fp) -1]) == innerFPSize:
if len(fp) < ntrain:
fp.append([])
#GPR routine
krbf = sigma_f_initial*RBF(length_scale=sigma_l_initial,length_scale_bounds=(sigma_l_bounds[0],sigma_l_bounds[1]))
noise_kernel = WhiteKernel(noise_level=sigma_n_initial,noise_level_bounds=(sigma_n_bounds[0],sigma_n_bounds[1]))
gp = GaussianProcessRegressor(kernel=krbf + noise_kernel,normalize_y=True,n_restarts_optimizer=25)
gp.fit(fp, forces)
#get optimized hyperparameters
rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", str(gp.kernel_))
optimized_hyperparameters.append(float(rr[-1]))
optimized_hyperparameters.append(float(rr[-2]))
optimized_hyperparameters.append(float(rr[0]))
return optimized_hyperparameters
def GPR_unc(*X):
try:
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel
except:
print 'THIS REFUSES TO WORK'
#initialize variables
uncertainty = []
testFP = []
trainingFP = []
trainingForces = []
innerFPSize = int(X[0])
testSize = int(X[1])
ntrain = int(X[2])
sigma = float(X[3])
sigma_n = float(X[4])
sigma_f = float(X[5])
counter = 0
setTrainFP = setTrainForces = False
setTestFP = True
testFP.append([])
trainingFP.append([])
#parse data from C++ arrays
for x in X:
try:
if counter > 5 and setTestFP == True:
testFP[len(testFP) - 1].append(x)
elif setTrainFP == True:
trainingFP[len(trainingFP) - 1].append(x)
elif setTrainForces == True:
trainingForces.append(x)
if counter > 5 and setTestFP == True:
if len(testFP[len(testFP) -1]) == innerFPSize:
if len(testFP) + 1 <= testSize:
testFP.append([])
else:
setTestFP = False
setTrainFP = True
elif setTrainFP == True:
if len(trainingFP[len(trainingFP) -1]) == innerFPSize:
if(len(trainingFP)) + 1 <= ntrain:
trainingFP.append([])
else:
setTrainFP = False
setTrainForces = True
counter += 1
except:
print 'ERROR'
#perform static "optimization" of gpr kernel to get gpr object
krbf = sigma_f**2*RBF(length_scale=sigma,length_scale_bounds=(sigma,sigma))
noise_kernel = WhiteKernel(noise_level=sigma_n,noise_level_bounds=(sigma_n,sigma_n))
gp = GaussianProcessRegressor(kernel=krbf + noise_kernel,normalize_y=True, optimizer=None)
gp.fit(trainingFP, trainingForces)
#get uncertanties on test set
val,std=gp.predict(testFP,return_std=True)
#ensure that the uncertainty is loaded into a float list in order to be sent back to c++
for x in std:
uncertainty.append(float(x))
for x in std:
uncertainty.append(float(x) * float(x))
return uncertainty
尝试从 GPR_unc 函数(python 代码中的第二个函数)导入模块时,python 脚本失败。
最佳答案
在模型验证功能期间,python 元组:
pArgs = PyTuple_New(size);
与附加到它的内容相比,传递给它的大小不正确。崩溃最终变成了一个简单的“在不调整数组大小的情况下写入数组末尾”。
关于python - 在 C++ 中嵌入 Python : Importing modules in python script works during one function call but not another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46934487/
我正在开发一个小型 Web 应用程序,其中有一个 object 元素(包含一个 embed),用于显示小型文档。 文档可以是 PDF 或纯文本文件 (.txt),我以 base64 字符串的形式从 W
我有一种小型语言,它基本上是 OCaml 的扩展(实际上它是 OCaml 子集的扩展,但这并不重要)。为了简化事情,我有一个“转义”表达式,可以将 OCaml 文字传输到我的语言中(因此您可以将任意
据我所知,我知道 embed tag用于嵌入来自 youtube 等网站的视频,object tag用于 Flash 视频和 video tags下HTML5 .但我很好奇这些标签的深入细节以及作为开
我假设您可以将 WebKit 嵌入到另一个桌面应用程序中并向其发送一个字符串,例如: Hello world! 它将显示在窗口内。 我的问题是,如果我将其压缩表示(JPEG 转储)加载到内存中,我该如
有没有一种可能的方式,我可以从youtube检索我的最新视频的列表(带有缩略图),使用cron作业将嵌入的代码存储在数据库中,这样我就可以在单独的页面上显示视频,而不是将用户引向youtube观看视频
最近我发现我的网站上嵌入的 YouTube 视频存在问题 - 全屏按钮不再起作用。确实有过一次。该按钮是可见的,但单击时没有任何反应。 我正在使用 Youtube Javascript API 将视频
在 Keras 内置函数中嵌入使用哪种算法?Word2vec?手套?其他? https://keras.io/layers/embeddings/ 最佳答案 简短的回答是都不是。本质上,GloVe 的
在 LSTM 上用于建模 IMDB 序列数据 ( https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py ) 的 ker
在机器学习中,通常用 one-hot-encoding 表示分类(特别是:名义)特征。 .我正在尝试学习如何使用 tensorflow 的嵌入层来表示分类问题中的分类特征。我有 tensorflow
我有一个使用 Storyboard的应用程序,我想在我的主视图中有一个 View ,并让它在场景中的不同 View 之间切换。 所以目前我有“容器对象”,我可以在其中嵌入另一个 viewControl
在我的项目中我遇到了这样的情况。 function fonsubmit() { alert('Out side PHP'); //Here the php code starts
我正在尝试添加一个JFileChooser,它选择父目录并允许用户输入文件名称。我知道 showSaveDialog 和 showOpenDialog 方法,但我不想创建新窗口。 这是我到目前为止所拥
我注意到我的网站创建了这样的链接:www.domain.com/post-name/embed/ 恐怕这可能会影响 SEO。是否可以禁用此功能? 最佳答案 显然这是默认的 WordPress 行为。此
我试图从 C 代码调用 python 函数,我遵循了 here 中的示例 我也有正确的包含文件目录、库目录和链接 python32.lib(我使用 python 32)但是错误是 python/C A
我正在使用基于云的 EDR 平台来监控客户端受损网络上发生的进程。我最近经常看到的是使用选项“-Embedding”调用的 msiexec.exe C:\Windows\System32\MsiExe
我有一个列表,其中包含数百万个需要嵌入的句子。我正在使用 Flair以此目的。这个问题似乎应该是并行的。但是,当我尝试优化时,我的性能要么没有提高,要么只是停滞不前。 我将我的句子定义为一个简单的字符
我想在我的应用程序中添加嵌入的 YouTube 视频:我该怎么做?我有这个 import 'package:youtube_player/youtube_player.dart'; import 'p
我有 json 看起来像: myjson = {"queries":{"F.SP": 27}} 所以与 queryResults = JObject.Parse(jsonString) 我可以 fir
我在 html 文档中嵌入 highcharts 饼图时遇到问题。具体来说,我无法在不更改图表大小的情况下调整图表容器的大小。有谁知道您是否可以在不缩小图表的情况下减少默认填充?或者,您可以在不增加容
我不太确定这在 MediaWiki 中是否可行。 我有几个类别,每个类别包含几页。如果您打开一个类别页面,您将看到该类别的内容,通常由以下三个部分组成: 用户定义的文本(可以使用编辑链接进行编辑)。
我是一名优秀的程序员,十分优秀!