├── LICENSE ├── MultiGPU.py ├── MultiLayerNeuralNetworks.py ├── MultiLayerNeuralNetworks_slim.py ├── NumpyExample.py ├── README.md ├── SingleLayerNeuralNetwork.py ├── TensorFlowVsNumpy.py ├── ValidateYourInstallation.py ├── YourFirstTensorFlowProgram.py ├── clustering.py ├── input_data.py ├── multiplication.py ├── regression.py └── regression_tb.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MultiGPU.py: -------------------------------------------------------------------------------- 1 | # Multi GPU Basic example 2 | # code source: Github (2016) Aymeric Damien: https://github.com/aymericdamien/TensorFlow-Examples 3 | ''' 4 | This tutorial requires your machine to have 2 GPUs 5 | "/cpu:0": The CPU of your machine. 6 | "/gpu:0": The first GPU of your machine 7 | "/gpu:1": The second GPU of your machine 8 | ''' 9 | 10 | import tensorflow as tf 11 | import datetime 12 | 13 | # Processing Units logs 14 | log_device_placement = True 15 | 16 | # num of multiplications to perform 17 | n = 10 18 | 19 | # shape of the matrix 20 | matrix_shape = [10000, 10000] 21 | 22 | 23 | def matpow(M, n): 24 | if n < 1: # Abstract cases where n < 1 25 | return M 26 | else: 27 | return tf.matmul(M, matpow(M, n-1)) 28 | 29 | ''' 30 | Example: compute A^n + B^n on 2 GPUs 31 | Results on 16 cores with 2 NVIDIA K80: 32 | * Only CPU computation time: 0:02:00.965574 33 | * Single GPU computation time: 0:00:24.933976 34 | * Multi GPU (x2) computation time: 0:00:08.771551 35 | ''' 36 | 37 | ''' 38 | Only CPU computing 39 | ''' 40 | with tf.device('/cpu:0'): 41 | # Creates two random matrix with shape (1e4, 1e4) 42 | a = tf.random_normal(matrix_shape) 43 | b = tf.random_normal(matrix_shape) 44 | # Compute A^n and B^n and store in a tensor 45 | r01 = matpow(a, n) 46 | r02 = matpow(b, n) 47 | sum = r01 + r02 # Addition of elements: A^n + B^n 48 | 49 | t1_0 = datetime.datetime.now() 50 | with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess: 51 | # Runs the op. 52 | sess.run(sum) 53 | t2_0 = datetime.datetime.now() 54 | 55 | # Clean the graph to start another computation 56 | tf.reset_default_graph() 57 | 58 | ''' 59 | Single GPU computing 60 | ''' 61 | with tf.device('/gpu:0'): 62 | # Creates two random matrix with shape (1e4, 1e4) 63 | a = tf.random_normal(matrix_shape) 64 | b = tf.random_normal(matrix_shape) 65 | # Compute A^n and B^n and store in a tensor 66 | r01 = matpow(a, n) 67 | r02 = matpow(b, n) 68 | 69 | with tf.device('/cpu:0'): 70 | sum = r01 + r02 # Addition of elements: A^n + B^n 71 | 72 | t1_1 = datetime.datetime.now() 73 | with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess: 74 | # Runs the op. 75 | sess.run(sum) 76 | t2_1 = datetime.datetime.now() 77 | 78 | # Clean the graph to start another computation 79 | tf.reset_default_graph() 80 | 81 | ''' 82 | Multi GPU computing 83 | ''' 84 | # GPU:0 computes A^n 85 | with tf.device('/gpu:0'): 86 | # Create one random matrix with shape (1e4, 1e4) 87 | a = tf.random_normal(matrix_shape) 88 | # Compute A^n and store result in a tensor 89 | r11 = matpow(a, n) 90 | 91 | # GPU:1 computes B^n 92 | with tf.device('/gpu:1'): 93 | # Create one random matrix with shape (1e4, 1e4) 94 | b = tf.random_normal(matrix_shape) 95 | # Compute b^n and store result in a tensor 96 | r12 = matpow(b, n) 97 | 98 | with tf.device('/cpu:0'): 99 | sum = r11 + r12 # Addition of elements: A^n + B^n 100 | 101 | t1_2 = datetime.datetime.now() 102 | with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess: 103 | # Runs the op. 104 | sess.run(sum) 105 | t2_2 = datetime.datetime.now() 106 | 107 | print("Only CPU computation time: " + str(t2_0 - t1_0)) 108 | print("Single GPU computation time: " + str(t2_1 - t1_1)) 109 | print("Multi GPU computation time: " + str(t2_2 - t1_2)) 110 | -------------------------------------------------------------------------------- /MultiLayerNeuralNetworks.py: -------------------------------------------------------------------------------- 1 | import input_data 2 | import tensorflow as tf 3 | 4 | mnist = input_data.read_data_sets('MNIST_data', one_hot=True) 5 | 6 | x = tf.placeholder("float", shape=[None, 784]) 7 | y_ = tf.placeholder("float", shape=[None, 10]) 8 | 9 | x_image = tf.reshape(x, [-1, 28, 28, 1]) 10 | 11 | 12 | def weight_variable(shape): 13 | initial = tf.truncated_normal(shape, stddev=0.1) 14 | return tf.Variable(initial) 15 | 16 | 17 | def bias_variable(shape): 18 | initial = tf.constant(0.1, shape=shape) 19 | return tf.Variable(initial) 20 | 21 | 22 | def conv2d(x, W): 23 | return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 24 | 25 | 26 | def max_pool_2x2(x): 27 | return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 28 | strides=[1, 2, 2, 1], padding='SAME') 29 | 30 | 31 | W_conv1 = weight_variable([5, 5, 1, 32]) 32 | b_conv1 = bias_variable([32]) 33 | 34 | h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 35 | h_pool1 = max_pool_2x2(h_conv1) 36 | 37 | W_conv2 = weight_variable([5, 5, 32, 64]) 38 | b_conv2 = bias_variable([64]) 39 | 40 | h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 41 | h_pool2 = max_pool_2x2(h_conv2) 42 | 43 | W_fc1 = weight_variable([7 * 7 * 64, 1024]) 44 | b_fc1 = bias_variable([1024]) 45 | 46 | h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) 47 | h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 48 | 49 | keep_prob = tf.placeholder("float") 50 | h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 51 | 52 | W_fc2 = weight_variable([1024, 10]) 53 | b_fc2 = bias_variable([10]) 54 | 55 | y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 56 | 57 | cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv)) 58 | train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 59 | correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) 60 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 61 | 62 | sess = tf.Session() 63 | sess.run(tf.global_variables_initializer()) 64 | 65 | for i in range(1000): 66 | batch_xs, batch_ys = mnist.train.next_batch(50) 67 | sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5}) 68 | if i % 10 == 0: 69 | train_accuracy = sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0}) 70 | print("Step %d - Train accuracy %.3f" % (i, train_accuracy)) 71 | 72 | test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}) 73 | print("Test accuracy %.3f" % test_accuracy) 74 | -------------------------------------------------------------------------------- /MultiLayerNeuralNetworks_slim.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://www.tensorflow.org/tutorials/layers 3 | """ 4 | 5 | import input_data 6 | import tensorflow as tf 7 | 8 | mnist = input_data.read_data_sets('MNIST_data', one_hot=True) 9 | 10 | x = tf.placeholder("float", shape=[None, 784]) 11 | y_ = tf.placeholder("float", shape=[None, 10]) 12 | 13 | x_image = tf.reshape(x, [-1, 28, 28, 1]) 14 | 15 | keep_prob = tf.placeholder("float") 16 | 17 | conv1 = tf.layers.conv2d( 18 | inputs=x_image, 19 | filters=32, 20 | kernel_size=[5, 5], 21 | padding="same", 22 | activation=tf.nn.relu) 23 | 24 | # Pooling Layer #1 25 | # First max pooling layer with a 2x2 filter and stride of 2 26 | # Input Tensor Shape: [batch_size, 28, 28, 32] 27 | # Output Tensor Shape: [batch_size, 14, 14, 32] 28 | pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) 29 | 30 | # Convolutional Layer #2 31 | # Computes 64 features using a 5x5 filter. 32 | # Padding is added to preserve width and height. 33 | # Input Tensor Shape: [batch_size, 14, 14, 32] 34 | # Output Tensor Shape: [batch_size, 14, 14, 64] 35 | conv2 = tf.layers.conv2d( 36 | inputs=pool1, 37 | filters=64, 38 | kernel_size=[5, 5], 39 | padding="same", 40 | activation=tf.nn.relu) 41 | 42 | # Pooling Layer #2 43 | # Second max pooling layer with a 2x2 filter and stride of 2 44 | # Input Tensor Shape: [batch_size, 14, 14, 64] 45 | # Output Tensor Shape: [batch_size, 7, 7, 64] 46 | pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) 47 | 48 | # Flatten tensor into a batch of vectors 49 | # Input Tensor Shape: [batch_size, 7, 7, 64] 50 | # Output Tensor Shape: [batch_size, 7 * 7 * 64] 51 | pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) 52 | 53 | # Dense Layer 54 | # Densely connected layer with 1024 neurons 55 | # Input Tensor Shape: [batch_size, 7 * 7 * 64] 56 | # Output Tensor Shape: [batch_size, 1024] 57 | dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) 58 | 59 | # Add dropout operation; 0.6 probability that element will be kept 60 | dropout = tf.layers.dropout( 61 | inputs=dense, rate=keep_prob, training=True) 62 | 63 | # Logits layer 64 | # Input Tensor Shape: [batch_size, 1024] 65 | # Output Tensor Shape: [batch_size, 10] 66 | y_conv = tf.layers.dense(inputs=dropout, units=10) 67 | 68 | cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv)) 69 | train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 70 | correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) 71 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 72 | 73 | sess = tf.Session() 74 | sess.run(tf.global_variables_initializer()) 75 | 76 | for i in range(1000): 77 | batch_xs, batch_ys = mnist.train.next_batch(50) 78 | sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5}) 79 | if i % 10 == 0: 80 | train_accuracy = sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0}) 81 | print("Step %d - Train accuracy %.3f" % (i, train_accuracy)) 82 | 83 | test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}) 84 | print("Test accuracy %.3f" % test_accuracy) 85 | -------------------------------------------------------------------------------- /NumpyExample.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | a = np.zeros((2,2)) 3 | b = np.ones((2,2)) 4 | print "a= ", a 5 | print "b= ", b 6 | print "np.sum(b, axis=1)= " , np.sum(b, axis=1) 7 | print "a.shape= ", a.shape 8 | print "np.reshape(a, (1,4))= ", np.reshape(a, (1,4)) 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Code of the previous [book of TensorFlow](http://wwww.jorditorres.org/TensorFlow) updated for TensorFlow 1.1 2 | 3 | 4 | [![solarized dualmode](http://jorditorres.org/wp-content/uploads/2016/02/TentativeBookCover.png)](#features) 5 | -------------------------------------------------------------------------------- /SingleLayerNeuralNetwork.py: -------------------------------------------------------------------------------- 1 | import input_data 2 | import tensorflow as tf 3 | 4 | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 5 | 6 | x = tf.placeholder("float", [None, 784]) 7 | W = tf.Variable(tf.zeros([784, 10])) 8 | b = tf.Variable(tf.zeros([10])) 9 | matm = tf.matmul(x, W) 10 | y = tf.nn.softmax(tf.matmul(x, W) + b) 11 | y_ = tf.placeholder("float", [None, 10]) 12 | cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) 13 | train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) 14 | 15 | correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) 16 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 17 | 18 | sess = tf.Session() 19 | sess.run(tf.global_variables_initializer()) 20 | 21 | for i in range(1000): 22 | batch_xs, batch_ys = mnist.train.next_batch(100) 23 | sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) 24 | 25 | if i % 10 == 0: 26 | train_accuracy = sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys}) 27 | print("Step %d - Train accuracy %.3f" % (i, train_accuracy)) 28 | 29 | test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}) 30 | print("Test accuracy %.3f" % test_accuracy) 31 | -------------------------------------------------------------------------------- /TensorFlowVsNumpy.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | tf.InteractiveSession() 3 | a = tf.zeros((2,2)) 4 | b = tf.ones((2,2)) 5 | print a.eval() 6 | print b .eval() 7 | print tf.reduce_sum(b, reduction_indices=1).eval() 8 | print a.get_shape() 9 | print tf.reshape(a, (1, 4)).eval() 10 | -------------------------------------------------------------------------------- /ValidateYourInstallation.py: -------------------------------------------------------------------------------- 1 | # to remove warnings saying if you build TensorFlow from source it can be faster on your machine 2 | import os 3 | os.environ['TF_CPP_MIN_LOG_LEVEL']='2' 4 | import tensorflow as tf 5 | 6 | #test 7 | import tensorflow as tf 8 | hello = tf.constant('Hello, TensorFlow!') 9 | sess = tf.Session() 10 | print(sess.run(hello)) 11 | 12 | -------------------------------------------------------------------------------- /YourFirstTensorFlowProgram.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | a = tf.placeholder("float") 4 | b = tf.placeholder("float") 5 | 6 | y = tf.multiply(a, b) 7 | 8 | sess = tf.Session() 9 | 10 | print(sess.run(y, feed_dict={a: 3, b: 3})) 11 | -------------------------------------------------------------------------------- /clustering.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | import pandas as pd 4 | import seaborn as sns 5 | import tensorflow as tf 6 | 7 | num_vectors = 1000 8 | num_clusters = 3 9 | num_steps = 100 10 | vector_values = [] 11 | for i in range(num_vectors): 12 | if np.random.random() > 0.5: 13 | vector_values.append([np.random.normal(0.5, 0.6), 14 | np.random.normal(0.3, 0.9)]) 15 | else: 16 | vector_values.append([np.random.normal(2.5, 0.4), 17 | np.random.normal(0.8, 0.5)]) 18 | df = pd.DataFrame({"x": [v[0] for v in vector_values], 19 | "y": [v[1] for v in vector_values]}) 20 | sns.lmplot("x", "y", data=df, fit_reg=False, size=7) 21 | plt.show() 22 | vectors = tf.constant(vector_values) 23 | centroids = tf.Variable(tf.slice(tf.random_shuffle(vectors), 24 | [0, 0], [num_clusters, -1])) 25 | expanded_vectors = tf.expand_dims(vectors, 0) 26 | expanded_centroids = tf.expand_dims(centroids, 1) 27 | 28 | print(expanded_vectors.get_shape()) 29 | print(expanded_centroids.get_shape()) 30 | 31 | distances = tf.reduce_sum( 32 | tf.square(tf.subtract(expanded_vectors, expanded_centroids)), 2) 33 | assignments = tf.argmin(distances, 0) 34 | 35 | means = tf.concat(axis=0, values=[ 36 | tf.reduce_mean( 37 | tf.gather(vectors, 38 | tf.reshape( 39 | tf.where( 40 | tf.equal(assignments, c) 41 | ), [1, -1]) 42 | ), axis=[1]) 43 | for c in range(num_clusters)]) 44 | 45 | update_centroids = tf.assign(centroids, means) 46 | init_op = tf.global_variables_initializer() 47 | 48 | # with tf.Session('local') as sess: 49 | sess = tf.Session() 50 | sess.run(init_op) 51 | 52 | for step in range(num_steps): 53 | _, centroid_values, assignment_values = sess.run([update_centroids, 54 | centroids, 55 | assignments]) 56 | print("centroids") 57 | print(centroid_values) 58 | 59 | data = {"x": [], "y": [], "cluster": []} 60 | for i in range(len(assignment_values)): 61 | data["x"].append(vector_values[i][0]) 62 | data["y"].append(vector_values[i][1]) 63 | data["cluster"].append(assignment_values[i]) 64 | df = pd.DataFrame(data) 65 | sns.lmplot("x", "y", data=df, 66 | fit_reg=False, size=7, 67 | hue="cluster", legend=False) 68 | plt.show() 69 | -------------------------------------------------------------------------------- /input_data.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | """Functions for downloading and reading MNIST data.""" 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import gzip 22 | import os 23 | import tempfile 24 | 25 | import numpy 26 | from six.moves import urllib 27 | from six.moves import xrange # pylint: disable=redefined-builtin 28 | import tensorflow as tf 29 | from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets -------------------------------------------------------------------------------- /multiplication.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | 3 | a = tf.placeholder("float") 4 | b = tf.placeholder("float") 5 | 6 | y = tf.multiply(a, b) 7 | 8 | sess = tf.Session() 9 | 10 | print(sess.run(y, feed_dict={a: 3, b: 3})) 11 | -------------------------------------------------------------------------------- /regression.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | num_puntos = 100 4 | conjunto_puntos = [] 5 | for i in range(num_puntos): 6 | x1 = np.random.normal(0.0, 0.9) 7 | y1 = x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.05) 8 | conjunto_puntos.append([x1, y1]) 9 | 10 | x_data = [v[0] for v in conjunto_puntos] 11 | y_data = [v[1] for v in conjunto_puntos] 12 | 13 | import matplotlib.pyplot as plt 14 | 15 | # Graphic display 16 | plt.plot(x_data, y_data, 'ro') 17 | plt.legend() 18 | plt.show() 19 | 20 | import tensorflow as tf 21 | 22 | W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) 23 | b = tf.Variable(tf.zeros([1])) 24 | y = W * x_data + b 25 | 26 | loss = tf.reduce_mean(tf.square(y - y_data)) 27 | optimizer = tf.train.GradientDescentOptimizer(0.5) 28 | train = optimizer.minimize(loss) 29 | 30 | init = tf.global_variables_initializer() 31 | 32 | sess = tf.Session() 33 | sess.run(init) 34 | 35 | for step in range(101): 36 | sess.run(train) 37 | if step % 10 == 0: 38 | print(step, sess.run(W), sess.run(b)) 39 | 40 | plt.plot(x_data, y_data, 'ro') 41 | plt.plot(x_data, sess.run(W) * x_data + sess.run(b)) 42 | plt.legend() 43 | plt.show() 44 | -------------------------------------------------------------------------------- /regression_tb.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tensorflow as tf 3 | 4 | 5 | tf.set_random_seed(1234) 6 | 7 | with tf.name_scope('data'): 8 | with tf.name_scope('x'): 9 | x = tf.random_normal([100], mean=0.0, stddev=0.9, name='rand_normal_x') 10 | with tf.name_scope('y'): 11 | y_true = x * tf.constant(0.1, name='real_slope') + tf.constant(0.3, name='bias') + tf.random_normal([100], mean=0.0, stddev=0.05, name='rand_normal_y') 12 | 13 | with tf.name_scope('W'): 14 | W = tf.Variable(tf.random_uniform([], minval=-1.0, maxval=1.0)) 15 | tf.summary.scalar('function/W', W) 16 | 17 | with tf.name_scope('b'): 18 | b = tf.Variable(tf.zeros([])) 19 | tf.summary.scalar('function/b', b) 20 | 21 | with tf.name_scope('function'): 22 | y_pred = W * x + b 23 | 24 | 25 | with tf.name_scope('error'): 26 | loss = tf.reduce_mean(tf.square(y_pred - y_true)) 27 | tf.summary.scalar('error', loss) 28 | 29 | with tf.name_scope('train'): 30 | optimizer = tf.train.GradientDescentOptimizer(0.05) 31 | train = optimizer.minimize(loss) 32 | 33 | init = tf.global_variables_initializer() 34 | 35 | sess = tf.Session() 36 | 37 | merged = tf.summary.merge_all() 38 | writer = tf.summary.FileWriter('/tmp/regression/run1', sess.graph) 39 | 40 | sess.run(init) 41 | 42 | for step in range(1, 101): 43 | _, summary_str, slope, intercept, error = sess.run([train, merged, W, b, loss]) 44 | if step % 10 == 0: 45 | writer.add_summary(summary_str, step) 46 | print('Step %.3d: W = %.5f; b = %.5f; loss = %.5f' % (step, slope, intercept, error)) --------------------------------------------------------------------------------