首页 > 编程 > Python > 正文

tensorflow 实现自定义layer并添加到计算图中

2020-02-15 21:25:18
字体:
来源:转载
供稿:网友

目的

将用户自定义的layer结合tensorflow自带的layer组成多层layer的计算图。

实现功能

对2D图像进行滑动窗口平均,并通过自定义的操作layer返回结果。

import tensorflow as tfimport numpy as npsess = tf.Session()#将size设为[1, 4, 4, 1]是因为tf中图像函数是处理四维图片的。#这四维依次是: 图片数量,高度, 宽度, 颜色通道x_shape = [1,4,4,1]x_val = np.random.uniform(size = x_shape)#tf.nn.conv2d中name表明该layer命名为“Moving_Avg_Window”#该卷积核为[[0.25,0.25],[0.25,0.25]],所以是一个求平均操作x_data = tf.placeholder(tf.float32, shape = x_shape)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')#自定义layer,对卷积操作之后的输出做操作def custom_layer(input_matrix):  input_matrix_sqeeze = tf.squeeze(input_matrix)  A = tf.constant([1.,2.],[-1.,3.])  b = tf.constant(1., shape = [2,2])  temp1 = tf.matmul(A, input_matrix_sqeeze)  temp2 = tf.add(temp1, b)  return(tf.sigmod(temp2))#把刚刚自定义的layer加入到计算图中,并给予自定义的命名(利用tf.name_scope())with tf.name_scope('Custom_Layer') as scope:  custom_layer1 = custom_layer(mov_avg_layer)#为占位符传入4*4图片,并执行计算图print(sess.run(custom_layer, feed_dict= {x_data: x_val}))

以上这篇tensorflow 实现自定义layer并添加到计算图中就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林站长站。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表