【问题标题】:Tensorflow 2 XOR implementationTensorFlow 2 XOR 实现
【发布时间】:2019-12-09 05:29:28
【问题描述】:

我是 tensorflow 新手,首先我想训练 XOR 模型,给出 4 个具有 2 个值的输入,并学习 4 个具有 1 个值的输出。 这是我在 TF 2 中所做的事情

    model = keras.Sequential([
    keras.layers.Input(shape=(2,)),
    keras.layers.Dense(units=2, activation='relu'),
    keras.layers.Dense(units=1, activation='softmax')
    ])

    model.compile(optimizer='adam',
                  loss=tf.losses.CategoricalCrossentropy(from_logits=True),
                  metrics=['accuracy'])

    history = model.fit(
        (tf.cast([[0,0],[0,1],[1,0],[1,1]], tf.float32), tf.cast([0,1,1,0], tf.float32)),
        epochs=4,
        steps_per_epoch=1,
        validation_data=(tf.cast([[0.7, 0.7]], tf.float32), tf.cast([0], tf.float32)),
        validation_steps=1
       )

上面的代码给出错误IndexError: list index out of range

请帮我解决这个问题,我想了解如何想出形状给模型。

【问题讨论】:

    标签: machine-learning keras tensorflow2.0


    【解决方案1】:

    在 fit 函数中分配参数时遇到问题:

    history = model.fit(
        (tf.cast([[0,0],[0,1],[1,0],[1,1]], tf.float32), tf.cast([0,1,1,0], tf.float32)),
        epochs=4,
        steps_per_epoch=1,
        validation_data=(tf.cast([[0.7, 0.7]], tf.float32), tf.cast([0], tf.float32)),
        validation_steps=1)
    

    尝试用以下代码替换该行:

    x_train = tf.cast([[0,0],[0,1],[1,0],[1,1]], tf.float32)
    y_train = tf.cast([0,1,1,0], tf.float32)
    x_test = tf.cast([[0.7, 0.7]], tf.float32)
    y_test = tf.cast([0], tf.float32)
    history = model.fit(
        x=x_train, y=y_train,
        epochs=4,
        steps_per_epoch=1,
        validation_data=(x_test, y_test),
        validation_steps=1
        )
    

    你的问题应该已经解决了。

    PS:只是一个建议,当你进行二元分类时,尝试使用 sigmoid 代替 softmax,并分别使用 BinaryCrossentropy loss 代替 CategoricalCrossentropy。祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 2016-01-01
      • 2013-10-10
      • 1970-01-01
      • 2013-10-12
      • 2016-03-04
      • 2017-05-03
      相关资源
      最近更新 更多