"""
TensorFlow 的多层 Layer
"""
import os
import tensorflow as tf
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
s = tf.Session()
# TensorFlow 的图像函数处理的图像是四维(图像的数量,高度,宽度和颜色通道)
# 创建 4*4 像素图片
x_shape = [1, 4, 4, 1]
x_val = np.random.uniform(size=x_shape)
# 在计算图中创建占位符,占位符是用来传入图片的
x_data = tf.placeholder(tf.float32, shape=x_shape)
# 使用 TensorFlow 内建函数创建过滤 4*4 图像的滑动窗口
# 卷积 2*2 形状的常量窗口
my_filter = tf.constant(0.25, shape=[2, 2, 1, 1])
# 创建一个 2*2 的窗口,每个方向长度为2的步长
my_strides = [1, 2, 2, 1]
"""
第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数]
注意这是一个4维的Tensor,要求类型为float32和float64其中之一
第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]这样的shape,
具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,有一个地方需要注意,第三维in_channels,
就是参数input的第四维
第三个参数strides:卷积时在图像每一维的步长
第四个参数padding:string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式(后面会介绍)
第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true
"""
# 通过 conv2d 的函数的 name 参数,把这层 Layer 命名为 "Moving_Avg_Window"
mov_avg_layer = tf.nn.conv2d(x_data, my_filter, my_strides, padding='SAME', use_cudnn_on_gpu=False,
name='Moving_Avg_Window')
# 自定义一个 Layer,操作滑动窗口平均的 2*2 的返回值
def custom_layer(input_matrix):
input_matrix_sqeezed = tf.squeeze(input_matrix) # 通过TensorFlow 内建函数 squeeze() 剪裁,去掉维度为 1 的维
a = tf.constant([[1., 2.], [-1., 3.]])
b = tf.constant(1., shape=[2, 2])
temp1 = tf.matmul(a, input_matrix_sqeezed)
temp = tf.add(temp1, b) # Ax + b
return tf.sigmoid(temp)
# 把刚定义的 Layer 加入到计算图中,并用 tf.name_scope() 命名唯一的 Layer 名字
with tf.name_scope('Custom_Layer') as scope:
custom_layer1 = custom_layer(mov_avg_layer)
# 为占位符传入 4*4 像素图片,然后执行计算图
print(s.run(custom_layer1, feed_dict={x_data: x_val}))
TensorFlow 机器学实战指南示例代码之 TensorFlow 的多层 Layer
最新推荐文章于 2020-02-03 10:56:54 发布