提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
按照此处[ https://www.tensorflow.org/extend/adding_an_op]的示例,我创建了自己的运算符,我们将其MyConv
。
现在,如果我做这样的事情:
# placeholders for inputs and labels
input = tf.placeholder(...)
label = tf.placeholder(...)
# MyConv operator on inputs... returns 1D tensor
conv_out = my_module.my_conv(input, ...)
# final classifier
output = tf.layers.dense(inputs=conv_out, units=10)
# eveything we need for backprop
probs = tf.losses.sparse_softmax_cross_entropy(logits=output, labels=label)
loss = tf.reduce_mean(probs)
adam_opt = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = adam_opt.minimize(loss)
并使用简单的输入转发将模型运行N-1次,而使用反向传递仅运行N次:
num_of_chunks = 100
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for c in range(num_of_chunks):
single_input = np.array(...)
# for num_of_chunks-1 times, just push the single_input through the network
if c != num_of_chunks - 1:
result = sess.run([output], feed_dict={input:single_input})
# only the last time, do the backprop and run the optimizer
else:
result, loss_out, train_out = sess.run([output, loss, train_op], feed_dict={input:single_input, label:np.array(...)})
有趣的事情发生了。 TF sess.run()
方法将实例化MyConv
类的一个对象并使用num_of_chunks-1
次,但最后一次(当它执行此else
路径时)将创建类MyConv
的新对象并使用该新对象( MyConv()构造函数已被调用一次)。 看起来就像是因为我在else
路径中引入了sess.run()
, sess.run()
创建了MyConv
运算符的新对象,而这并不是我所期望的行为(我将某些信息存储为私有类成员,并且我真的MyConv
在运行会话时保留一个MyConv
对象)。
因此,问题是:您是否知道sess.run()方法为什么会因为我从“仅向前模式”切换到“正向和反向传播模式”而创建了运算符的新对象?
还有,一个音符。 如果删除此if-else
语句并让每个块都执行MyConv
,那么一切都很好,仅实例化和使用MyConv
一个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.