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

Dabria ·
更新时间:2024-09-21
· 795 次阅读

目的

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

您可能感兴趣的文章:tensorflow之自定义神经网络层实例python使用tensorflow深度学习识别验证码对tensorflow中tf.nn.conv1d和layers.conv1d的区别详解



计算图 tensorflow

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章