1、tf.reduce_sum
從tensor的維度上面計算元素之和
tf.reduce_sum(
input_tensor, # 輸入
axis=None, # 表示在哪個維度進行sum操作。
keepdims=None, # 表示是否保留原始數據的維度,False相當於執行完後原始數據就會少一個維度。
name=None,
reduction_indices=None,
keep_dims=None
)
import tensorflow as tf
x = tf.constant([[1, 1, 1],
[1, 1, 1]])
a = tf.reduce_sum(x) # 修改這裏
b = tf.reduce_sum(x, axis=0)
c = tf.reduce_sum(x, axis=1)
d = tf.reduce_sum(x, keep_dims=True)
e = tf.reduce_sum(x, keep_dims=False)
f = tf.reduce_sum(x, axis=[0, 1])
tensors = [a, b, c, d, e, f]
with tf.Session() as sess:
for tensor in tensors:
y = sess.run(tensor)
print(y)
# 6
# [2 2 2]
# [3 3]
# [[6]]
# 6
# 6
2、tf.multiply
數乘
tf.multiply(
x,
y,
name=None # A name for the operation (optional).
)
import tensorflow as tf
a = tf.constant([[1, 2],
[3, 4]])
b = tf.constant([[1, 3],
[2, 1]])
y = tf.multiply(a, b)
with tf.Session() as sess:
res = sess.run(y)
print(res)
# [[1 6]
# [6 4]]
import tensorflow as tf
x = tf.constant([[1.0, 2.0],
[3.0, 4.0]])
a = 0.5 * x
b = tf.multiply(0.5, x)
tensors = [a, b]
with tf.Session() as sess:
for tensor in tensors:
y = sess.run(tensor)
print(y)
# [[0.5 1. ]
# [1.5 2. ]]
# [[0.5 1. ]
# [1.5 2. ]]
3、tf.matmul
矩陣點乘
tf.matmul(
a,
b,
transpose_a=False,
transpose_b=False,
adjoint_a=False,
adjoint_b=False,
a_is_sparse=False,
b_is_sparse=False,
name=None
)
import tensorflow as tf
a = tf.constant([[1, 2],
[3, 4]])
b = tf.constant([[1, 3],
[2, 1]])
y = tf.matmul(a, b)
with tf.Session() as sess:
res = sess.run(y)
print(res)
# [[ 5 5]
# [11 13]]
3、tf.add
import tensorflow as tf
x = tf.constant([[1, 2],
[3, 4]])
a = 1 + x
b = tf.add(1, x)
tensors = [a, b]
with tf.Session() as sess:
for tensor in tensors:
y = sess.run(tensor)
print(y)
# [[2 3]
# [4 5]]
# [[2 3]
# [4 5]]