xor.py 690 B

123456789101112131415161718192021222324
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. import tensorflow as tf
  4. from tensorflow.keras import layers, models
  5. trainingData = tf.constant([[0, 0], [0, 1], [1, 0], [1, 1]])
  6. trainLabels = tf.constant([ 0, 1, 1, 0 ])
  7. model = models.Sequential()
  8. model.add(layers.Dense(32, input_dim=2, activation='relu'))
  9. model.add(layers.Dense(1, activation='sigmoid'))
  10. model.compile(loss='mean_squared_error',
  11. optimizer='adam',
  12. metrics=['binary_accuracy'])
  13. model.fit(trainingData, trainLabels, epochs=400)
  14. prediction = model.predict(trainingData)
  15. for (a, b), (y,) in zip(trainingData, prediction):
  16. print("{:.0f} xor {:.0f} = {:.0f}".format(a, b, y))