TensorFlow 机器学实战指南示例代码之 TensorFlow 的多层 Layer
2018-02-05 22:11
357 查看
""" 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
- TensorFlow 机器学实战指南示例代码之 TensorFlow 实现损失函数
- TensorFlow 机器学实战指南示例代码之 TensorFlow 实现反向传播(一)
- TensorFlow 机器学实战指南示例代码之 TensorFlow 实现反向传播(二)
- TensorFlow 机器学实战指南示例代码之 TensorFlow 实现随机训练和批量训练
- 免费教材丨第55期:Python机器学习实践指南、Tensorflow 实战Google深度学习框架
- 深度学习之卷积神经网络CNN及tensorflow代码实现示例
- Spring Boot实战之数据库操作的示例代码
- 机器学习之主成分分析PCA及代码示例
- 机器学习实战 朴素贝叶斯原理及代码
- ActiveMQ实战(二)-代码示例
- Python机器登陆新浪微博代码示例
- 深度学习DeepLearning.ai系列课程学习总结:8. 多层神经网络代码实战
- tensorflow实战系列(四)基于TensorFlow构建AlexNet代码解析
- tensorflow示例代码注释3
- android 监听网络状态的变化及实战的示例代码
- 机器学习实战笔记(3.2)-朴素贝叶斯算法(贝努力模型代码实现)
- asp+mapxtreme的示例代码-通过layerinfo创建图层并画矩形
- [01]tensorflow跑示例代码
- 实战基本的Linux sed命令示例代码