【发布时间】:2020-11-04 14:22:33
【问题描述】:
我正在尝试使用 TensorFlow 实现神经网络来解决 XOR 问题。我选择了sigmoid作为激活函数,形状(2, 2, 1)和optimizer=SGD()。我选择batch_size=1,因为问题的宇宙是4,所以真的很小。问题是预测甚至没有接近正确的答案。我做错了什么?
我在 Google Colab 上做这个,Tensorflow 版本是 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)
输出:
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]]
【问题讨论】:
标签: python tensorflow machine-learning keras neural-network