Tensorflow_gpu训练手写数字pb模型文件,C++调用预测

Tensorflow_gpu训练手写数字pb模型文件,C++调用预测

没啥好说,直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 09:50:41 2019

@author: admin
"""

# Python3

# 使用LeNet5的七层卷积神经网络用于MNIST手写数字识别

import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
pb_file_path = os.getcwd() #获取当前代码路径

# 为输入图像和目标输出类别创建节点
tf.reset_default_graph()
x = tf.placeholder(tf.float32, shape=[None, 784],name='x') # 训练所需数据 占位符
y_ = tf.placeholder(tf.float32, shape=[None, 10]) # 训练所需标签数据 占位符

# *************** 构建多层卷积网络 *************** #

# 权重、偏置、卷积及池化操作初始化,以避免在建立模型的时候反复做初始化操作
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1) # 取随机值,符合均值为0,标准差stddev为0.1
return tf.Variable(initial)

def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)

# x 的第一个参数为图片的数量,第二、三个参数分别为图片高度和宽度,第四个参数为图片通道数。
# W 的前两个参数为卷积核尺寸,第三个参数为图像通道数,第四个参数为卷积核数量
# strides为卷积步长,其第一、四个参数必须为1,因为卷积层的步长只对矩阵的长和宽有效
# padding表示卷积的形式,即是否考虑边界。"SAME"是考虑边界,不足的时候用0去填充周围,"VALID"则不考虑
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

# x 参数的格式同tf.nn.conv2d中的x,ksize为池化层过滤器的尺度,strides为过滤器步长
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

#把x更改为4维张量,第1维代表样本数量,第2维和第3维代表图像长宽, 第4维代表图像通道数
x_image = tf.reshape(x, [-1,28,28,1]) # -1表示任意数量的样本数,大小为28x28,深度为1的张量

# 第一层:卷积
W_conv1 = weight_variable([5, 5, 1, 32]) # 卷积在每个5x5的patch中算出32个特征。
b_conv1 = bias_variable([32])

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

# 第二层:池化
h_pool1 = max_pool_2x2(h_conv1)

# 第三层:卷积
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

# 第四层:池化
h_pool2 = max_pool_2x2(h_conv2)

# 第五层:全连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# 在输出层之前加入dropout以减少过拟合
keep_prob = tf.placeholder(tf.float32, name="keep_prob")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# 第六层:全连接层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

# 第七层:输出层
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2,name='y')

# *************** 训练和评估模型 *************** #

# 为训练过程指定最小化误差用的损失函数,即目标类别和预测类别之间的交叉熵
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))

# 使用反向传播,利用优化器使损失函数最小化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 检测我们的预测是否真实标签匹配(索引位置一样表示匹配)
# tf.argmax(y_conv,dimension), 返回最大数值的下标 通常和tf.equal()一起使用,计算模型准确度
# dimension=0 按列找 dimension=1 按行找
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))

# 统计测试准确率, 将correct_prediction的布尔值转换为浮点数来代表对、错,并取平均值。
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

saver = tf.train.Saver() # 定义saver

# *************** 开始训练模型 *************** #
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())

for i in range(1002):
batch = mnist.train.next_batch(50)
if i%100 == 0:

# 评估模型准确度,此阶段不使用Dropout
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
# 训练模型,此阶段使用50%的Dropout
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
if i%100 == 0:
constant_graph = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def, ['x','y','keep_prob'])
with tf.gfile.FastGFile('e:\\model.pb', mode='wb') as f: #模型的名字是model.pb
f.write(constant_graph.SerializeToString())
saver.save(sess, './save/model.ckpt') #模型储存位置

print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images [0:2000], y_: mnist.test.labels [0:2000], keep_prob: 1.0}))

训练会生成pb文件,到e:\model.pb,随后用python调用,调用代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 10:21:40 2019

@author: admin
"""

from PIL import Image
import tensorflow as tf
from tensorflow.python.platform import gfile
import numpy as np

im = Image.open('C:\\Users\\admin\\Pictures\\3.png')
data = list(im.getdata())
result = [(255-x)*1.0/255.0 for x in data]
#print(result)

# 为输入图像和目标输出类别创建节点
tf.reset_default_graph()
#x = tf.placeholder("float", shape=[None, 784]) # 训练所需数据 占位符

