如何在Tensorflow中形成多层张量

时间:2019-02-27 02:58:51

标签: python tensorflow

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

2 个答案:

答案 0 :(得分: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)

为说明会发生什么,看2d示例可能会更容易:

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]]

答案 1 :(得分:0)

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

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复制变量,然后像前面的答案一样将它们连接起来。