diff --git a/examples/1_Introduction/basic_eager_api.py b/examples/1_Introduction/basic_eager_api.py index e00719d3..6fd02fa1 100644 --- a/examples/1_Introduction/basic_eager_api.py +++ b/examples/1_Introduction/basic_eager_api.py @@ -27,33 +27,33 @@ tfe.enable_eager_execution() # Define constant tensors -print("Define constant tensors") -a = tf.constant(2) -print("a = %i" % a) -b = tf.constant(3) -print("b = %i" % b) +# print("Define constant tensors") +# a = tf.constant(2) +# print("a = %i" % a) +# b = tf.constant(3) +# print("b = %i" % b) -# Run the operation without the need for tf.Session -print("Running operations, without tf.Session") -c = a + b -print("a + b = %i" % c) -d = a * b -print("a * b = %i" % d) +# # Run the operation without the need for tf.Session +# print("Running operations, without tf.Session") +# c = a + b +# print("a + b = %i" % c) +# d = a * b +# print("a * b = %i" % d) -# Full compatibility with Numpy -print("Mixing operations with Tensors and Numpy Arrays") +# # Full compatibility with Numpy +# print("Mixing operations with Tensors and Numpy Arrays") # Define constant tensors -a = tf.constant([[2., 1.], +a = tf.constant([[2., 5.], [1., 0.]], dtype=tf.float32) -print("Tensor:\n a = %s" % a) +# print("Tensor:\n a = %s" % a) b = np.array([[3., 0.], [5., 1.]], dtype=np.float32) -print("NumpyArray:\n b = %s" % b) +# print("NumpyArray:\n b = %s" % b) # Run the operation without the need for tf.Session -print("Running operations, without tf.Session") +# print("Running operations, without tf.Session") c = a + b print("a + b = %s" % c) @@ -61,6 +61,9 @@ d = tf.matmul(a, b) print("a * b = %s" % d) +e = tf.multiply(a, b) +print("a . b = %s" % e) + print("Iterate through Tensor 'a':") for i in range(a.shape[0]): for j in range(a.shape[1]): diff --git a/examples/1_Introduction/basic_operations.py b/examples/1_Introduction/basic_operations.py index e1775069..cc38139d 100644 --- a/examples/1_Introduction/basic_operations.py +++ b/examples/1_Introduction/basic_operations.py @@ -14,6 +14,8 @@ # of the Constant op. a = tf.constant(2) b = tf.constant(3) +print("a = %s" % a) +print('b = %s' % b) # Launch the default graph. with tf.Session() as sess: @@ -58,6 +60,9 @@ # multiplication. product = tf.matmul(matrix1, matrix2) +print('product = %s' % product) +print('------------------------') + # To run the matmul op we call the session 'run()' method, passing 'product' # which represents the output of the matmul op. This indicates to the call # that we want to get the output of the matmul op back. @@ -73,3 +78,9 @@ result = sess.run(product) print(result) # ==> [[ 12.]] + +# 上下文管理器的内容,在外面依然可以访问 +print('--------', result) + +# 即使在 session 运行结束之后,product 依然只是 matmul operation 的 placeholder +print('*****', product) \ No newline at end of file diff --git a/examples/2_BasicModels/gradient_boosted_decision_tree.py b/examples/2_BasicModels/gradient_boosted_decision_tree.py index 00501a2b..fb07b8c8 100644 --- a/examples/2_BasicModels/gradient_boosted_decision_tree.py +++ b/examples/2_BasicModels/gradient_boosted_decision_tree.py @@ -25,8 +25,13 @@ # Set verbosity to display errors only (Remove this line for showing warnings) tf.logging.set_verbosity(tf.logging.ERROR) from tensorflow.examples.tutorials.mnist import input_data -mnist = input_data.read_data_sets("/tmp/data/", one_hot=False, - source_url='http://yann.lecun.com/exdb/mnist/') + +# mnist = input_data.read_data_sets("/tmp/data/", one_hot=False, +# source_url='http://yann.lecun.com/exdb/mnist/') + +mnist = input_data.read_data_sets("../../../MNIST_data/", one_hot=False) + +print(mnist) # Parameters batch_size = 4096 # The number of samples per batch @@ -67,10 +72,13 @@ # Display TF info logs tf.logging.set_verbosity(tf.logging.INFO) +# print(mnist) + # Define the input function for training input_fn = tf.estimator.inputs.numpy_input_fn( x={'images': mnist.train.images}, y=mnist.train.labels, batch_size=batch_size, num_epochs=None, shuffle=True) + # Train the Model gbdt_model.fit(input_fn=input_fn, max_steps=max_steps) @@ -79,6 +87,7 @@ input_fn = tf.estimator.inputs.numpy_input_fn( x={'images': mnist.test.images}, y=mnist.test.labels, batch_size=batch_size, shuffle=False) + # Use the Estimator 'evaluate' method e = gbdt_model.evaluate(input_fn=input_fn) diff --git a/examples/2_BasicModels/kmeans.py b/examples/2_BasicModels/kmeans.py index ed4bf91b..e93a10f2 100644 --- a/examples/2_BasicModels/kmeans.py +++ b/examples/2_BasicModels/kmeans.py @@ -22,7 +22,8 @@ # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data -mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) + +mnist = input_data.read_data_sets("../../../MNIST_data/", one_hot=True) full_data_x = mnist.train.images # Parameters @@ -75,6 +76,7 @@ # Count total number of labels per centroid, using the label of each training # sample to their closest centroid (given by 'idx') counts = np.zeros(shape=(k, num_classes)) + for i in range(len(idx)): counts[idx[i]] += mnist.train.labels[i] # Assign the most frequent label to the centroid @@ -84,6 +86,7 @@ # Evaluation ops # Lookup: centroid_id -> label cluster_label = tf.nn.embedding_lookup(labels_map, cluster_idx) + # Compute accuracy correct_prediction = tf.equal(cluster_label, tf.cast(tf.argmax(Y, 1), tf.int32)) accuracy_op = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) diff --git a/examples/2_BasicModels/linear_regression_eager_api.py b/examples/2_BasicModels/linear_regression_eager_api.py index a9b2b2f7..611e28f1 100644 --- a/examples/2_BasicModels/linear_regression_eager_api.py +++ b/examples/2_BasicModels/linear_regression_eager_api.py @@ -44,6 +44,7 @@ def mean_square_fn(model_fn, inputs, labels): # SGD Optimizer optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) + # Compute gradients grad = tfe.implicit_gradients(mean_square_fn) diff --git a/examples/2_BasicModels/logistic_regression_eager_api.py b/examples/2_BasicModels/logistic_regression_eager_api.py index c65205e7..38ae8dc9 100644 --- a/examples/2_BasicModels/logistic_regression_eager_api.py +++ b/examples/2_BasicModels/logistic_regression_eager_api.py @@ -27,6 +27,7 @@ dataset = tf.data.Dataset.from_tensor_slices( (mnist.train.images, mnist.train.labels)) + dataset = dataset.repeat().batch(batch_size).prefetch(batch_size) dataset_iter = tfe.Iterator(dataset) diff --git a/examples/2_BasicModels/text8.zip b/examples/2_BasicModels/text8.zip new file mode 100644 index 00000000..436e05b2 Binary files /dev/null and b/examples/2_BasicModels/text8.zip differ diff --git a/examples/2_BasicModels/word2vec.py b/examples/2_BasicModels/word2vec.py index 094fca8c..50dbbb23 100644 --- a/examples/2_BasicModels/word2vec.py +++ b/examples/2_BasicModels/word2vec.py @@ -27,16 +27,16 @@ # Training Parameters learning_rate = 0.1 batch_size = 128 -num_steps = 3000000 -display_step = 10000 -eval_step = 200000 +num_steps = 30000 +display_step = 2000 +eval_step = 20000 # Evaluation Parameters eval_words = ['five', 'of', 'going', 'hardware', 'american', 'britain'] # Word2Vec Parameters embedding_size = 200 # Dimension of the embedding vector -max_vocabulary_size = 50000 # Total number of different words in the vocabulary +max_vocabulary_size = 5000 # Total number of different words in the vocabulary min_occurrence = 10 # Remove all words that does not appears at least n times skip_window = 3 # How many words to consider left and right num_skips = 2 # How many times to reuse an input to generate a label @@ -46,18 +46,25 @@ # Download a small chunk of Wikipedia articles collection url = 'http://mattmahoney.net/dc/text8.zip' data_path = 'text8.zip' -if not os.path.exists(data_path): - print("Downloading the dataset... (It may take some time)") - filename, _ = urllib.urlretrieve(url, data_path) - print("Done!") + +# + # Unzip the dataset file. Text has already been processed with zipfile.ZipFile(data_path) as f: text_words = f.read(f.namelist()[0]).lower().split() +# print('text_words:', text_words) + # Build the dictionary and replace rare words with UNK token count = [('UNK', -1)] + +# print('count:', count) + # Retrieve the most common words count.extend(collections.Counter(text_words).most_common(max_vocabulary_size - 1)) + +# print('update count: %s' % count[0: 10]) + # Remove samples with less than 'min_occurrence' occurrences for i in range(len(count) - 1, -1, -1): if count[i][1] < min_occurrence: @@ -65,13 +72,19 @@ else: # The collection is ordered, so stop when 'min_occurrence' is reached break + # Compute the vocabulary size +# 47135 vocabulary_size = len(count) + # Assign an id to each word word2id = dict() -for i, (word, _)in enumerate(count): + +for i, (word, _) in enumerate(count): word2id[word] = i +# print('word2id: %s' % word2id['the']) + data = list() unk_count = 0 for word in text_words: @@ -80,116 +93,143 @@ if index == 0: unk_count += 1 data.append(index) + count[0] = ('UNK', unk_count) id2word = dict(zip(word2id.values(), word2id.keys())) -print("Words count:", len(text_words)) -print("Unique words:", len(set(text_words))) -print("Vocabulary size:", vocabulary_size) -print("Most common words:", count[:10]) +# print("Words count:", len(text_words)) +# print("Unique words:", len(set(text_words))) +# print("Vocabulary size:", vocabulary_size) +# print("Most common words:", count[:10]) +# print('data: %s' % data[1:200]) data_index = 0 # Generate training batch for the skip-gram model def next_batch(batch_size, num_skips, skip_window): + global data_index assert batch_size % num_skips == 0 assert num_skips <= 2 * skip_window batch = np.ndarray(shape=(batch_size), dtype=np.int32) labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32) + # get window size (words left and right + current one) span = 2 * skip_window + 1 buffer = collections.deque(maxlen=span) if data_index + span > len(data): data_index = 0 buffer.extend(data[data_index:data_index + span]) + + print('buffer: %s' % buffer) + data_index += span - for i in range(batch_size // num_skips): + + print('data_index: %s' % data_index) + + # for i in range(batch_size // num_skips): + for i in range(1): context_words = [w for w in range(span) if w != skip_window] words_to_use = random.sample(context_words, num_skips) + + print('context_words: %s, words_to_use: %s' % (context_words, words_to_use)) + for j, context_word in enumerate(words_to_use): + batch[i * num_skips + j] = buffer[skip_window] labels[i * num_skips + j, 0] = buffer[context_word] + print('batch: %s,\n labels: %s' % (batch, labels)) + if data_index == len(data): buffer.extend(data[0:span]) data_index = span else: buffer.append(data[data_index]) data_index += 1 + print('buffer: %s' % buffer) + # Backtrack a little bit to avoid skipping words in the end of a batch data_index = (data_index + len(data) - span) % len(data) return batch, labels - -# Input data -X = tf.placeholder(tf.int32, shape=[None]) -# Input label -Y = tf.placeholder(tf.int32, shape=[None, 1]) - -# Ensure the following ops & var are assigned on CPU -# (some ops are not compatible on GPU) -with tf.device('/cpu:0'): - # Create the embedding variable (each row represent a word embedding vector) - embedding = tf.Variable(tf.random_normal([vocabulary_size, embedding_size])) - # Lookup the corresponding embedding vectors for each sample in X - X_embed = tf.nn.embedding_lookup(embedding, X) - - # Construct the variables for the NCE loss - nce_weights = tf.Variable(tf.random_normal([vocabulary_size, embedding_size])) - nce_biases = tf.Variable(tf.zeros([vocabulary_size])) - -# Compute the average NCE loss for the batch -loss_op = tf.reduce_mean( - tf.nn.nce_loss(weights=nce_weights, - biases=nce_biases, - labels=Y, - inputs=X_embed, - num_sampled=num_sampled, - num_classes=vocabulary_size)) - -# Define the optimizer -optimizer = tf.train.GradientDescentOptimizer(learning_rate) -train_op = optimizer.minimize(loss_op) - -# Evaluation -# Compute the cosine similarity between input data embedding and every embedding vectors -X_embed_norm = X_embed / tf.sqrt(tf.reduce_sum(tf.square(X_embed))) -embedding_norm = embedding / tf.sqrt(tf.reduce_sum(tf.square(embedding), 1, keepdims=True)) -cosine_sim_op = tf.matmul(X_embed_norm, embedding_norm, transpose_b=True) - -# Initialize the variables (i.e. assign their default value) -init = tf.global_variables_initializer() - -with tf.Session() as sess: - - # Run the initializer - sess.run(init) - - # Testing data - x_test = np.array([word2id[w] for w in eval_words]) - - average_loss = 0 - for step in xrange(1, num_steps + 1): - # Get a new batch of data - batch_x, batch_y = next_batch(batch_size, num_skips, skip_window) - # Run training op - _, loss = sess.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y}) - average_loss += loss - - if step % display_step == 0 or step == 1: - if step > 1: - average_loss /= display_step - print("Step " + str(step) + ", Average Loss= " + \ - "{:.4f}".format(average_loss)) - average_loss = 0 - - # Evaluation - if step % eval_step == 0 or step == 1: - print("Evaluation...") - sim = sess.run(cosine_sim_op, feed_dict={X: x_test}) - for i in xrange(len(eval_words)): - top_k = 8 # number of nearest neighbors - nearest = (-sim[i, :]).argsort()[1:top_k + 1] - log_str = '"%s" nearest neighbors:' % eval_words[i] - for k in xrange(top_k): - log_str = '%s %s,' % (log_str, id2word[nearest[k]]) - print(log_str) +batch_x, batch_y = next_batch(batch_size, num_skips, skip_window) + +# print('batch_x: %s, batch_y: %s' % (batch_x, batch_y)) + +# # Input data +# X = tf.placeholder(tf.int32, shape=[None]) +# # Input label +# Y = tf.placeholder(tf.int32, shape=[None, 1]) +# # Ensure the following ops & var are assigned on CPU +# # (some ops are not compatible on GPU) +# with tf.device('/cpu:0'): +# # Create the embedding variable (each row represent a word embedding vector) +# embedding = tf.Variable(tf.random_normal([vocabulary_size, embedding_size])) +# # Lookup the corresponding embedding vectors for each sample in X +# X_embed = tf.nn.embedding_lookup(embedding, X) + +# print('X_embed: %s' % X_embed) + +# # Construct the variables for the NCE loss +# nce_weights = tf.Variable(tf.random_normal([vocabulary_size, embedding_size])) +# nce_biases = tf.Variable(tf.zeros([vocabulary_size])) + +# # Compute the average NCE loss for the batch +# loss_op = tf.reduce_mean( +# tf.nn.nce_loss(weights=nce_weights, +# biases=nce_biases, +# labels=Y, +# inputs=X_embed, +# num_sampled=num_sampled, +# num_classes=vocabulary_size)) + +# # Define the optimizer +# optimizer = tf.train.GradientDescentOptimizer(learning_rate) +# train_op = optimizer.minimize(loss_op) + +# # Evaluation +# # Compute the cosine similarity between input data embedding and every embedding vectors +# X_embed_norm = X_embed / tf.sqrt(tf.reduce_sum(tf.square(X_embed))) +# embedding_norm = embedding / tf.sqrt(tf.reduce_sum(tf.square(embedding), 1, keepdims=True)) +# cosine_sim_op = tf.matmul(X_embed_norm, embedding_norm, transpose_b=True) + +# # Initialize the variables (i.e. assign their default value) +# init = tf.global_variables_initializer() + +# with tf.Session() as sess: + +# # Run the initializer +# sess.run(init) + +# # Testing data +# x_test = np.array([word2id[w] for w in eval_words]) + +# print('x_test: %s' % x_test) + +# average_loss = 0 +# for step in xrange(1, num_steps + 1): + +# # Get a new batch of data +# batch_x, batch_y = next_batch(batch_size, num_skips, skip_window) + +# # Run training op +# _, loss = sess.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y}) +# average_loss += loss + +# if step % display_step == 0 or step == 1: +# if step > 1: +# average_loss /= display_step +# print("Step " + str(step) + ", Average Loss= " + \ +# "{:.4f}".format(average_loss)) +# average_loss = 0 + +# # Evaluation +# if step % eval_step == 0 or step == 1: +# print("Evaluation...") +# sim = sess.run(cosine_sim_op, feed_dict={X: x_test}) +# for i in xrange(len(eval_words)): +# top_k = 8 # number of nearest neighbors +# nearest = (-sim[i, :]).argsort()[1:top_k + 1] +# log_str = '"%s" nearest neighbors:' % eval_words[i] +# for k in xrange(top_k): +# log_str = '%s %s,' % (log_str, id2word[nearest[k]]) +# print(log_str) diff --git a/examples/3_NeuralNetworks/neural_network.py b/examples/3_NeuralNetworks/neural_network.py index 1fff2d54..6114d81a 100644 --- a/examples/3_NeuralNetworks/neural_network.py +++ b/examples/3_NeuralNetworks/neural_network.py @@ -89,15 +89,20 @@ def model_fn(features, labels, mode): input_fn = tf.estimator.inputs.numpy_input_fn( x={'images': mnist.train.images}, y=mnist.train.labels, batch_size=batch_size, num_epochs=None, shuffle=True) + # Train the Model model.train(input_fn, steps=num_steps) # Evaluate the Model # Define the input function for evaluating input_fn = tf.estimator.inputs.numpy_input_fn( - x={'images': mnist.test.images}, y=mnist.test.labels, - batch_size=batch_size, shuffle=False) + x={'images': mnist.test.images}, + y=mnist.test.labels, + batch_size=batch_size, + shuffle=False +) + # Use the Estimator 'evaluate' method -e = model.evaluate(input_fn) +e = model.evaluate( ) print("Testing Accuracy:", e['accuracy']) diff --git a/examples/4_Utils/tensorboard_advanced.py b/examples/4_Utils/tensorboard_advanced.py index 45a7f962..64090982 100644 --- a/examples/4_Utils/tensorboard_advanced.py +++ b/examples/4_Utils/tensorboard_advanced.py @@ -76,9 +76,11 @@ def multilayer_perceptron(x, weights, biases): with tf.name_scope('SGD'): # Gradient Descent optimizer = tf.train.GradientDescentOptimizer(learning_rate) + # Op to calculate every variable gradient grads = tf.gradients(loss, tf.trainable_variables()) grads = list(zip(grads, tf.trainable_variables())) + # Op to update all variables according to their gradient apply_grads = optimizer.apply_gradients(grads_and_vars=grads) @@ -100,6 +102,7 @@ def multilayer_perceptron(x, weights, biases): # Summarize all gradients for grad, var in grads: tf.summary.histogram(var.name + '/gradient', grad) + # Merge all summaries into a single op merged_summary_op = tf.summary.merge_all() diff --git a/examples/4_Utils/tensorboard_basic.py b/examples/4_Utils/tensorboard_basic.py index 81216c0b..fc0e4e7d 100644 --- a/examples/4_Utils/tensorboard_basic.py +++ b/examples/4_Utils/tensorboard_basic.py @@ -53,8 +53,10 @@ # Create a summary to monitor cost tensor tf.summary.scalar("loss", cost) + # Create a summary to monitor accuracy tensor tf.summary.scalar("accuracy", acc) + # Merge all summaries into a single op merged_summary_op = tf.summary.merge_all() diff --git a/examples/5_DataManagement/tensorflow_dataset_api.py b/examples/5_DataManagement/tensorflow_dataset_api.py index dad0132a..105fdb97 100644 --- a/examples/5_DataManagement/tensorflow_dataset_api.py +++ b/examples/5_DataManagement/tensorflow_dataset_api.py @@ -31,6 +31,7 @@ # Create a dataset tensor from the images and the labels dataset = tf.data.Dataset.from_tensor_slices( (mnist.train.images, mnist.train.labels)) + # Automatically refill the data queue when empty dataset = dataset.repeat() # Create batches of data diff --git a/input_data.py b/input_data.py index 0ebcbdad..e7bbeab3 100644 --- a/input_data.py +++ b/input_data.py @@ -4,7 +4,9 @@ import os import urllib import numpy + SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/' + def maybe_download(filename, work_directory): """Download the data from Yann's website, unless it's already here.""" if not os.path.exists(work_directory): @@ -15,9 +17,11 @@ def maybe_download(filename, work_directory): statinfo = os.stat(filepath) print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.') return filepath + def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder('>') return numpy.frombuffer(bytestream.read(4), dtype=dt) + def extract_images(filename): """Extract the images into a 4D uint8 numpy array [index, y, x, depth].""" print('Extracting', filename) @@ -34,6 +38,7 @@ def extract_images(filename): data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) return data + def dense_to_one_hot(labels_dense, num_classes=10): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] @@ -41,6 +46,7 @@ def dense_to_one_hot(labels_dense, num_classes=10): labels_one_hot = numpy.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot + def extract_labels(filename, one_hot=False): """Extract the labels into a 1D uint8 numpy array [index].""" print('Extracting', filename) @@ -112,6 +118,7 @@ def next_batch(self, batch_size, fake_data=False): assert batch_size <= self._num_examples end = self._index_in_epoch return self._images[start:end], self._labels[start:end] + def read_data_sets(train_dir, fake_data=False, one_hot=False): class DataSets(object): pass