462358f4a0
... but the interpreter might be more useful although
84 lines
2.7 KiB
Python
84 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
|
|
|
|
"""
|
|
@authors: TensorFlow Team (Understood and improved by Sam')
|
|
"""
|
|
|
|
|
|
import tensorflow as tf
|
|
from tensorflow.examples.tutorials.mnist import input_data
|
|
|
|
|
|
# Let's load MNIST data and labels.
|
|
mnist = input_data.read_data_sets("/tmp/MNIST/", one_hot=True)
|
|
|
|
|
|
"""
|
|
Here, 'x' is a symbolic variable. We'll give it as input to TensorFlow.
|
|
It'll be a 'float32'.
|
|
'None' represents the non-limited length for any input dimension.
|
|
'784' is for flattening the input to 784-dimensional vector.
|
|
"""
|
|
x = tf.placeholder(tf.float32, [None, 784])
|
|
|
|
# Below, 'W' and 'b' will be respectively the different weights and bias...
|
|
# ... for each input.
|
|
W = tf.Variable(tf.zeros([784, 10]))
|
|
b = tf.Variable(tf.zeros([10]))
|
|
|
|
# Now, it's time to tell to TensorFlow which model we'll enforce between our...
|
|
# ... inputs and our outputs.
|
|
y = tf.nn.softmax(tf.matmul(x, W) + b) # --> y = W * x + b
|
|
|
|
# New placeholder for cross-entropy computation.
|
|
y_ = tf.placeholder(tf.float32, [None, 10])
|
|
|
|
# Cross-entropy function:
|
|
cross_entropy = tf.reduce_mean(
|
|
-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])
|
|
)
|
|
|
|
# Let's run the training with a gradient descent, while minimizing...
|
|
# ... the cross-entropy.
|
|
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
|
|
|
|
# Now everything is correctly set up, let's define the initialization of all...
|
|
# ... the variables above.
|
|
initialization = tf.initialize_all_variables()
|
|
|
|
# Let's choose our device for computation.
|
|
with tf.device("/cpu:0"):
|
|
|
|
# A new session to compute the TensorFlow graph.
|
|
with tf.Session() as sess:
|
|
|
|
# Let's run the initialization of the variables in the graph.
|
|
sess.run(initialization)
|
|
|
|
# Now, we'll run 1000 times the training function.
|
|
for i in range(1000):
|
|
|
|
# Let's get 100 training examples from the MNIST dataset.
|
|
batch_xs, batch_ys = mnist.train.next_batch(100)
|
|
|
|
# Computes the training on these examples.
|
|
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
|
|
|
|
# Here, 'correct_prediction' will become a list with '1' and '0'...
|
|
# ... when yes or no, the prediction was the reality
|
|
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
|
|
|
|
# Let's compute the mean of this list (e.g. [1., 0., 1.] --> 66.66 %)
|
|
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
|
|
|
|
# Runs and prints the value of the accuracy
|
|
print("--> Accuracy:", round(
|
|
sess.run(accuracy, feed_dict={
|
|
x: mnist.test.images,
|
|
y_: mnist.test.labels
|
|
}) * 100, 2), '%')
|
|
|
|
# Always close the session afterwards.
|
|
sess.close()
|