【问题标题】:Tensorflow Probability Logistic Regression ExampleTensorFlow 概率逻辑回归示例
【发布时间】:2019-04-04 02:32:39
【问题描述】:

我觉得我必须遗漏一些明显的东西,在努力获得对张量流概率中逻辑回归的正控制。

我修改了逻辑回归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

【问题讨论】:

    标签: tensorflow-probability


    【解决方案1】:

    与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% 的准确度。

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2013-06-05
      • 2017-11-20
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多