【Tensorflow】TensorFlow的嵌入layer和多层layer
生活随笔
收集整理的這篇文章主要介紹了
【Tensorflow】TensorFlow的嵌入layer和多层layer
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
計算圖中的操作
# python 3.6 import tensorflow as tf import numpy as npsess = tf.Session()# 將張量和占位符對象組成一個計算圖,創建一個簡單的分類器# 一、計算圖中的操作 # 1. 聲明張量和占位符,創建numpy數組,傳入計算圖操作 x_vals = np.array([1.,3.,5.,7.,9.]) x_data = tf.placeholder(tf.float32) m_const = tf.constant(3.) my_product = tf.multiply(x_data, m_const) for x_val in x_vals:print(sess.run(my_product, feed_dict={x_data: x_val})) #輸出: # 3.0 # 9.0 # 15.0 # 21.0 # 27.0計算圖中的操作
工作原理:
嵌入Layer
# python 3.6 import tensorflow as tf import numpy as npsess = tf.Session() # 二、TensorFlow的嵌入layer # 在同一個計算圖中進行多個乘法操作 # 1. 創建數據和占位符 array = np.array([[1.,3.,5.,7.,9.],[2.,4.,6.,8.,10.],[-4,-2,0,1,2]]) # 3×5的矩陣 x_vals = np.array([array, array+1]) # 兩個3×5的矩陣 # 如果未知占位符的維度可以設為None shape=(3,None) x_data = tf.placeholder(tf.float32,shape=(3,5))# 2. 創建常量矩陣 c1 = tf.constant([[1.],[0.],[-1.],[3.],[2.]]) c2 = tf.constant([[2.]]) c3 = tf.constant([[10.]])# 3. 聲明計算圖操作 prod1 = tf.matmul(x_data, c1) # (3,5) × (5×1) = (3,1) prod2 = tf.matmul(prod1, c2) # (3,1) × (1×1) = (3,1) add1 = tf.add(prod2, c3) # print(prod2) print(c3) print(add1) # 4. 計算圖賦值 for x_val in x_vals:print(sess.run(add1,feed_dict={x_data:x_val}))# print("----")# print(sess.run(prod2,feed_dict={x_data:x_val}))# print("----")# print(sess.run(c3,feed_dict={x_data:x_val}))# print("----")# print(sess.run(add1,feed_dict={x_data:x_val}))原理:
多層Layer
# 三、TensorFlow的多層Layer # 如何連接傳播數據的多層layer? # 1. 通過numpy創建2D圖像,4×4像素圖片。 # 將創建成四維:第一維和最后一維大小為1。 # 注意,TensorFlow的圖像函數是處理四維圖片的, # 這四維是:圖片數量(1)、高度、寬度和顏色通道(1)。 # 這里是一張圖片,單顏色通道,所以設兩個維度值為1: x_shape = [1,4,4,1] x_val = np.random.uniform(size=x_shape)# 2. 創建占位符,用來傳入圖片 x_data = tf.placeholder(tf.float32,shape=x_shape)# 3. 創建過濾4×4像素圖片的滑動窗口 # 用conv2d()卷積2×2形狀的常量窗口:傳入滑動窗口、過濾器和步長 # 窗口大小:2×2 步長:2 # 為了計算平均值,用常量為0.25的向量與2×2窗口卷積 filter = tf.constant(0.25, shape=[2,2,1,1]) strides = [1,2,2,1] mov_avg_layer = tf.nn.conv2d(x_data,filter,strides,padding='SAME', name='Moving_Avg_Window')# 4. 自定義layer,操作滑動窗口平均的2×2的返回值 # 輸入張量乘以2×2的矩陣張量 然后每個元素加1 # 因為矩陣乘法只計算二維矩陣所以剪裁squeeze()圖形的多余維度 def custom_layer(input_matrix):input_matrix_sqeezed = tf.squeeze(input_matrix)a = tf.constant([[1.,2.],[-1.,3.]])b = tf.constant(1.,shape=[2,2])temp1 = tf.matmul(a, input_matrix_sqeezed)temp = tf.add(temp1,b)return tf.sigmoid(temp)# 5. 將自定義的layer加入計算圖,用tf.name.scope命名唯一的layer名字 # 后續在計算圖中可以折疊或者擴展Custom_Layer with tf.name_scope('Custom_Layer') as scope:custom_layer1 = custom_layer(mov_avg_layer)# 6. 傳入4×4的像素圖片,執行計算圖 print(sess.run(custom_layer1, feed_dict={x_data:x_val}))原理
總結
以上是生活随笔為你收集整理的【Tensorflow】TensorFlow的嵌入layer和多层layer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android官方开发文档Trainin
- 下一篇: 随机/线性颜色生成器(RandomCol