TensorFlow单层Layer示例请参考我的博客--Tensorboard计算图问题汇总
下面我们尝试构建多层Layer
首先引入tensorflow库并创建计算图会话
import tensorflow as tf import numpy as np sess = tf.Session()
接下来,通过numpy创建2D图像,并将其数据改变为4维,分别是:图片数量、高度、宽度、颜色通道
创建占位符
x_shape = [1,4,4,1] x_val = np.random.uniform(size=x_shape) x_data = tf.placeholder(tf.float32,shape=x_shape)
为了创建过滤4*4像素图片的华东窗口,我们采用conv2d卷积2×2形状的常量窗口,其中conv2d需要传入滑动窗口、过滤器和步长。这里,我们选用各个方向步长为2,过滤器(滤波器)采用均值滤波器(平均值),padding为是否进行扩展,这里选用‘SAME’
#第一层 my_filter = tf.constant(0.25,shape=[2,2,1,1]) my_strides = [1,2,2,1] mov_avg_layer = tf.nn.conv2d(x_data,my_filter,my_strides,padding='SAME',name='Moving_Avg_Window')
现在我们自定义一个层,对第一层的输出进行y=wx+b操作
def custom_layer(input_matrix): input_matrix_sqeezed = tf.squeeze(input_matrix) #去掉维度为1的值 例如[1,2,3,4]==>[2,3,4],[1,3,1,4]==>[3,4] A = tf.constant([[1.,2.],[-1.,3.]]) b = tf.constant(1.,shape=[2,2]) temp1 = tf.matmul(A,input_matrix_sqeezed) temp2 = tf.add(temp1,b) return temp2
这里用tf.name_scope命令该层的名字,当然也可以不要这句代码,直接执行custom_layer1 = custom_layer(mov_avg_layer)
with tf.name_scope('Custom_Layer') as scope: custom_layer1 = custom_layer(mov_avg_layer) print(sess.run(custom_layer1,feed_dict={x_data:x_val})) log = './log' write = tf.summary.FileWriter(logdir=log,graph=sess.graph)
最后我们通过sess.run执行计算图,并通过tensorboard打开