標籤:建立 返回 傳回值 變數 feed 乘法 常量 hub text
tensorflow常數操作
import tensorflow as tf# 定義兩個常數,a和ba = 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.]])# 定義矩陣乘法運算multiplicationproduct = tf.matmul(matrix1, matrix2)# 啟動預設圖進行運算with tf.Session() as sess: result = sess.run(product) print(result)
結果
[[12.]]
簡單例子
import tensorflow as tfhello = 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-基本操作運算