Quellcode durchsuchen

added Python 3 compatibility (#58)

Robert Walecki vor 8 Jahren
Ursprung
Commit
1a44c34fcb

+ 8 - 6
examples/1_Introduction/basic_operations.py

@@ -5,6 +5,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 
 # Basic constant operations
@@ -15,9 +17,9 @@ b = tf.constant(3)
 
 # Launch the default graph.
 with tf.Session() as sess:
-    print "a=2, b=3"
-    print "Addition with constants: %i" % sess.run(a+b)
-    print "Multiplication with constants: %i" % sess.run(a*b)
+    print("a=2, b=3")
+    print("Addition with constants: %i" % sess.run(a+b))
+    print("Multiplication with constants: %i" % sess.run(a*b))
 
 # Basic Operations with variable as graph input
 # The value returned by the constructor represents the output
@@ -33,8 +35,8 @@ mul = tf.mul(a, b)
 # Launch the default graph.
 with tf.Session() as sess:
     # Run every operation with variable input
-    print "Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3})
-    print "Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3})
+    print("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
+    print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))
 
 
 # ----------------
@@ -69,5 +71,5 @@ product = tf.matmul(matrix1, matrix2)
 # The output of the op is returned in 'result' as a numpy `ndarray` object.
 with tf.Session() as sess:
     result = sess.run(product)
-    print result
+    print(result)
     # ==> [[ 12.]]

+ 3 - 1
examples/1_Introduction/helloworld.py

@@ -5,6 +5,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 
 #Simple hello world using TensorFlow
@@ -20,4 +22,4 @@ hello = tf.constant('Hello, TensorFlow!')
 sess = tf.Session()
 
 # Run the op
-print sess.run(hello)
+print(sess.run(hello))

+ 11 - 9
examples/2_BasicModels/linear_regression.py

@@ -5,6 +5,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 import numpy
 import matplotlib.pyplot as plt
@@ -53,12 +55,12 @@ with tf.Session() as sess:
         #Display logs per epoch step
         if (epoch+1) % display_step == 0:
             c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
-            print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
-                "W=", sess.run(W), "b=", sess.run(b)
+            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
+                "W=", sess.run(W), "b=", sess.run(b))
 
-    print "Optimization Finished!"
-    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
-    print "Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n'
+    print("Optimization Finished!"
+    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y}))
+    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
 
     #Graphic display
     plt.plot(train_X, train_Y, 'ro', label='Original data')
@@ -70,13 +72,13 @@ with tf.Session() as sess:
     test_X = numpy.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])
     test_Y = numpy.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03])
 
-    print "Testing... (Mean square loss Comparison)"
+    print("Testing... (Mean square loss Comparison)")
     testing_cost = sess.run(
         tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * test_X.shape[0]),
         feed_dict={X: test_X, Y: test_Y})  # same function as cost above
-    print "Testing cost=", testing_cost
-    print "Absolute mean square loss difference:", abs(
-        training_cost - testing_cost)
+    print("Testing cost=", testing_cost)
+    print("Absolute mean square loss difference:", abs(
+        training_cost - testing_cost))
 
     plt.plot(test_X, test_Y, 'bo', label='Testing data')
     plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')

+ 2 - 0
examples/2_BasicModels/logistic_regression.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 
 # Import MINST data

+ 6 - 4
examples/2_BasicModels/nearest_neighbor.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import numpy as np
 import tensorflow as tf
 
@@ -42,10 +44,10 @@ with tf.Session() as sess:
         # Get nearest neighbor
         nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
         # Get nearest neighbor class label and compare it to its true label
-        print "Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
-            "True Class:", np.argmax(Yte[i])
+        print("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \
+            "True Class:", np.argmax(Yte[i]))
         # Calculate accuracy
         if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
             accuracy += 1./len(Xte)
-    print "Done!"
-    print "Accuracy:", accuracy
+    print("Done!")
+    print("Accuracy:", accuracy)

+ 7 - 5
examples/3_NeuralNetworks/bidirectional_rnn.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 from tensorflow.python.ops import rnn, rnn_cell
 import numpy as np
@@ -106,15 +108,15 @@ with tf.Session() as sess:
             acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})
             # Calculate batch loss
             loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})
-            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
+            print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                   "{:.6f}".format(loss) + ", Training Accuracy= " + \
-                  "{:.5f}".format(acc)
+                  "{:.5f}".format(acc))
         step += 1
-    print "Optimization Finished!"
+    print("Optimization Finished!")
 
     # Calculate accuracy for 128 mnist test images
     test_len = 128
     test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
     test_label = mnist.test.labels[:test_len]
