機器學習系列-tensorflow-02-基本操作運算
阿新 • • 發佈:2018-10-31
ply 運行 class 結果 -s 構造器 weight eight ali
a=2, b=3
Addition with constants: 5
Multiplication with constants: 6
tensorflow常數操作
import tensorflow as tf
# 定義兩個常數,a和b
a = tf.constant(2)
b = tf.constant(3)
# 執行默認圖運算
with tf.Session() as sess:
print("a=2, b=3")
print("Addition with constants: %i" % sess.run(a+b))
print("Multiplication with constants: %i" % sess.run(a*b))
結果
a=2, b=3
Addition with constants: 5
Multiplication with constants: 6
tensorflow變量操作
變量作為圖形輸入,構造器的返回值作為變量的輸出,在運行會話時,傳入變量的值,在進行運算。
import tensorflow as tf # 定義兩個變量 a = tf.placeholder(tf.int16) b = tf.placeholder(tf.int16) # 定義加法和乘法運算 add = tf.add(a, b) mul = tf.multiply(a, b) # 啟動默認圖進行運算 with tf.Session() as sess: # 傳入變量值,進行運算 print("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3})) print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))
結果
Addition with variables: 5
Multiplication with variables: 6
tensorflow矩陣常量操作
import tensorflow as tf # 創建一個1X2的常數矩陣 matrix1 = tf.constant([[3., 3.]]) # 創建一個2X1的常數矩陣 matrix2 = tf.constant([[2.],[2.]]) # 定義矩陣乘法運算multiplication product = tf.matmul(matrix1, matrix2) # 啟動默認圖進行運算 with tf.Session() as sess: result = sess.run(product) print(result)
結果
[[12.]]
簡單例子
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
結果
b‘Hello, TensorFlow!‘
參考:
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
機器學習系列-tensorflow-02-基本操作運算