简体   繁体   中英

Initialize variables in Tensorflow C++ API

I am having trouble finding a working way to initialize variables in the C++ API for Tensorflow. I am trying to make a basic fully connected single layer neural network for the MNIST dataset.

Currently, what I've found is that the proper way to do it is like this:

TF_CHECK_OK(session->Run({}, {}, {"init_all_vars_op"}, nullptr));

However, using this returns the following error:

tensorflow/cc/example/example.cc:178:71: error: no matching function for call to 'tensorflow::ClientSession::Run(<brace-enclosed initializer list>, <brace-enclosed initializer list>, <brace-enclosed initializer list>, std::nullptr_t)' .

Has anyone encountered this before? If you did, how did you fix it?

EDIT: I should add that if I remove any attempt at initializing the variables I use and just run the session it will compile, but it returns:

2017-06-27 11:31:12.861244: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.

2017-06-27 11:31:12.862007: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.

2017-06-27 11:31:12.862433: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.

2017-06-27 11:31:12.866282: F tensorflow/cc/example/example.cc:180] Non-OK-status: session->Run(feed ,{y_pred} ,&outputs) status: Failed precondition: Attempting to use uninitialized value weights

[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/cpu:0"](_arg_x_0_0, weights)]]

/usr/bin/bazel exited with code 8

I've managed to find a solution that only works in the context where the initial state of the variables is unimportant. You can use the Assign method to assign a value of 0 initially to the variable, as Assign doesn't require that the variable is initialized before-hand. This initialization should be done before the train loop:

auto init_value = Const(root, 0);

auto assign = Assign(root.WithOpName("assign"), var, init_value);

I've yet to run a test on this code snippet but it compiles in my current source code.

It looks like the code is not compiling with that call to session.run. It could be due to problematic type inference as tensorflow::ClientSession::Run is overloaded with many different signatures. Try replacing the {} initializers with explicit type names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM