|
| 1 | +# Lab 6 Softmax Classifier |
| 2 | +import tensorflow as tf |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +x_data = np.array([[1, 2, 1], [1, 3, 2], [1, 3, 4], [1, 5, 5], |
| 6 | + [1, 7, 5], [1, 2, 5], [1, 6, 6], [1, 7, 7]], dtype=np.float32) |
| 7 | +y_data = np.array([[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 1, 0], |
| 8 | + [0, 1, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0]], dtype=np.float32) |
| 9 | + |
| 10 | +X = tf.placeholder("float", [None, 3]) |
| 11 | +Y = tf.placeholder("float", [None, 3]) |
| 12 | + |
| 13 | +W = tf.Variable(tf.zeros([3, 3])) |
| 14 | +# Softmax |
| 15 | +hypothesis = tf.nn.softmax(tf.matmul(X, W)) |
| 16 | +# tf.nn.softmax computes softmax activations |
| 17 | +# softmax = exp(logits) / reduce_sum(exp(logits), dim) |
| 18 | + |
| 19 | +# Cross entropy cost |
| 20 | +cost = tf.reduce_mean(-tf.reduce_sum(Y * |
| 21 | + tf.log(hypothesis), axis=1)) |
| 22 | + |
| 23 | +optimizer = tf.train.GradientDescentOptimizer( |
| 24 | + learning_rate=0.1).minimize(cost) |
| 25 | + |
| 26 | +init = tf.global_variables_initializer() |
| 27 | + |
| 28 | +# Launch graph |
| 29 | +with tf.Session() as sess: |
| 30 | + sess.run(init) |
| 31 | + |
| 32 | + for step in range(2001): |
| 33 | + sess.run(optimizer, feed_dict={X: x_data, Y: y_data}) |
| 34 | + if step % 200 == 0: |
| 35 | + print(step, sess.run(cost, feed_dict={ |
| 36 | + X: x_data, Y: y_data}), sess.run(W)) |
| 37 | + |
| 38 | + print('--------------') |
| 39 | + |
| 40 | + # Testing & One-hot encoding |
| 41 | + a = sess.run(hypothesis, feed_dict={X: [[1, 11, 7]]}) |
| 42 | + print(a, sess.run(tf.arg_max(a, 1))) |
| 43 | + |
| 44 | + print('--------------') |
| 45 | + |
| 46 | + b = sess.run(hypothesis, feed_dict={X: [[1, 3, 4]]}) |
| 47 | + print(a, sess.run(tf.arg_max(b, 1))) |
| 48 | + |
| 49 | + print('--------------') |
| 50 | + |
| 51 | + c = sess.run(hypothesis, feed_dict={X: [[1, 1, 0]]}) |
| 52 | + print(a, sess.run(tf.arg_max(c, 1))) |
| 53 | + |
| 54 | + print('--------------') |
| 55 | + |
| 56 | + all = sess.run(hypothesis, feed_dict={ |
| 57 | + X: [[1, 11, 7], [1, 3, 4], [1, 1, 0]]}) |
| 58 | + print(all, sess.run(tf.arg_max(all, 1))) |
0 commit comments