-    print "Testing Accuracy:", \
-        sess.run(accuracy, feed_dict={x: test_data, y: test_label})
+    print("Testing Accuracy:", \
+        sess.run(accuracy, feed_dict={x: test_data, y: test_label}))

+ 7 - 5
examples/3_NeuralNetworks/convolutional_network.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 
 # Import MINST data
@@ -119,14 +121,14 @@ with tf.Session() as sess:
             loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
                                                               y: batch_y,
                                                               keep_prob: 1.})
-            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
+            print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                   "{:.6f}".format(loss) + ", Training Accuracy= " + \
-                  "{:.5f}".format(acc)
+                  "{:.5f}".format(acc))
         step += 1
-    print "Optimization Finished!"
+    print("Optimization Finished!")
 
     # Calculate accuracy for 256 mnist test images
-    print "Testing Accuracy:", \
+    print("Testing Accuracy:", \
         sess.run(accuracy, feed_dict={x: mnist.test.images[:256],
                                       y: mnist.test.labels[:256],
-                                      keep_prob: 1.})
+                                      keep_prob: 1.}))

+ 7 - 5
examples/3_NeuralNetworks/dynamic_rnn.py

@@ -9,6 +9,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 import random
 
@@ -179,16 +181,16 @@ with tf.Session() as sess:
             # Calculate batch loss
             loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y,
                                              seqlen: batch_seqlen})
-            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
+            print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                   "{:.6f}".format(loss) + ", Training Accuracy= " + \
-                  "{:.5f}".format(acc)
+                  "{:.5f}".format(acc))
         step += 1
-    print "Optimization Finished!"
+    print("Optimization Finished!")
 
     # Calculate accuracy
     test_data = testset.data
     test_label = testset.labels
     test_seqlen = testset.seqlen
-    print "Testing Accuracy:", \
+    print("Testing Accuracy:", \
         sess.run(accuracy, feed_dict={x: test_data, y: test_label,
-                                      seqlen: test_seqlen})
+                                      seqlen: test_seqlen}))

+ 6 - 4
examples/3_NeuralNetworks/multilayer_perceptron.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 # Import MINST data
 from tensorflow.examples.tutorials.mnist import input_data
 mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
@@ -82,12 +84,12 @@ with tf.Session() as sess:
             avg_cost += c / total_batch
         # Display logs per epoch step
         if epoch % display_step == 0:
-            print "Epoch:", '%04d' % (epoch+1), "cost=", \
-                "{:.9f}".format(avg_cost)
-    print "Optimization Finished!"
+            print("Epoch:", '%04d' % (epoch+1), "cost=", \
+                "{:.9f}".format(avg_cost))
+    print("Optimization Finished!")
 
     # Test model
     correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
     # Calculate accuracy
     accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
-    print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
+    print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

+ 7 - 5
examples/3_NeuralNetworks/recurrent_network.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 from tensorflow.python.ops import rnn, rnn_cell
 import numpy as np
@@ -97,15 +99,15 @@ with tf.Session() as sess:
             acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})
             # Calculate batch loss
             loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})
-            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
+            print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
                   "{:.6f}".format(loss) + ", Training Accuracy= " + \
-                  "{:.5f}".format(acc)
+                  "{:.5f}".format(acc))
         step += 1
-    print "Optimization Finished!"
+    print("Optimization Finished!")
 
     # Calculate accuracy for 128 mnist test images
     test_len = 128
     test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
     test_label = mnist.test.labels[:test_len]
-    print "Testing Accuracy:", \
-        sess.run(accuracy, feed_dict={x: test_data, y: test_label})
+    print("Testing Accuracy:", \
+        sess.run(accuracy, feed_dict={x: test_data, y: test_label}))

+ 15 - 13
examples/4_Utils/save_restore_model.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 # Import MINST data
 from tensorflow.examples.tutorials.mnist import input_data
 mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
@@ -68,7 +70,7 @@ init = tf.initialize_all_variables()
 saver = tf.train.Saver()
 
 # Running first session
-print "Starting 1st session..."
+print("Starting 1st session...")
 with tf.Session() as sess:
     # Initialize variables
     sess.run(init)
@@ -87,29 +89,29 @@ with tf.Session() as sess:
             avg_cost += c / total_batch
         # Display logs per epoch step
         if epoch % display_step == 0:
-            print "Epoch:", '%04d' % (epoch+1), "cost=", \
-                "{:.9f}".format(avg_cost)
-    print "First Optimization Finished!"
+            print("Epoch:", '%04d' % (epoch+1), "cost=", \
+                "{:.9f}".format(avg_cost))
+    print("First Optimization Finished!")
 
     # Test model
     correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
     # Calculate accuracy
     accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
