1. 程式人生 > >玩玩機器學習3——TensorFlow基礎之Session基本運算、佔位符和變數的使用

玩玩機器學習3——TensorFlow基礎之Session基本運算、佔位符和變數的使用

通過TensorFlow的矩陣和常量的"加減乘除"運算,講一下Session、變數以及佔位符的使用

目錄

變數的使用

Session建立會話與運算

#session的使用,介紹兩種啟動Session的方式,進行矩陣乘法運算
import tensorflow as tf #引入TensorFlow庫

m1 = tf.constant([[2,2],[3,4]])#定義一個一行兩列的矩陣常量
m2 = tf.constant([[3,4],[3,1]])#定義一個兩行一列的矩陣常量
dot_operation = tf.matmul(m1, m2)#定義m1和m2的TensorFlow矩陣乘法

# 使用會話的方法1
sess = tf.Session()#定義會話
result = sess.run(dot_operation)#執行會話乘法
print(result)#列印矩陣相乘的結果
sess.close()#關閉會話

# 使用會話的方法2,會話簡化達到相同效果
with tf.Session() as sess:
    result_ = sess.run(dot_operation)
    print(result_)

輸出結果:

[[12 10]  [21 16]]

變數的使用

#變數的使用
var = tf.Variable(0)#定義一個常量var,數值為0

add_operation = tf.add(var, 1)#定義一個常量加法運算,var數值加1
update_operation = tf.assign(var, add_operation)#將加法運算

with tf.Session() as sess:#開啟會話
    sess.run(tf.global_variables_initializer())#變數本地初始化
    for _ in range(3):#運算迴圈3次
        sess.run(update_operation)#執行加法運算
        print(sess.run(var))#輸出每次的運算結果

輸出結果:

1 2 3  

佔位符的使用

#佔位符的使用
x1 = tf.placeholder(dtype=tf.float32, shape=None)#用佔位符定義常量x1
y1 = tf.placeholder(dtype=tf.float32, shape=None)#用佔位符定義常量y1
z1 = x1 + y1#定義z2為x1和y1相加的結果

x2 = tf.placeholder(dtype=tf.float32, shape=[2, 1])#用佔位符定義2行1列矩陣x2
y2 = tf.placeholder(dtype=tf.float32, shape=[1, 2])#用佔位符定義1行2列矩陣y2
z2 = tf.matmul(x2, y2)#定義z2為x2和y2矩陣相乘的結果

with tf.Session() as sess:
    #將常量放入佔位符
    z1_value = sess.run(z1, feed_dict={x1: 1, y1: 2})

    # 將矩陣放入佔位符
    z2_value = sess.run([z2],feed_dict={x2: [[2], [2]], y2: [[3, 3]]})
    print(z1_value)
    print(z2_value)

輸出結果:

3.0 [array([[6., 6.],        [6., 6.]], dtype=float32)]