Tensorflow2.0笔记 - Broadcasting和Tile

本文介绍了TensorFlow中的广播机制,展示了如何使用broadcast_to、tile和expand_dims等方法扩展张量维度进行运算,以及在处理不同形状张量时的注意事项。
摘要由CSDN通过智能技术生成

        关于broadcasting的介绍,参考这篇文章。

        https://blog.csdn.net/python_LC_nohtyp/article/details/104097417

import tensorflow as tf
import numpy as np

tf.__version__

#关于broadcasting的介绍,参考这篇文章
#https://blog.csdn.net/python_LC_nohtyp/article/details/104097417

tensor = tf.random.normal([4,32,32,3])
#tensor + [3],[3]可以扩展为[4,32,32,3]后相加
t = tensor + tf.random.normal([3])
print("=========tensor + [3]=======", t.shape)
#tensor +[32,32,1],可以扩展为[4,32,32,3]后相加
t = tensor + tf.random.normal([32,32,1])
print("=========tensor + [32,32,1]=======", t.shape)
#tensor + [4,1,1,1],可以扩展为[4,32,32,3]后相加
t = tensor + tf.random.normal([4,1,1,1])
print("=========tensor + [4,1,1,1]=======", t.shape)
#不使用运算符,使用broadcast_to来扩展维度
b = tf.broadcast_to(tf.random.normal([4,1,1,1]), [4,32,32,3])
print("=========tf.broadcast_to([4,1,1,1], [4,32,32,3])========", b.shape)
#tensor + [1,4,1,1],第二维度不是1,也不是32,无法相加,报错
#t = tensor + tf.random.normal([1,4,1,1])
#print("=========tensor + [1,4,1,1]=======", t.shape)
#InvalidArgumentError: {{function_node __wrapped__AddV2_device_/job:localhost/replica:0/task:0/device:CPU:0}} 
#Incompatible shapes: [4,32,32,3] vs. [1,4,1,1] [Op:AddV2] name: 

#使用tile方式进行复制扩展,tile方式会实际分配内存
tensor = tf.random.uniform([3,4], minval=0, maxval=10, dtype=tf.int32)
print("=========Original tensor======\n", tensor)

#使用broadcasting复制扩展,不会分配内存,但实际效果和tile一样
b = tf.broadcast_to(tensor, [2,3,4])
print("==========Broadcasting========\n", b)

#使用expand_dims扩展一个维度
t = tf.expand_dims(tensor, axis=0)
print("==========After expand_dims:", t.shape)
#使用tile复制第一个维度,参数[2,1,1]表示第一个维度复制两次,后两个维度复制1次(不动)
t1 = tf.tile(t, [2,1,1])
print("After tile:", t1.shape)
print(t1)

        运行结果

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亦枫Leonlew

希望这篇文章能帮到你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值