前言
实现孪生卷积神经网络时,验证是否共享了参数,进行了特征图可视化。由于卷积层特征图通道都很大,需要进行重新reshape成Tensorboard可以显示的通道数(1或3或4),这里全部变成了单通道的特征图。没有使用tf.reshape()是因为发现有问题,所以还是自己重新利用tf.concat进行reshape。
效果
代码提示
主要是最后两个函数,一个添加Tensorboard,一个对特征图进行reshape,很简单的思路。如果嫌特征图太小了,可以选择每次选一半的特征图进行reshape。见代码注释!
代码
# coding=utf-8
"""孪生卷积神经网络"""
import tensorflow as tf
import numpy as np
import math
class SiameseNet(object):
def __init__(self):
print("正在构建孪生网络...")
self.opts = {
'trainWeightDecay': 0.0, 'stddev': 0.01}
def build_siamese_cnn_network(self, input):
first_image = tf.expand_dims(input[:, :, :, 0], 3)
second_image = tf.expand_dims(input[:, :, :, 1], 3)
with tf.variable_scope('siamese_CNN') as scope:
first_output = self._build_branch(first_image, True)
scope.reuse_variables()
second_output = self._build_branch(second_image, False)
return first_output, second_output
def _build_branch(self, image, branch):
print("构建孪生网络分支...")
with tf.variable_scope('conv_block1_1'):
print("构建conv1,relu1...")
name = tf.get_variable_scope().name
outputs = self._conv(image, 64, 3, 1, self.opts['trainWeightDecay'], self.opts['stddev'])
o