栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

tensorflow 2.x Broadcasting

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

tensorflow 2.x Broadcasting

Broadcasting

本质上

是一个张量的维度的扩张手段,它是指对某一个维度上面重复N多次,但是却没有真正的复制数据,但是却呈现出数据被扩张了。

机制:

  • expand
  • without copying data
    • VS tf.tile
  • tf.broadcast_to

举例:

Feature maps: [4, 32, 32, 3]
▪ Bias: [3] → [1, 1, 1, 32] → [4, 32, 32, 3]

如何理解??

When it has no axis 如果没有这一个维度
▪ Create a new concept 创建一个新的概念
▪ [classes, students, scores] + [scores]

When it has dim of size 1 当存在dim=1的维度**
▪ Treat it shared by all 1的维度是对每一个维度适用的
▪ [classes, students, scores] + [students, 1]

为什么要做boardcasting?

  1. 实际上存在这种需求
    ▪ [classes, students, scores]
    ▪ 给所有学生加 5 分
    ▪ [4, 32, 8] + [4, 32, 8]
    ▪ [4, 32, 8] + [5.0]

  2. 减少内存空间
    ▪ [4, 32, 8] → 1024
    ▪ bias=[8]: [5.0,5.0,5.0,…] → 8

是否能够broadcast?

▪ 如果当前 dim=1, 扩张
▪ 如果相应位置上没有维度, 插入一个维度(shape 是 1),扩张成相同的维度
▪ 否则不能扩张

例如:

[4, 32, 14, 14]
[1, 32, 1, 1] → [4, 32, 14, 14]
可以扩张,[1, 32, 1, 1]可以扩张为[4, 32, 14, 14],因为维度相等,且需要扩张的地方都是1,可以扩张

[4, 32, 14, 14]
[14, 14] → [1, 1, 14, 14] → [4, 32, 14, 14]
可以扩张,[14, 14]可以扩张为[4, 32, 14, 14],因为维度不等,先给相应位置上添加维度,再扩张


▪ [4, 32, 14, 14]
▪ [2, 32, 14, 14]
不能扩张。因为维度相等,相应位置上都有维度,且不是1,

实操
import tensorflow as tf

x = tf.random.normal([4,32,32,3])
print("初始维度:",x.shape)
print("x + tf.random.normal([3]) :",(x + tf.random.normal([3])).shape)
print("x + tf.random.normal([32,32,1]): ",(x + tf.random.normal([32,32,1])).shape)
#print("x+tf.random.normal([1,4,1,1]): ",(x+tf.random.normal([1,4,1,1])))
#报错:InvalidArgumentError: Incompatible shapes: [4,32,32,3] vs. [1,4,1,1] [Op:AddV2]
#因为都是四维,axis=1的维度对应的数字为4,无法扩张为32
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/269708.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号