Tensorflow C ++版本:1.13.1
平台:Ubuntu16.04
工具:日食
我已经构建了libtensorflow_cc.so并通过一些示例(例如加载mnist数据集)成功对其进行了测试。
enter image description here
即使打印一些警告,上图也能返回正确的结果。 最近,我尝试将python代码转换为c ++版本,下面是一段python代码。
import tensorflow as tf
import numpy as np
from skimage import io, transform
import cv2
sess = tf.Session()
new_saver = tf.train.import_meta_graph(r'D:\CNN_test_result_sizhuangzao_model\v2_101_ziji_9\model\model.meta') new_saver.restore(sess,tf.train.latest_checkpoint(r'D:\CNN_test_result_sizhuangzao_model\v2_101_ziji_9\model'))
graph = tf.get_default_graph()
#Here is confusing to me."input:0" and "is_training:0" are two tensors in python
#How does tensorflow c++ put in 2 tensors as the first argument of session->run()?
input_x = graph.get_tensor_by_name("input:0")
is_training_x=graph.get_tensor_by_name("is_training:0")
jpg_path=r"D:\CNN_test_result_sizhuangzao\chaodacesiji1\pos.txt"
file = open(jpg_path)
lines = file.readlines()
num=0
for line in lines:
img0 = io.imread(line.strip())
l=img0.shape
k=l[0]
c=l[1]
num+=1
print(num)
if c/k<5:
continue
img = transform.resize(img0, (48,160, 1))
feed_dict={input_x:np.reshape(img, [-1, 48, 160, 1]),is_training_x:False}
#And here 'output' is an operation and "output:0" is a tensor in python.How does tensorflow c++ describe them ?
prob_op = graph.get_operation_by_name('output')
out_softmax = graph.get_tensor_by_name("output:0")
img_out_softmax = sess.run(out_softmax,feed_dict)
prediction_labels = np.argmax(img_out_softmax,1)
我已经尝试过Tensorflow C ++作为以下代码 (此功能根据https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/label_image/main.cc进行了略微更改) ''' int main() { 会话*会话; 状态状态= NewSession(SessionOptions(),&session);
const std::string graph_fn = "/tensorflowtest/model-0617/model.meta";
MetaGraphDef graphdef;
Status status_load = ReadBinaryProto(Env::Default(), graph_fn, &graphdef);
if (!status_load.ok()) {
return -1;
}
Status status_create = session->Create(graphdef.graph_def());
if (!status_create.ok()) {
std::cout << "ERROR: Creating graph in session failed..." << status_create.ToString() << std::endl;
return -1;
}
cout << "Session successfully created.Load model successfully!"<< endl;
const std::string checkpointPath = "/media/root/Ubuntu311/projects/Ecology_projects/tensorflowtest/model-0617/model";
Tensor checkpointPathTensor(DT_STRING, TensorShape());
checkpointPathTensor.scalar<std::string>()() = checkpointPath;
status = session->Run(
{{ graphdef.saver_def().filename_tensor_name(), checkpointPathTensor },},
{},{graphdef.saver_def().restore_op_name()},nullptr);
if (!status.ok())
{
throw runtime_error("Error loading checkpoint from " + checkpointPath + ": " + status.ToString());
}
cout << "Load weights successfully!"<< endl;
//read image for prediction...
string image_path= "/media/root/Ubuntu311/projects/Ecology_projects/copy/cnn-imgs/AABW.jpg";
int input_height =48;
int input_width=160;
int input_mean=0;
int input_std=1;
std::vector<Tensor> resized_tensors;
Status read_tensor_status =
ReadImageFile(image_path, input_height, input_width, input_mean,
input_std, &resized_tensors);
if (!read_tensor_status.ok()) {
LOG(ERROR) << read_tensor_status;
cout<<"resing error"<<endl;
return -1;
}
const Tensor& resized_tensor = resized_tensors[0];
std::cout <<"Read image successfully: "<< resized_tensor.DebugString()<<endl;
//I do not know if it is wrong that making "input" and "is_training" together to the variable--resized_tensor.
std::string Input1Name = "input";
std::string Input2Name = "is_training";
vector<std::pair<string, Tensor> > inputs;
inputs.push_back(std::make_pair(Input1Name, resized_tensor));
inputs.push_back(std::make_pair(Input2Name, resized_tensor));
vector<tensorflow::Tensor> outputs;
//I do not know if i should make "out_softmax" or "output" as the 2nd argument in session->Run and the 3rd should be null or not.
string output2="out_softmax";
string output_ = "output";
//session->Run returns the error information--"model_pruner failed: Invalid argument: Invalid input graph."
Status status_run = session->Run(inputs, {output2}, {}, &outputs);
if (!status_run.ok()) {
std::cout << "ERROR: RUN failed..." << std::endl;
std::cout << status_run.ToString() << "\n";
return -1;
}
...
}
以下信息是整个印刷品:
Session successfully created.Load model successfully!
Load weights successfully!
Read image successfully: Tensor<type: float shape: [1,48,160,1] values: [[[0.592156887][0.603921592][0.603921592]]]...>
2019-07-03 14:47:02.087086: E tensorflow/core/grappler/optimizers/meta_optimizer.cc:486] model_pruner failed: Invalid argument: Invalid input graph.
有帮助吗?