首页 > 解决方案 > TensorFlow 2 XOR 实现

问题描述

我是一个 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-learningkerastensorflow2.0

解决方案


您在 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。祝你好运


推荐阅读