温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-04 22:54:41 来源:脚本之家 阅读:161 作者:yuanCruise 栏目:开发技术

目的

将用户自定义的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并添加到计算图中就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI