Tensorflow 概率逻辑回归示例

Tensorflow Probability Logistic Regression Example

我觉得我一定遗漏了一些明显的东西,在努力对张量流概率中的逻辑回归进行正控制时。

我修改了逻辑回归示例 here,并创建了阳性对照特征和标签数据。我很难达到 60% 以上的准确率,但是对于 'vanilla' Keras 模型(准确率 100%)来说这是一个简单的问题。我错过了什么?我尝试了不同的层、激活等。使用这种设置模型的方法,实际上是否在执行后验更新?我需要指定一个拦截器对象吗?非常感谢..

### Added positive control
nSamples = 80
features1 = np.float32(np.hstack((np.reshape(np.ones(40), (40, 1)), 
        np.reshape(np.random.randn(nSamples), (40, 2)))))
features2 = np.float32(np.hstack((np.reshape(np.zeros(40), (40, 1)), 
        np.reshape(np.random.randn(nSamples), (40, 2)))))
features = np.vstack((features1, features2))
labels = np.concatenate((np.zeros(40), np.ones(40)))
featuresInt, labelsInt = build_input_pipeline(features, labels, 10)
###

#w_true, b_true, features, labels = toy_logistic_data(FLAGS.num_examples, 2) 
#featuresInt, labelsInt = build_input_pipeline(features, labels, FLAGS.batch_size)

with tf.name_scope("logistic_regression", values=[featuresInt]):
    layer = tfp.layers.DenseFlipout(
        units=1,
        activation=None,
        kernel_posterior_fn=tfp.layers.default_mean_field_normal_fn(),
        bias_posterior_fn=tfp.layers.default_mean_field_normal_fn())
    logits = layer(featuresInt)
    labels_distribution = tfd.Bernoulli(logits=logits)

neg_log_likelihood = -tf.reduce_mean(labels_distribution.log_prob(labelsInt))
kl = sum(layer.losses)
elbo_loss = neg_log_likelihood + kl

predictions = tf.cast(logits > 0, dtype=tf.int32)
accuracy, accuracy_update_op = tf.metrics.accuracy(
    labels=labelsInt, predictions=predictions)

with tf.name_scope("train"):
    optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate)
    train_op = optimizer.minimize(elbo_loss)

init_op = tf.group(tf.global_variables_initializer(),
                    tf.local_variables_initializer())

with tf.Session() as sess:
    sess.run(init_op)

    # Fit the model to data.
    for step in range(FLAGS.max_steps):
        _ = sess.run([train_op, accuracy_update_op])
        if step % 100 == 0:
            loss_value, accuracy_value = sess.run([elbo_loss, accuracy])
            print("Step: {:>3d} Loss: {:.3f} Accuracy: {:.3f}".format(
                step, loss_value, accuracy_value))

### Check with basic Keras
kerasModel = tf.keras.models.Sequential([
    tf.keras.layers.Dense(1)])
optimizer = tf.train.AdamOptimizer(5e-2)
kerasModel.compile(optimizer = optimizer, loss = 'binary_crossentropy', 
    metrics = ['accuracy'])

kerasModel.fit(features, labels, epochs = 50) #100% accuracy

与github例子相比,你在定义KL散度时忘记除以例子数:

kl = sum(layer.losses) / FLAGS.num_examples

当我将此更改为您的代码时,我很快就获得了 99.9% 的玩具数据准确率。

此外,您的 Keras 模型的输出层实际上需要 sigmoid 激活这个问题(二进制分类):

kerasModel = tf.keras.models.Sequential([
    tf.keras.layers.Dense(1, activation='sigmoid')])

这是一个玩具问题,但您会注意到模型通过 sigmoid 激活函数更快地达到 100% 的准确率。