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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-04-02 我要评论

目的

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

实现功能

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

import tensorflow as tf
import numpy as np
sess = 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并添加到计算图中就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们