I'm trying to implement a Neural Network to solve the XOR problem using TensorFlow. I chose sigmoid as activation function, shape (2, 2, 1) and optimizer=SGD(). I choose batch_size=1 because the universe of the problem is 4, so is really small. The problem is the predictions are not even close to the right answers. What am I doing wrong?
I'm doing this on Google Colab, and the Tensorflow version is 2.3.0.
import tensorflow as tf
import numpy as np
x = np.array([[0, 0],
[1, 1],
[1, 0],
[0, 1]], dtype=np.float32)
y = np.array([[0],
[0],
[1],
[1]], dtype=np.float32)
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(2,)))
model.add(tf.keras.layers.Dense(2, activation=tf.keras.activations.sigmoid))
model.add(tf.keras.layers.Dense(2, activation=tf.keras.activations.sigmoid))
model.add(tf.keras.layers.Dense(1, activation=tf.keras.activations.sigmoid))
model.compile(optimizer=tf.keras.optimizers.SGD(),
loss=tf.keras.losses.MeanSquaredError(),
metrics=['binary_accuracy'])
history = model.fit(x, y, batch_size=1, epochs=500, verbose=False)
print("Tensorflow version: ", tf.__version__)
predictions = model.predict_on_batch(x)
print(predictions)
The output:
Tensorflow version: 2.3.0
WARNING:tensorflow:10 out of the last 10 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7f69f7a83a60> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.
[[0.5090364 ]
[0.4890102 ]
[0.50011414]
[0.49678832]]
