出于学习目的,如何使用 TensorFlow C API 编写这个 Python 示例?
import tensorflow as tf
hello = tf.constant("hello TensorFlow!")
sess=tf.Session()
print(sess.run(hello))
我试过这样:
#include <string.h>
#include <iostream.h>
#include "c_api.h"
int main( int argc, char ** argv )
{
TF_Graph * graph = TF_NewGraph();
TF_SessionOptions * options = TF_NewSessionOptions();
TF_Status * status = TF_NewStatus();
TF_Session * session = TF_NewSession( graph, options, status );
char hello[] = "Hello TensorFlow!";
TF_Tensor * tensor = TF_AllocateTensor( TF_STRING, 0, 0, 8 + TF_StringEncodedSize( strlen( hello ) ) );
TF_OperationDescription * operationDescription = TF_NewOperation( graph, "Const", "hello" );
TF_Operation * operation;
struct TF_Output * output;
TF_StringEncode( hello, strlen( hello ), 8 + ( char * ) TF_TensorData( tensor ), TF_StringEncodedSize( strlen( hello ) ), status );
TF_SetAttrTensor( operationDescription, "value", tensor, status );
TF_SetAttrType( operationDescription, "dtype", TF_TensorType( tensor ) );
operation = TF_FinishOperation( operationDescription, status );
output->oper = operation;
output->index = 0;
TF_SessionRun( session, 0,
0, 0, 0, // Inputs
output, &tensor, 1, // Outputs
&operation, 1, // Operations
0, status );
printf( "%i", TF_GetCode( status ) );
TF_CloseSession( session, status );
TF_DeleteSession( session, status );
TF_DeleteStatus( status );
TF_DeleteSessionOptions( options );
return 0;
}
我正在使用以下TensorFlow.dll
来源在 Windows 上对其进行测试:http:
//ci.tensorflow.org/view/Nightly/job/nightly-libtensorflow-windows/lastSuccessfulBuild/artifact/lib_package/libtensorflow-cpu-windows-x86_64.zip
上面的代码 GPFs 就TF_SessionRun()
调用了。一旦我们找到解决方案,如何检索输出?是否应该为输出使用不同的张量?上面的代码在输出和操作中都重用了它。
非常感谢