Tensorflow:用tf替换/输入图的占位符。变量?

tha*_*ang 5 placeholder tensorflow

我有一个模型,M1其数据输入是一个占位符M1.input,其权重得到了训练。我的目标是要建立一个新的模式M2,其计算输出oM1从输入(其训练的权重)w的形式tf.Variable(而不是喂养实际值M1.input)。换句话说,我将训练后的模型M1用作黑盒函数来构建新模型o = M1(w)(在我的新模型中,w需要学习,并且其权重M1固定为常量)。问题在于,M1仅接受M1.input需要输入实际值的输入作为输入,而不接受tf.Variable这样的输入w

作为一个天真的解决方案来构建M2,我可以手动生成M1M2然后初始化M1与预受训值的权重,使他们不内可训练M2。但是,在实践中,这M1很复杂,我不想在中手动M1重新构建M2。我要寻找一个更好的解决方案,像一个解决方法或直接的解决方案,以取代输入占位符的东西M1.inputM1有tf.Variable w

感谢您的时间。

Pat*_*wie 2

这个有可能。关于什么:

import tensorflow as tf


def M1(input, reuse=False):
    with tf.variable_scope('model_1', reuse=reuse):
        param = tf.get_variable('param', [1])
        o = input + param
        return o


w = tf.get_variable('some_w', [1])
plhdr = tf.placeholder_with_default(w, [1])

output_m1 = M1(plhdr)

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    sess.run(w.assign([42]))

    print(sess.run(output_m1, {plhdr: [0]}))  # direct from placeholder
    print(sess.run(output_m1))                # direct from variable
Run Code Online (Sandbox Code Playgroud)

因此,当 feed_dict 具有占位符值时,将使用该值。否则,使用变量“w”的后备选项将处于活动状态。