在TensorFlow中定义常数
import tensorflow as tf
a = tf.constant(1)
b = tf.constant(2)
sess = tf.Session()
sess.run(a)
sess.run(b)
进行算数运算:
with tf.Session() as sess:
print("Addition matrix: %i" % sess.run(a + b))
print("Multiplication matrix: %i" % sess.run(a * b))
定义函数
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}))
矩阵乘法
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.], [2.]])
mul = tf.matmul(matrix1, matrix2)
sess = tf.Session()
print(sess.run(mul))
可以看到上面的操作大多都需要 tf.Session(),显得有些累赘,此时可以利用Eager API简化操作
from __feature__ import absolute_import, division, print_function
import tensorflow as tf
import numpy as np
print("Setting Edge model...")
tf.enable_edger_execution()
tf.contrib.eager
print("Define constant eager")
a = tf.constant(2)
print("a = %i" % a)
b = tf.constant(3)
print("b = %i" % b)
print("Running operations, without tf.Session")
c = a + b
print("a + b = % i" % c)
d = a * b
print("a * b = % i" % d)
print("Mixing operations with tensors and numpy arrays")
a = tf.constant([[2., 1.], [1., 0.]], dtype = tf.float32)
print("Tensor: \n a = %s" % a)
b = np.array([[3., 0.], [5., 1.]], dtype = np.float32)
print("NumpyArray: \b b = %s" % b)
print("Running operations, without tf.Session")
c = a + b
print("a + b = %s" % c)
d = a * b
print("a * b = %s" % d)
print("Iterate through Tensor 'a' :")
for i in range (a.shape[0]):
for j in range(a.shape[1]):
print(a[i][j])