tensorflow中常用的计算操作

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

axis维度描述

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]]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章