Tensorflow概率逻辑回归示例

时间:2018-10-31 00:28:24

标签: tensorflow-probability

我觉得我在努力获得对张量流概率进行逻辑回归的正向控制方面肯定缺少明显的东西。

我修改了逻辑回归here的示例,并创建了一个积极的控制功能和标签数据。我很难达到60%以上的准确度,但是对于“香草” 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

1 个答案:

答案 0 :(得分:0)

与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')])

这是一个玩具问题,但是您会注意到,通过S型激活可以使模型更快地达到100%的准确性。