我使用以下简单的卷积网络:
def forward_pass(train_batch):
with tf.name_scope('input'):
inputData = tf.identity(train_batch)
#network definition
#image input 32 x 32 x 3
#weights for the first convolution layer
with tf.name_scope('conv1'):
W_conv1 = weight_variable([5, 5, 3, 6])
b_conv1 = bias_variable([6])
#structure of the first convolution layer: convolution, activation, pooling
h_conv1 = tf.nn.tanh(tf.nn.bias_add(conv2d(inputData, W_conv1), b_conv1))
with tf.name_scope('pool1'):
h_pool1 = max_pool_2x2(h_conv1)
#image input 14 x 14 x 6
#weights for the second convolution layer
with tf.name_scope('conv2'):
W_conv2 = weight_variable([5, 5, 6, 16])
b_conv2 = bias_variable([16])
#structure of the second convolution layer: convolution, activation, pooling
h_conv2 = tf.nn.tanh(tf.nn.bias_add(conv2d(h_pool1, W_conv2), b_conv2))
with tf.name_scope('pool2'):
h_pool2 = max_pool_2x2(h_conv2)
#image input 10 x 10 x 16
with tf.name_scope('reshape'):
h_pool2_flat = tf.reshape(h_pool2, [-1, 5 * 5 * 16])
#fully connected layer
with tf.name_scope('fc'):
W_fc1 = weight_variable([5 * 5 * 16, 46])
b_fc1 = bias_variable([46])
y_re = tf.matmul(h_pool2_flat, W_fc1)
fc_output = tf.nn.bias_add(y_re, b_fc1)
with tf.name_scope('output'):
output = tf.multiply(fc_output, 1.)
return output
为了训练网络,我使用Adam优化器,如下所示:
output = forward_pass(train_batch)
with tf.name_scope('one-hot'):
label_batch_vector = tf.one_hot(label_batch, 46)
with tf.name_scope('loss'):
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=label_batch_vector, logits=output))
with tf.name_scope('adam-optimizer'):
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
要保存我最后使用的网络:
tf.train.write_graph(sess.graph.as_graph_def(), "", 'graph.pb')
使用TensorFlow进行培训会产生良好的效果,但现在我想使用OpenCV中的网络。
我按如下方式转换网络:
python3 $TF_TOOLS/freeze_graph.py \
--input_graph=graph.pb \
--input_checkpoint=Model.ckpt \
--output_graph=frozen_graph.pb \
--output_node_names=output/Mul
python3 $TF_TOOLS/optimize_for_inference.py \
--input frozen_graph.pb \
--output opt_graph.pb \
--frozen_graph True \
--input_names input/Identity \
--output_names output/Mul
我正在使用opt_graph.pb来加载带有cv :: dnn :: readNetFromTensorflow的模型。然后我测试我的训练数据,我得到2%的识别率。有人可以帮忙吗?是否有可能我没有在opt_graph.pb中正确保存权重?对我而言,似乎训练数据已经丢失。
答案 0 :(得分:0)
解决方案是在tf.reshape操作之前添加tf.transpose(h_pool2,[0,3,1,2])操作。请参阅https://github.com/opencv/opencv/issues/10065中的其他信息。