TensorFlow學習筆記(三)-- feed_dict 使用


個人理解:就是TF的一種輸入語法。

跟C語言的scanf(),C++的 cin>> 意思差不多,只是長相奇怪了點而已。

做完下面幾個例子,基本也就適應了。

首先占位符申請空間;使用的時候,通過占位符“喂(feed)”給程序。然后程序就可以run了。。。

理解的不一定對,也不夠深入,僅供參考。

import tensorflow as tf
  • tf.placeholder 占位符
  • tf.Session 會話

1. 輸出 Hello World

Str = tf.placeholder(tf.string)

with tf.Session() as sess:
    output = sess.run(Str, feed_dict={Str: 'Hello World !'})
    print(output)
Hello World !

2.字符串拼接

Str1 = tf.placeholder(tf.string)
Str2 = tf.placeholder(tf.string)
Str3 = tf.placeholder(tf.string)

Str = tf.string_join([Str1, Str2, Str3], separator=" ") 

with tf.Session() as sess:
    output = sess.run(Str, feed_dict={Str1: 'I', Str2: 'like', Str3: 'TensorFlow !'})
    print(output.decode())
I like TensorFlow !

3.浮點數乘積

Num1 = tf.placeholder(tf.float32)
Num2 = tf.placeholder(tf.float32)

Result = tf.multiply(Num1, Num2)

with tf.Session() as sess:
    print(sess.run(Result, feed_dict={Num1:[5.],Num2:[6.]}))
[ 30.]

4.不用占位符,而用常量,也可完成。

只是驗證一下,不推薦使用。初始化時的常量值將會被覆蓋。

Num1 = tf.constant(1.0)
Num2 = tf.constant(2.0)

Result = tf.multiply(Num1, Num2)

with tf.Session() as sess:
    print (sess.run(Result, feed_dict = {Num1: 5., Num2: 6.}))
30.0

5.矩陣乘法

順道學點新東西

定義兩個矩陣,分別為 2*3 和 3*2矩陣,完成乘法運算

Matrix1 = tf.Variable(tf.random_normal([2,3]))  
Matrix2 = tf.Variable(tf.truncated_normal([3,2]))  

Result = tf.matmul(Matrix1,Matrix2)  

with tf.Session() as sess:  
    sess.run(tf.global_variables_initializer()) 
    print ('Matrix1:')
    print (sess.run(Matrix1)) 
    print ('Matrix2:')
    print (sess.run(Matrix2)) 
    print ('Result:')
    print (sess.run(Result)) 
Matrix1:
[[-1.00879586  0.61892986 -0.39552122]
 [-0.83463311 -0.54309726 -0.31309164]]
Matrix2:
[[ 1.35596943  0.67712855]
 [-0.09836598 -0.41533285]
 [ 0.20601694 -0.14825489]]
Result:
[[-1.51026201 -0.88150841]
 [-1.14281678 -0.29317039]]

使用 feed_dict完成矩陣乘法

表達看上去更繁瑣。。。對比一下是為了更好地理解feed_dict。。。

Matrix1_Value = tf.random_normal([2,3])
Matrix2_Value = tf.truncated_normal([3,2])

Matrix1 = tf.placeholder(dtype=tf.float32,shape=[2,3]) 
Matrix2 = tf.placeholder(dtype=tf.float32,shape=[3,2])   

Result = tf.matmul(Matrix1,Matrix2)  

with tf.Session() as sess:  
    sess.run(tf.global_variables_initializer()) 
    print ('Matrix1:')
    print (sess.run(Matrix1_Value)) 
    print ('Matrix2:')
    print (sess.run(Matrix2_Value)) 
    print ('Result:')
    print (sess.run(Result,feed_dict={Matrix1:sess.run(Matrix1_Value),Matrix2:sess.run(Matrix2_Value)}))  
Matrix1:
[[-0.6228959   0.04135797 -0.76592982]
 [ 0.04814498 -0.98519218 -0.88335162]]
Matrix2:
[[-0.73028505  0.62314421]
 [-0.64763296 -0.18691106]
 [ 0.0198773   0.68467569]]
Result:
[[-1.66321826 -2.89716744]
 [ 1.28906226  2.08242035]]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM