Python教程

C++ python混合编程

本文主要是介绍C++ python混合编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
  • 配置属性->常规->配置类型为应用程序(.exe)
  • 配置属性->高级->目标文件扩展名为.exe
#include <iostream>
#include <pybind11/embed.h>

namespace py = pybind11;

int main() {
    // start the interpreterand keep it alive
    py::scoped_interpreter guard{};

    auto math = py::module::import("math");
    double root_two = math.attr("sqrt")(2.0).cast<double>();

    std::cout << "The square root of 2 is: " << root_two << "\n";
}

编译成功,运行报错:Fatal Python error: initfsencoding: unable to load the file system codec. ModuleNotFoundError: No module named ‘encodings’
原因在于:需要在用户变量中添加PYTHONHOME和PYTHONPATH两个变量,路径均为python文件夹
链接:链接
C++将python训练的模型导入并预测

#include <iostream>
#include <pybind11/embed.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <vector>
#include <array>
#include <time.h>
namespace py = pybind11;
using namespace std;


//*指针-->numpy 1D
template<typename T>
py::array_t<T> _ptr_to_arrays_1d(T* data, py::ssize_t col) {
    auto result = py::array_t<T>(col);//申请空间
    py::buffer_info buf = result.request();
    T* ptr = (T*)buf.ptr;//获取py::array的指针并隐式转换类型为T*

    for (auto i = 0; i < col; i++)
        ptr[i] = data[i];

    return result;
}


//numpy 1D->interger,如[1]->1
int array_to_int(py::array data) {
    py::buffer_info buf = data.request();
    int* ptr = (int*)buf.ptr;
    return *ptr;
}

//numpy 1D->vector
vector<double> array_to_vector(py::array data,  py::ssize_t col) {
    py::buffer_info buf = data.request();
    double* ptr = (double*)buf.ptr;
    vector<double> res;
    
    for (int i = 0; i < col; i++) {
        res.push_back(ptr[i]);
    }
    return res;
}

//numpy 1D->array
array<double,4> nparray_to_array(py::array data, py::ssize_t col) {
    py::buffer_info buf = data.request();
    double* ptr = (double*)buf.ptr;
    array<double, 4> res;

    for (int i = 0; i < col; i++) {
        res[i] = ptr[i];
    }
    return res;
}

//*指针-->numpy 1D
template<typename T>
py::array_t<T> ptr_to_arrays_1d(T* data, py::ssize_t col) {
    py::array_t<double> out = py::array_t<double>(col);
    auto r3 = out.mutable_unchecked<1>();

    for (int i = 0; i < col; i++)
        r3(i) = data[i];

    return out;
}
//*****测试******//
int main1() {
    py::scoped_interpreter guard{};//python初始化 

    //*测试1D
    double data1[] = { 1.1,2.2,3.3,4.4 };
    py::array_t<double> _arr1 = _ptr_to_arrays_1d(data1, 4);
    py::array_t<double> _arr2 = _ptr_to_arrays_1d(data1, 4);
    py::array_t<double> arr1 = ptr_to_arrays_1d(data1, 4);
    py::array_t<double> arr2 = ptr_to_arrays_1d(data1, 4);

    py::print(_arr1);
 
    py::print(_arr2);

    py::array a = _arr1.attr("reshape")(1, -1);
    py::print(a);

    int data2[] = { 1 };
    py::array_t<int> _arr_test = _ptr_to_arrays_1d(data2, 1);
    int res = array_to_int(_arr_test);
    cout << res << endl;
}

int main() {
    // start the interpreterand keep it alive
    py::scoped_interpreter guard{};

    auto math = py::module::import("math");//=import math
    double root_two = math.attr("sqrt")(2.0).cast<double>();//=math.sqrt(2.0)

    std::cout << "The square root of 2 is: " << root_two << "\n";


    auto joblib2 = py::module::import("sklearn.externals").attr("joblib");//=from sklearn.externals import joblib
    auto datasets= py::module::import("sklearn").attr("datasets");//=from sklearn import datasets
    auto numpy = py::module_::import("numpy");//=import numpy
    auto randomForest = py::module::import("sklearn.ensemble").attr("RandomForestClassifier");
    auto rfc2 = joblib2.attr("load")("G:/0/rfc.pkl");//加载模型 =rfc2 = joblib.load('G:/0/rfc.pkl')
  
    py::print(rfc2);
    double data1[] = { 5.1 ,3.5 ,1.4 ,0.2 };
    py::array_t<double> _arr1 = _ptr_to_arrays_1d(data1, 4);//[5.1 3.5 1.4 0.2]
    py::array a = _arr1.attr("reshape")(1, -1);//=_attr1.reshape(1,-1),[[5.1 3.5 1.4 0.2]]
    py::print(a);

    auto predict_value = rfc2.attr("predict")(a);//=rfc2.predict(a)
    py::print(predict_value);//[0]
    int res = array_to_int(predict_value);
    cout << res << endl;//0
    
}

//****测试代码运行速度*****//
//numpy 1D->interger 0.193s
//*指针-->numpy 1D 0.175s
int main3() {
    py::scoped_interpreter guard{};
    clock_t start, finish;
    start = clock();
    int T = 10000;
    while (T--) {
        double data1[] = { 5.1 ,3.5 ,1.4 ,0.2 };
        py::array_t<double> _arr1 = _ptr_to_arrays_1d(data1, 4);
        py::array a = _arr1.attr("reshape")(1, -1);
    }
    finish = clock();
    cout << endl << "the time cost is:" << double(finish - start) / CLOCKS_PER_SEC << endl;
}

//****测试vector和numpy互转
int main4() {
    py::scoped_interpreter guard{};
    vector<double> vi = { 1.1,2.2,3.3,4.4 };
    double* data = vi.data();//vector->数组
    cout << *data << endl;
    py::array_t<double> _arr1 = _ptr_to_arrays_1d(data, 4);//数组->numpy
    py::print(_arr1);

    vector<double> res = array_to_vector(_arr1, 4);//numpy->vector
    for (auto x : res) {
        cout << x << " ";
    }
}

//****测试array和numpy互转
int main5() {
    py::scoped_interpreter guard{};
    array<double, 4> ar = { 1.1,2.2,3.3,4.4 };
    double* data = ar.data();//array->数组
    py::array_t<double> _arr1 = _ptr_to_arrays_1d(data, 4);//数组->numpy
    py::print(_arr1);

    array<double, 4> res = nparray_to_array(_arr1, 4);//numpy->array
    for (auto x : res) {
        cout << x << " ";
    }
}
这篇关于C++ python混合编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!