关行tf的一些API

1. tf.tile() 和 tf.contrib.seq2seq.tile_batch()

import tensorflow as tf

# 将input的某一维度复制多少次, len(input.shape()) 等于 len(multiples)
# tf.tile(input, multiples, name=None)
t = tf.constant([[1, 1, 1, 9], [2, 2, 2, 9], [7, 7, 7, 9]])
# 第一维度和第二维度都保持不变
z0 = tf.tile(t, multiples=[1, 1])
# 第1维度不变, 第二维度复制为2份
z1 = tf.tile(t, multiples=[1, 2])
# 第1维度复制为两份, 第二维度不变
z2 = tf.tile(t, multiples=[2, 1])
# tf.contrib.seq2seq.tile_batch(encoder_outputs, multiplier=self.beam_size)
encoder_outputs = tf.constant([[[1, 3, 1], [2, 3, 2]], [[2, 3, 4], [2, 3, 2]]])
print(encoder_outputs.get_shape())  # (2, 2, 3)
# 将batch内的每个样本复制3次, tile_batch() 的第2个参数是一个 int 类型数据
z4 = tf.contrib.seq2seq.tile_batch(encoder_outputs, multiplier=3)

with tf.Session() as sess:
    print('z0:\n', sess.run(z0))
    print('z1:\n', sess.run(z1))
    print('z2:\n', sess.run(z2))
    print('z4:\n', sess.run(z4))

运行结果:
(2, 2, 3)
z0:
[[1 1 1 9]
[2 2 2 9]
[7 7 7 9]]
z1:
[[1 1 1 9 1 1 1 9]
[2 2 2 9 2 2 2 9]
[7 7 7 9 7 7 7 9]]
z2:
[[1 1 1 9]
[2 2 2 9]
[7 7 7 9]
[1 1 1 9]
[2 2 2 9]
[7 7 7 9]]
z4:
[[[1 3 1]
[2 3 2]]

[[1 3 1]
[2 3 2]]

[[1 3 1]
[2 3 2]]

[[2 3 4]
[2 3 2]]

[[2 3 4]
[2 3 2]]

[[2 3 4]
[2 3 2]]]

2. tf.reduce_sum/tf.reduce_mean/tf.reduce_max

import tensorflow as tf

x = tf.constant([[1, 1, 1], [2, 2, 2]])
with tf.Session() as sess:
    print(sess.run(tf.reduce_sum(x)))  # 所有求和
    print(sess.run(tf.reduce_sum(x, 0)))  # 按 列 求和
    print(sess.run(tf.reduce_sum(x, 1)))  # 按 行 求和
    print(sess.run(tf.reduce_sum(x, [0, 1])))  # 行列求和
    print(sess.run(tf.reduce_sum(x, reduction_indices=[1])))

x = tf.constant([[1, 2], [3, 4]])
with tf.Session() as sess:
    print(sess.run(tf.reduce_mean(x)))  # 所有求平均
    print(sess.run(tf.reduce_mean(x, 0)))  # 按 列 求和
    print(sess.run(tf.reduce_mean(x, 1)))  # 按行求平均
    print(sess.run(tf.reduce_max(x)))
    print(sess.run(tf.reduce_max(x, 0)))
    print(sess.run(tf.reduce_max(x, 1)))

运行结果:
9
[3 6]
2
[2 3]
[1 3]
4
[3 4]
[2 4]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值