Tensorflow:使变量trainab

2024-06-08 16:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想优化一个变量(负二项分布的参数),用一些最大矩估计量预先初始化:

sample_data = tf.placeholder(tf.float32)
(r, p) = fit_mme(sample_data) # pre-calculation

# The important part: make `r` trainable
r = tf.Variable(r, dtype=tf.float32, name="r")



#####################################################
# to clarify: from here training of `r`

mu = tf.reduce_mean(sample_data, axis=0, name="mu")
p = mu / (r + mu)
p = tf.identity(p, "p")

distribution = tf.contrib.distributions.NegativeBinomial(total_count=r,
                                    probs=p,
                                    name="nb-dist")
probs = distribution.log_prob(sample_data)
# minimize negative log probability
loss = -tf.reduce_sum(probs, name="loss")

train_op = tf.train.AdamOptimizer(learning_rate=0.05)
train_op = train_op.minimize(loss, global_step=tf.train.get_global_step())

errors = []
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(10000):
        (probs_res, loss_res, _) = \
            sess.run((probs, loss, train_op), feed_dict={sample_data: x})
        errors.append(loss_res)
        print(i)

    r_estim = probs_res.total_count

适合: 在

^{pr2}$

但是,我得到了以下错误:

ValueError: initial_value must have a shape specified: Tensor("MME/r:0", dtype=float32)

是否有更好/更干净的解决方案使r可培训?


Tags: samplenamereducedatatftrainresglobal
2条回答

很多事情我不清楚。在

为什么要“打破”图表:

sample_data = tf.placeholder(tf.float32)
r, p = fit_mme(sample_data) # pre-calculation

# The important part: make `r` trainable
r_var = tf.Variable(r, dtype=tf.float32, name="r")

r已经是一个可以更新的张量,因此不需要将它的值输入变量。尤其是如果你不想对它进行任何色情处理。在

但是,如果你真的想这样做,你可以这样做:

^{pr2}$

检查r的形状。它应该有明确的定义。在

我怀疑你有一个*/没有/?对于第一个维度,允许您使用不同大小的批次。在

要么用tf.reshape修复形状,要么用tf.reduce_mean或类似的方法折叠第一个维度。在

相关问题 更多 >