tensorflow 實現(xiàn)自定義layer并添加到計算圖中
目的
將用戶自定義的layer結(jié)合tensorflow自帶的layer組成多層layer的計算圖。
實現(xiàn)功能
對2D圖像進行滑動窗口平均,并通過自定義的操作layer返回結(jié)果。
import tensorflow as tf import numpy as np sess = tf.Session() #將size設(shè)為[1, 4, 4, 1]是因為tf中圖像函數(shù)是處理四維圖片的。 #這四維依次是: 圖片數(shù)量,高度, 寬度, 顏色通道 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圖片,并執(zhí)行計算圖 print(sess.run(custom_layer, feed_dict= {x_data: x_val}))
以上這篇tensorflow 實現(xiàn)自定義layer并添加到計算圖中就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python?turtle.right與turtle.setheading的區(qū)別講述
這篇文章主要介紹了Python?turtle.right與turtle.setheading的區(qū)別,本文以turtle.right為例給大家詳細(xì)介紹,需要的朋友可以參考下2022-03-03Python numpy二維數(shù)組如何刪除指定行和列
本文展示了如何對數(shù)組進行行列刪除操作,包括刪除單行、單列、多行和多列的方法,通過具體的運行結(jié)果展示,讀者可以清晰地了解到如何在不同情況下進行數(shù)據(jù)處理,文章內(nèi)容實用,適合需要進行數(shù)據(jù)處理的讀者參考學(xué)習(xí)2024-09-09python heic后綴圖片文件轉(zhuǎn)換成jpg格式的操作
這篇文章主要介紹了python heic后綴圖片文件轉(zhuǎn)換成jpg格式的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python中的map()函數(shù)和reduce()函數(shù)的用法
這篇文章主要介紹了Python中的map()函數(shù)和reduce()函數(shù)的用法,代碼基于Python2.x版本,需要的朋友可以參考下2015-04-04Django框架中render_to_response()函數(shù)的使用方法
這篇文章主要介紹了Django框架中render_to_response()函數(shù)的使用方法,注意范例中該方法的參數(shù)的使用,需要的朋友可以參考下2015-07-07