【问题标题】:How to form multiple layers tensor in Tensorflow如何在 Tensorflow 中形成多层张量
【发布时间】:2019-02-27 02:58:50
【问题描述】:

在张量流中,我有一个形状为 [2,3,3,1] 的张量,现在我想将张量复制到多层到形状为 [2,3,3,3] 的张量,我该怎么做这样做?

【问题讨论】:

标签: python tensorflow


【解决方案1】:

您可以通过tf.tiletf.concat 实现此目的:

t = tf.random_uniform([2, 3, 3, 1], 0, 1)
s1 = tf.tile(t, [1, 1, 1, 3])
s2 = tf.concat([t]*3, axis=-1)

with tf.Session() as sess:
    tnp, s1np, s2np = sess.run([t, s1, s2])
    print(tnp.shape)
    print(s1np.shape)
    print(s2np.shape)

打印出来的

(2, 3, 3, 1)
(2, 3, 3, 3)
(2, 3, 3, 3)

为了说明发生了什么,看一个二维示例可能更容易:

import tensorflow as tf

t = tf.random_uniform([2, 1], 0, 1)
s1 = tf.tile(t, [1, 3])
s2 = tf.concat([t]*3, axis=-1)

with tf.Session() as sess:
    tnp, s1np, s2np = sess.run([t, s1, s2])
    print(tnp)
    print(s1np)
    print(s2np)

打印出来的

[[0.52104855]
 [0.95304275]]
[[0.52104855 0.52104855 0.52104855]
 [0.95304275 0.95304275 0.95304275]]
[[0.52104855 0.52104855 0.52104855]
 [0.95304275 0.95304275 0.95304275]]

【讨论】:

    【解决方案2】:

    如果您想要由相同初始化程序生成的每个副本的值(但不需要完全相同的值),这是另一种解决方案。

    import tensorflow as tf
    tf.reset_default_graph()
    init_shape = [2, 3, 3, 1]
    n_times = 2
    var1 = tf.Variable(tf.random_normal(shape=init_shape))
    vars_ = [tf.contrib.copy_graph.copy_variable_to_graph(var1, var1.graph)
             for _ in range(n_times)] + [var1]
    
    result = tf.reshape(tf.concat(vars_, axis=3),
                        shape=init_shape[:-1] + [len(vars_)])
    print(result.get_shape().as_list())
    # [2, 3, 3, 3]
    

    使用tf.contrib.copy_graph 复制变量,然后像上一个答案一样将它们连接起来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-05
      • 2020-05-03
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2020-12-19
      相关资源
      最近更新 更多