我想要做的是为我的神经网络增加一个权重矩阵,它的大小会增加(即每次迭代都会添加一个神经元)。但是,我不想再次使用tf.Variable
,因为这会通过复制上一个矩阵中的值而不是扩展矩阵本身而浪费内存。如何放大张量流中的矩阵而不重复值?
我已经看到人们使用tf.assign与validate_shape设置为False,但是,这并没有改变正确的变量的形状,我认为这是一个错误,但张量流GitHub似乎并不同意(我不'不知道为什么从他们的reply)。
下面是该问题的简单示例。 x是我想要扩展的矩阵,以便它可以添加到z中。如果有人知道什么,我想在这里实现我会很感激的解决方案=)
import tensorflow as tf
import numpy as np
# Initialise some variables
sess = tf.Session()
x = tf.Variable(tf.truncated_normal([2, 4], stddev = 0.04))
z = tf.Variable(tf.truncated_normal([3, 4], stddev = 0.04))
sess.run(tf.variables_initializer([x, z]))
# Enlarge the matrix by assigning it a new set of values
sess.run(tf.assign(x, tf.concat((x, tf.cast(tf.truncated_normal([1, 4], stddev = 0.04), tf.float32)), 0), validate_shape=False))
# Print shapes of matrices, notice that x's actual shape is different for the
# shape tensorflow has recorded for it
print(x.get_shape())
print(x.eval(session=sess).shape)
print(z.get_shape())
print(z.eval(session=sess).shape)
# Add two matrices with equal shapes
print(tf.add(x, z).eval(session=sess))
注:我意识到,如果我初始化Z到形状(2,4 ),然后用tf.assign扩展它(就像我用x做的那样),上面的例子就可以工作。但由于另一个约束,我无法控制z的原始形状。