- 该系列是笔者在Tensorflow编程学习过程中记录的笔记,仅供参考。
- 所有涉及的代码都来自课堂学习纯手打记录。
Test1 常量、变量、Fetch、Feed、Session
在tensorflow中,常量通过constant函数来定义。
在tensorflow中,变量通过Variable函数来定义,注意:只要用到变量,就一定要run一下initialize_all_variables()来初始化变量。
Session在tensorflow中就像指针一样,指向需要运行的代码。
Session运行结束后,需要关闭。
Fetch对多个操作节点取值。
Feed给占位符赋值。
import tensorflow as tf
a = tf.constant(3.0) #定义常量(赋值)
b = tf.Variable(1.0) #定义变量(赋值)
c = tf.placeholder(tf.float32) #定义占位符(位数)
d1 = tf.add(a,b) #a+b
d2 = tf.sub(a,b) #a-bb
d3 = tf.mul(a,b) #a*b
d4 = tf.div(a,b) #a/b
e1 = tf.mod(a,b) #a%b
e2 = tf.abs(c) #|c|
e3 = tf.sqrt(c) #平方根
e4 = tf.pow(a,b) #a^b
f1 = tf.maximum(a,b)
f2 = tf.minimum(a,b)
m1 = tf.constant([[3,3]])
m2 = tf.constant([[2],[3]])
g = tf.matmul(m1,m2) #矩阵乘法[2*3+3*3]=[15]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) #变量初始化
result = sess.run([d1,d2,d3,d4,e1,e4,f1,f2,g]) #Fetch
print(result)
print (sess.run(e2, feed_dict={c: -3})) #Feed
print (sess.run(e3, feed_dict={c: 4}))
print(g)