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/