tensorflow常用数据函数总结(tf.tile()、tf.expand_dims())

tf.tile()

tensorflow中的tile()函数是用来对张量(Tensor)进行扩展的,其特点是对当前张量内的数据进行一定规则的复制。最终的输出张量维度不变。也就是说tile可以某一维度的tensor复制n份。(下面举几个例子)

x = tf.Variable([1, 2, 3])   # shape = (3,)
y = tf.Variable([[2, 2, 2], [1, 1, 1]])  # shape = (2,3)
z = tf.Variable([[[2, 2, 2]]]) # shape = (1,1,3)

# 在第一dim复制3次
x_1 = tf.tile(x, multiples=[3])  # shape=(9,)
# 在第一dim复制6次,第二dim复制2次
y_1 = tf.tile(y, multiples=[3, 2])  # shape=(6,6)
# 仅在第二dim复制4次
z_1 = tf.tile(z, multiples=[1, 4, 1]) # shape=(1,4,3)

从上面不难看出,tf.tile()还是非常灵活,最主要是要确定multiples这个列表的长度,如果tensor有几维那么multiples长度该为几,multiples[i]对应tensor第i维应该应该复制多少倍。

tf.expand_dims()

tf.expand_dims()是用来增加tensor的维度,拿官方给出的参考文档来说

# 't' is a tensor of shape [2] 
tf.shape(tf.expand_dims(t, 0))  # [1, 2]
tf.shape(tf.expand_dims(t, 1))  # [2, 1]
tf.shape(tf.expand_dims(t, -1))  # [2, 1]

# 't2' is a tensor of shape [2, 3, 5]
tf.shape(tf.expand_dims(t2, 0))  # [1, 2, 3, 5]
tf.shape(tf.expand_dims(t2, 2))  # [2, 3, 1, 5]
tf.shape(tf.expand_dims(t2, 3))  # [2, 3, 5, 1]

t代表具体tensor,后面一个参数表示要在当前的哪一个dim位置添加一维tensor.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值