gpt4 book ai didi

Tensorflow:用 tf.Variable 替换/提供图形的占位符?

转载 作者:行者123 更新时间:2023-12-04 21:04:19 25 4
gpt4 key购买 nike

我有一个型号M1其数据输入为占位符M1.input并且训练了其权重。
我的目标是建立一个新模型M2计算输出 oM1 (带有经过训练的权重)来自输入 w形式为 tf.Variable (而不是将实际值提供给 M1.input )。换句话说,我使用训练好的模型 M1作为构建新模型的黑盒函数o = M1(w) (在我的新模型中,w 是要学习的,M1 的权重是固定的)。问题是 M1仅接受作为其输入 M1.input我们需要通过它提供实际值,而不是像 w 这样的 tf.Variable .

作为构建 M2 的幼稚解决方案,我可以手动构建M1M2 内然后初始化M1的权重与预训练值并保持它们在 M2 内不可训​​练.然而,在实践中,M1很复杂,我不想手动构建M1再次在 M2 内.我正在寻找更优雅的解决方案,例如替代输入占位符 M1.input 的解决方法或直接解决方案的 M1使用 tf.Variable w .

感谢您的时间。

最佳答案

这个有可能。关于什么:

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

所以当 feed_dict 有占位符的值时,就会使用这个值。否则,使用变量“w”的后备选项处于事件状态。

关于Tensorflow:用 tf.Variable 替换/提供图形的占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com