【发布时间】:2019-01-16 15:08:42
【问题描述】:
我希望能够使用来自 C++ 的 numpy、scipy 等 python 模块。以下代码尝试调用 scipy.optimize.curve_fit 来拟合抛物线函数。调用 curve_fit 时出现问题。这里抛出异常。
#include <iostream>
#include <pybind11/embed.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h> // mandatory for myPyObject.cast<std::vector<T>>()
#include <pybind11/functional.h> // mandatory for py::cast( std::function )
namespace py = pybind11;
int main()
{
try {
py::scoped_interpreter guard{};
py::module np = py::module::import("numpy");
py::object random = np.attr("random");
py::module scipy = py::module::import("scipy.optimize");
// create some data for fitting
std::vector<double> xValues(11, 0);
std::vector<double> yValues(11, 0);
for (int i = -5; i < 6; ++i) {
xValues[i + 5] = i;
yValues[i + 5] = i*i;
}
// cast it to numpy arrays
py::array_t<double> pyXValues = py::cast(xValues);
py::array_t<double> pyYValues = py::cast(yValues);
// add some noise to the yValues using numpy -> Works!
py::array_t<double> pyYValuesNoise = np.attr("add")(pyYValues, random.attr("randn")(11));
// create a function f_a(x) = a*x^2
std::function<std::vector<double>(std::vector<double>, double)> squared = [](std::vector<double> x, double a) {
std::vector<double> retvals(x);
std::transform(x.begin(), x.end(), retvals.begin(), [a](double val) { return a*val*val; });
return retvals;
};
// cast it to a python function
py::function pySquared = py::cast(squared);
// get scipy.optimize.curve_fit
py::function curve_fit = scipy.attr("curve_fit");
// call curve_fit -> throws exception
/* py::object = */ curve_fit(pySquared, pyXValues, pyYValues);
}
catch (std::exception error) {
std::cout << error.what() << std::endl;
}
system("pause");
return 0;
}
异常给出信息:
ValueError: no signature found for builtin
在:
D:\Programs\python36_6_x64\Lib\inspect.py(2090): _signature_from_builtin D:\Programs\python36_6_x64\Lib\inspect.py(2266): _signature_from_callable D:\Programs\python36_6_x64\Lib\inspect.py(2802): from_callable D:\Programs\python36_6_x64\Lib\inspect.py(3052):签名 D:\Programs\python36_6_x64\lib\site-packages\scipy_lib_util.py(290): getargspec_no_self
D:\Programs\python36_6_x64\lib\site-packages\scipy\optimize\minpack.py(685):curve_fit
如何正确地从 C++ 调用 curve_fit?
【问题讨论】:
-
很遗憾,我无法帮助您。但我确实认为您可以通过删除
stdafx.h库并删除try-except构造来使您的问题更加清晰。 -
删除了stdafx.h,但是删除
try-except的原因是什么? -
当然没有有力的论据,但它并没有让你的问题更清楚(也不是很清楚)所以我总是在这个平台上省略它
-
我明白为什么这不起作用,
curve_fit是一个高阶函数,它会自动初始化与目标函数的尾随参数签名匹配的变量。如果你真的想要这个,你可以执行几行 python,其中目标函数是一个 python 函数,可能调用一个 c++ 函数。 -
@JensMunk 所以不能直接通过pybind调用以函数为参数的函数吗?
标签: c++ visual-studio-2015 scipy pybind11