-    print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
+    print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
 
     # Save model weights to disk
     save_path = saver.save(sess, model_path)
-    print "Model saved in file: %s" % save_path
+    print("Model saved in file: %s" % save_path)
 
 # Running a new session
-print "Starting 2nd session..."
+print("Starting 2nd session...")
 with tf.Session() as sess:
     # Initialize variables
     sess.run(init)
 
     # Restore model weights from previously saved model
     saver.restore(sess, model_path)
-    print "Model restored from file: %s" % save_path
+    print("Model restored from file: %s" % save_path)
 
     # Resume training
     for epoch in range(7):
@@ -125,13 +127,13 @@ with tf.Session() as sess:
             avg_cost += c / total_batch
         # Display logs per epoch step
         if epoch % display_step == 0:
-            print "Epoch:", '%04d' % (epoch + 1), "cost=", \
-                "{:.9f}".format(avg_cost)
-    print "Second Optimization Finished!"
+            print("Epoch:", '%04d' % (epoch + 1), "cost=", \
+                "{:.9f}".format(avg_cost))
+    print("Second Optimization Finished!")
 
     # Test model
     correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
     # Calculate accuracy
     accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
-    print "Accuracy:", accuracy.eval(
-        {x: mnist.test.images, y: mnist.test.labels})
+    print("Accuracy:", accuracy.eval(
+        {x: mnist.test.images, y: mnist.test.labels}))

+ 7 - 5
examples/4_Utils/tensorboard_advanced.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 
 # Import MINST data
@@ -126,14 +128,14 @@ with tf.Session() as sess:
             avg_cost += c / total_batch
         # Display logs per epoch step
         if (epoch+1) % display_step == 0:
-            print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
+            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
 
-    print "Optimization Finished!"
+    print("Optimization Finished!")
 
     # Test model
     # Calculate accuracy
-    print "Accuracy:", acc.eval({x: mnist.test.images, y: mnist.test.labels})
+    print("Accuracy:", acc.eval({x: mnist.test.images, y: mnist.test.labels}))
 
-    print "Run the command line:\n" \
+    print("Run the command line:\n" \
           "--> tensorboard --logdir=/tmp/tensorflow_logs " \
-          "\nThen open http://0.0.0.0:6006/ into your web browser"
+          "\nThen open http://0.0.0.0:6006/ into your web browser")

+ 7 - 5
examples/4_Utils/tensorboard_basic.py

@@ -7,6 +7,8 @@ Author: Aymeric Damien
 Project: https://github.com/aymericdamien/TensorFlow-Examples/
 '''
 
+from __future__ import print_function
+
 import tensorflow as tf
 
 # Import MINST data
@@ -80,14 +82,14 @@ with tf.Session() as sess:
             avg_cost += c / total_batch
         # Display logs per epoch step
         if (epoch+1) % display_step == 0:
-            print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
+            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))
 
-    print "Optimization Finished!"
+    print("Optimization Finished!")
 
     # Test model
     # Calculate accuracy
-    print "Accuracy:", acc.eval({x: mnist.test.images, y: mnist.test.labels})
+    print("Accuracy:", acc.eval({x: mnist.test.images, y: mnist.test.labels}))
 
-    print "Run the command line:\n" \
+    print("Run the command line:\n" \
           "--> tensorboard --logdir=/tmp/tensorflow_logs " \
-          "\nThen open http://0.0.0.0:6006/ into your web browser"
+          "\nThen open http://0.0.0.0:6006/ into your web browser")

+ 4 - 2
examples/5_MultiGPU/multigpu_basics.py

@@ -12,6 +12,8 @@ This tutorial requires your machine to have 2 GPUs
 "/gpu:1": The second GPU of your machine
 '''
 
+from __future__ import print_function
+
 import numpy as np
 import tensorflow as tf
 import datetime
@@ -87,5 +89,5 @@ with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)
 t2_2 = datetime.datetime.now()
 
 
-print "Single GPU computation time: " + str(t2_1-t1_1)
-print "Multi GPU computation time: " + str(t2_2-t1_2)
+print("Single GPU computation time: " + str(t2_1-t1_1))
+print("Multi GPU computation time: " + str(t2_2-t1_2))

+ 2 - 2
multigpu_basics.py

@@ -81,5 +81,5 @@ with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)
 t2_2 = datetime.datetime.now()
 
 
-print "Single GPU computation time: " + str(t2_1-t1_1)
-print "Multi GPU computation time: " + str(t2_2-t1_2)
+print("Single GPU computation time: " + str(t2_1-t1_1))
+print("Multi GPU computation time: " + str(t2_2-t1_2))