TensorFlow学习笔记(三)-- feed_dict 使用
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.矩阵乘法
顺道学点新东西
- tf.random_normal 从正态分布中输出随机值
- tf.truncated_normal 从截断的正态分布中输出随机值
定义两个矩阵,分别为 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]]


浙公网安备 33010602011771号