# *************** 开始识别 *************** #
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
with gfile.FastGFile('e:\\model.pb', 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
x = sess.graph.get_tensor_by_name("x:0")
y = sess.graph.get_tensor_by_name("y:0")
keep_prob = sess.graph.get_tensor_by_name("keep_prob:0")
# print(test)
#saver.restore(sess, "./save/model.ckpt")#这里使用了之前保存的模型参数

prediction = tf.argmax(y,1)
predint = prediction.eval(feed_dict={x: [result],keep_prob: 1.0}, session=sess)

print("recognize result: %d" %predint[0])

使用到的图片是这个,你可以自己下载直接用,也可以手写然后用OpenCV处理得到28*28的灰度图片。


3

Visual C++调用pb文件预测

也是直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#define COMPILER_MSVC
#define NOMINMAX
#define PLATFORM_WINDOWS

#include <fstream>

#include <utility>
#include<vector>
#include<string>

#include<opencv2/opencv.hpp>
#include"tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/cc/ops/standard_ops.h"

using namespace tensorflow;
using tensorflow::Tensor;
using std::cout;
using std::endl;

int main() {
// 设置输入图像
cv::Mat img = cv::imread("C:\\Users\\admin\\Pictures\\3.png");
cv::cvtColor(img, img, cv::COLOR_BGR2GRAY);
int height = img.rows;
int width = img.cols;
int depth = img.channels();
cv::Mat img_transpose = img.t();

// 取图像数据,赋给tensorflow支持的Tensor变量中
const float* source_data = (float*)img.data;
cout<<source_data[1]<<endl;
tensorflow::Tensor input_tensor(DT_FLOAT, TensorShape({ 1, height, width ,1 })); //这里只输入一张图片,参考tensorflow的数据格式NHWC
auto input_tensor_mapped = input_tensor.tensor<float,4>(); // input_tensor_mapped相当于input_tensor的数据接口,“4”表示数据是4维的。后面取出最终结果时也能看到这种用法

// 把数据复制到input_tensor_mapped中,实际上就是遍历opencv的Mat数据
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
input_tensor_mapped(0, i, j ,0) = (255- img.at<uchar>(i, j))/255.0;

}
}

// 初始化tensorflow session
Session* session;
Status status = NewSession(SessionOptions(), &session);
if (!status.ok()) {
std::cerr << status.ToString() << endl;
return -1;
}
else {
cout << "Session created successfully" << endl;
}


// 读取二进制的模型文件到graph中
GraphDef graph_def;
status = ReadBinaryProto(Env::Default(), "e:\\model.pb", &graph_def);
if (!status.ok()) {
std::cerr << status.ToString() << endl;
return -1;
}
else {
cout << "Load graph protobuf successfully" << endl;
}


// 将graph加载到session
status = session->Create(graph_def);
if (!status.ok()) {
std::cerr << status.ToString() << endl;
return -1;
}
else {
cout << "Add graph to session successfully" << endl;
}

tensorflow::Tensor keep_prob(DT_FLOAT, TensorShape());
keep_prob.scalar<float>()() = 1.0;
std::vector<std::pair<std::string, tensorflow::Tensor>> inputs = {
{ "x", input_tensor },
{ "keep_prob", keep_prob },
};

// 输出outputs
std::vector<tensorflow::Tensor> outputs;

// 运行会话,计算输出"x_predict",即我在模型中定义的输出数据名称,最终结果保存在outputs中
auto input_shape = input_tensor.shape();
status = session->Run(inputs, { "y" }, {}, &outputs);
if (!status.ok()) {
std::cerr << status.ToString() << endl;
system("pause");
return -1;
}
else {
cout << "Run session successfully" << endl;
}
// 下面进行输出结果的可视化
tensorflow::Tensor output = std::move(outputs.at(0)); // 模型只输出一个结果,这里首先把结果移出来(也为了更好的展示)
auto out_shape = output.shape(); // 这里的输出结果为1x4x16
auto out_val = output.tensor<float, 2>(); // 与开头的用法对应,3代表结果的维度
// cout << out_val.argmax(2) << " "; // 预测结果,与python一致,但具体数值有差异,猜测是计算精度不同造成的
cout <<"Output tensor shape:"<< output.shape()<<endl;
for (int j = 0; j < out_shape.dim_size(1); j++) {
cout << out_val(0, j) << " ";
}
cout << "size:" << out_shape.dim_size(1)<<endl;
cout <<"Prediction value:"<< out_val.argmax(1)<<endl;
system("pause");
}

相关配置都有在前两篇博客写过,就不赘述了。这里要说下CUDA配置完Tensorflow C++使用坑爹的地方,如果你同时开着python的tensorflowIDE环境,它会分出部分GPU内存给该环境,但是如果你用上面的代码运行测试,会发现报内存超出的错。


normal

正常调用会这样,但是开着其他环境,就报错:


abnormal

CUDA_ERROR_OF_MEMORY,然后更坑爹的是我的c++无法同python一样指定gpu内存分配,会报unresolved external symbol错误,也就是未解析的外部符号。解决办法就一个,关掉其他gpu进程。

预测结果如下:


c++预测

细节回去再更….