tf.reshape函数用法&理解

作者: 七八音 | 来源:发表于2020-05-20 16:27 被阅读0次

    函数原型

    函数接口:

    <pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n4" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); --select-text-bg-color: #36284e; --select-text-font-color: #fff; font-size: 0.9rem; line-height: 1.71429em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(218, 218, 218); position: relative !important; margin-bottom: 3em; margin-left: 2em; padding-left: 1ch; padding-right: 1ch; width: inherit; color: rgb(31, 9, 9); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">tf.reshape(
    tensor, shape, name=None
    )</pre>

    参数
    tensor Tensor张量
    shape Tensor张量,用于定义输出张量的shape,组成元素类型为 int32int64.
    name 可选参数,用于定义操作名称.
    返回
    A Tensor. 输出张量和输入张量的元素类型相同。

    用法

    tf.reshape函数用于对输入tensor进行维度调整,但是这种调整方式并不会修改内部元素的数量以及元素之间的顺序,换句话说,reshape函数不能实现类似于矩阵转置的操作。比如,对于矩阵[[1,2,3],[4,5,6]],如果使用reshape,将维度变为[3,2], 其输出结果为:[[1,2],[3,4],[5,6]], 元素之间的顺序并没有改变:1之后还是2,如果是矩阵转置操作,1之后应该为4。

    其内部实现可以理解为: tf.reshape(a, shape) -> tf.reshape(a, [-1]) -> tf.reshape(a, shape)

    现将输入tensor,flatten铺平,然后再进行维度调整(元素的顺序没有变化

    tf.reshape不会更改张量中元素的顺序或总数,因此可以重用基础数据缓冲区。这使得它快速运行,而与要运行的张量有多大无关。

    如果需要修改张量的维度来实现对元素重新排序,需要使用tf.transpose

    image-20200517190147962

    总结

    关于tf.reshape函数我们需要知道的是:

    1. 函数用于张量维度调整,但是不会修改内部元素的数量以及相对顺序

    2. shape中-1表示这个维度的大小,程序运行时会自动计算填充(因为变换前后元素数量不变,我们可以根据其他维度的大小,最终确定-1这个位置应该表示的数字

    3. 如果需要通过修改内部元素的存储顺序以实现维度调整,需要使用tf.transpose函数


    关注公众号,一起学习成长

    相关文章

      网友评论

        本文标题:tf.reshape函数用法&理解

        本文链接:https://www.haomeiwen.com/subject/fysnohtx.html