|
| 1 | +# Lab 9 XOR |
| 2 | +# This example does not work |
| 3 | +import tensorflow as tf |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +x_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32) |
| 7 | +y_data = np.array([[0], [1], [1], [0]], dtype=np.float32) |
| 8 | + |
| 9 | +X = tf.placeholder(tf.float32) |
| 10 | +Y = tf.placeholder(tf.float32) |
| 11 | + |
| 12 | + |
| 13 | +W = tf.Variable(tf.random_uniform( |
| 14 | + shape=[2, 1], minval=-1.0, maxval=1.0, dtype=tf.float32)) |
| 15 | + |
| 16 | +# Hypothesis |
| 17 | +h = tf.matmul(X, W) |
| 18 | +hypothesis = tf.div(1., 1. + tf.exp(-h)) |
| 19 | + |
| 20 | +# Cost function |
| 21 | +cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) |
| 22 | + * tf.log(1 - hypothesis)) |
| 23 | + |
| 24 | +train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost) |
| 25 | + |
| 26 | +# Initialize variables |
| 27 | +init = tf.global_variables_initializer() |
| 28 | + |
| 29 | +# Launch graph |
| 30 | +with tf.Session() as sess: |
| 31 | + sess.run(init) |
| 32 | + |
| 33 | + for step in range(1001): |
| 34 | + sess.run(train, feed_dict={X: x_data, Y: y_data}) |
| 35 | + if step % 200 == 0: |
| 36 | + print(step, sess.run(cost, feed_dict={ |
| 37 | + X: x_data, Y: y_data}), sess.run(W)) |
| 38 | + |
| 39 | + # Test model |
| 40 | + correct_prediction = tf.equal(tf.floor(hypothesis + 0.5), Y) |
| 41 | + |
| 42 | + # Accuracy |
| 43 | + accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32)) |
| 44 | + print(sess.run([hypothesis, tf.floor(hypothesis + 0.5), |
| 45 | + correct_prediction, accuracy], feed_dict={X: x_data, Y: y_data})) |
| 46 | + print("Accuracy: ", accuracy.eval({X: x_data, Y: y_data})) |
0 commit comments