有时我想将Tensorflow应用程序构建为动态链接库,以便其他C ++应用程序可以调用它。尽管我可以使用Tensorflow C ++ API来构建数据流图,但我还是更喜欢使用它的Python API,因为许多共享模型是由该API编写的。
以下是我使用Cython包装Tensorflow应用程序的方法之一。但是,最终出现“找不到tensorflow.pxd”错误。
首先,这是python代码:
#File Name: HelloTensorflow.pyx
cimport numpy as np
cimport tensorflow as tf
cdef public float ExecuteTensorFlow():
x = tf.placeholder(tf.float32, [1, 2])
w = tf.constant([0.2, 0.3], tf.float32)
b = tf.constant( -0.1, tf.float32)
linearModel = tf.matmul(x, tf.reshape(w, shape=[2, 1])) + b
session = tf.Session()
result = session.run(linearModel, feed_dict={x: np.reshape([-0.1, -0.4], [1, 2])} )
return np.reshape(result, [])
Run Code Online (Sandbox Code Playgroud)
以及将调用它的C ++源代码:
// File Name: CppCallPython.cpp
#include <Python.h>
#include "HelloTensorflow.h"
#include <iostream> …Run Code Online (Sandbox Code Playgroud)