1

論理 AND 演算を計算できる tensorflow カスタム推定器を使用して単純な 1 レイヤー/1 ユニット nn を作成しようとしていますが、シグモイド アクティベーションに問題があります - しきい値を設定したい

ここに私のコードがあります

x = np.array([
    [0, 0],
    [1, 0],
    [0, 1],
    [1, 1]
], dtype=np.float32)

y = np.array([
    [0],
    [0],
    [0],
    [1]
])

def sigmoid(val):
    res = tf.nn.sigmoid(val)
    isGreater = tf.greater(res, tf.constant(0.5))
    return tf.cast(isGreater, dtype=tf.float32)

def model_fn(features, labels, mode, params):
    predictions = tf.layers.dense(inputs=features, units=1, activation=sigmoid)

    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

    loss = tf.losses.sigmoid_cross_entropy(labels, predictions)
    optimizer = tf.train.GradientDescentOptimizer(0.5)
    train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())

    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

nn = tf.estimator.Estimator(model_fn=model_fn)
input_fn = tf.estimator.inputs.numpy_input_fn(x=x, y=y, shuffle=False, num_epochs=None)

nn.train(input_fn=input_fn, steps=500)

しかし、これはエラーをスローします

ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables ["<tf.Variable 'dense/kernel:0' shape=(2, 1) dtype=float32_ref>", "<tf.Variable 'dense/bias:0' shape=(1,) dtype=float32_ref>"] and loss Tensor("sigmoid_cross_entropy_loss/value:0", shape=(), dtype=float32).

どうすればこれを修正できますか? 助けてください..

私が持っている別の質問 - なぜ Tensorflow にはシグモイド アクティベーションのしきい値が組み込まれていないのですか? バイナリ分類 (シグモイド/tanh を使用) に最も必要なものの 1 つではありませんか?

4

1 に答える 1

2

組み込みのシグモイド アクティベーションがありtf.nn.sigmoidます。

ただし、ネットワークを作成するときは、最後のレイヤーでアクティベーションを使用しないでください。次のように、スケーリングされていないロジットをレイヤーに提供する必要があります。

predictions = tf.layers.dense(inputs=features, units=1, activation=None)

loss = tf.losses.sigmoid_cross_entropy(labels, predictions)

それ以外の場合、カスタム シグモイドを使用すると、予測は or のいずれ01になり、これに使用できる勾配はありません。

于 2018-03-16T05:17:06.213 に答える