aymericdamien 9 år sedan
förälder
incheckning
d4bce7088c

+ 16 - 11
README.md

@@ -1,25 +1,25 @@
 # TensorFlow Examples
-Basic code examples for some machine learning algorithms, using TensorFlow library.
+Code examples for some popular machine learning algorithms, using TensorFlow library. Both code and notebook are available.
 
 ## Tutorial index
 
 #### 1 - Introduction
-- Hello World ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/helloworld.py))
-- Basic Operations ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/basic_operations.py))
+- Hello World ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/1%20-%20Introduction/helloworld.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/1%20-%20Introduction/helloworld.py))
+- Basic Operations ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/1%20-%20Introduction/basic_operations.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/1%20-%20Introduction/basic_operations.py))
 
 #### 2 - Basic Classifiers
-- Nearest Neighbor ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/nearest_neighbor.py))
-- Linear Regression ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/linear_regression.py))
-- Logistic Regression ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/logistic_regression.py))
+- Nearest Neighbor ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/2%20-%20Basic%20Classifiers/nearest_neighbor.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2%20-%20Basic%20Classifiers/nearest_neighbor.py))
+- Linear Regression ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/2%20-%20Basic%20Classifiers/linear_regression.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2%20-%20Basic%20Classifiers/linear_regression.py))
+- Logistic Regression ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/2%20-%20Basic%20Classifiers/logistic_regression.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2%20-%20Basic%20Classifiers/logistic_regression.py))
 
 #### 3 - Neural Networks
-- Multilayer Perceptron ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/multilayer_perceptron.py))
-- Convolutional Neural Network ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/convolutional_network.py))
-- AlexNet ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/alexnet.py))
-- Reccurent Network ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/recurrent_network.py))
+- Multilayer Perceptron ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3%20-%20Neural%20Networks/multilayer_perceptron.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/multilayer_perceptron.py))
+- Convolutional Neural Network ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3%20-%20Neural%20Networks/convolutional_network.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/convolutional_network.py))
+- AlexNet ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/3%20-%20Neural%20Networks/alexnet.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/alexnet.py))
+- Reccurent Network ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/recurrent_network.py))
 
 ### 4 - Multi GPU
-- Basic Operations on multi-GPU ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/multigpu_basics.py))
+- Basic Operations on multi-GPU ([notebook](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/4%20-%20Multi%20GPU/multigpu_basics.py)) ([code](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/4%20-%20Multi%20GPU/multigpu_basics.py))
 
 ## Dependencies
 ```
@@ -28,5 +28,10 @@ numpy
 matplotlib
 cuda (to run examples on GPU)
 ```
+For more details about TensorFlow installation, you can check [Setup_TensorFlow.md](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/Setup_TensorFlow.md)
+
+## Dataset
+Some examples require MNIST dataset for training and testing. Don't worry, this dataset will automatically be downloaded when running examples (with input_data.py).
+MNIST is a database of handwritten digits, with 60,000 examples for training and 10,000 examples for testing. (Website: [http://yann.lecun.com/exdb/mnist/](http://yann.lecun.com/exdb/mnist/))
 
 _Other tutorials are coming soon..._

+ 7 - 1
examples/4 - Multi GPU/multigpu_basics.py

@@ -1,4 +1,10 @@
-#Multi GPU Basic example
+'''
+Basic Multi GPU computation example using TensorFlow library.
+
+Author: Aymeric Damien
+Project: https://github.com/aymericdamien/TensorFlow-Examples/
+'''
+
 '''
 This tutorial requires your machine to have 2 GPUs
 "/cpu:0": The CPU of your machine.

+ 348 - 0
notebooks/3 - Neural Networks/alexnet.ipynb

@@ -0,0 +1,348 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 1,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# AlexNet implementation example using TensorFlow library.\n",
+    "# This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)\n",
+    "# AlexNet Paper (http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)\n",
+    "\n",
+    "# Author: Aymeric Damien\n",
+    "# Project: https://github.com/aymericdamien/TensorFlow-Examples/"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 2,
+   "metadata": {
+    "collapsed": false
+   },
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "Extracting /tmp/data/train-images-idx3-ubyte.gz\n",
+      "Extracting /tmp/data/train-labels-idx1-ubyte.gz\n",
+      "Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n",
+      "Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n"
+     ]
+    }
+   ],
+   "source": [
+    "# Import MINST data\n",
+    "import input_data\n",
+    "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 3,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "import tensorflow as tf"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 17,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Parameters\n",
+    "learning_rate = 0.001\n",
+    "training_iters = 300000\n",
+    "batch_size = 64\n",
+    "display_step = 100"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 5,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Network Parameters\n",
+    "n_input = 784 # MNIST data input (img shape: 28*28)\n",
+    "n_classes = 10 # MNIST total classes (0-9 digits)\n",
+    "dropout = 0.8 # Dropout, probability to keep units"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 6,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# tf Graph input\n",
+    "x = tf.placeholder(tf.types.float32, [None, n_input])\n",
+    "y = tf.placeholder(tf.types.float32, [None, n_classes])\n",
+    "keep_prob = tf.placeholder(tf.types.float32) # dropout (keep probability)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 7,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Create AlexNet model\n",
+    "def conv2d(name, l_input, w, b):\n",
+    "    return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, 1, 1, 1], \n",
+    "                                                  padding='SAME'),b), name=name)\n",
+    "\n",
+    "def max_pool(name, l_input, k):\n",
+    "    return tf.nn.max_pool(l_input, ksize=[1, k, k, 1], strides=[1, k, k, 1], \n",
+    "                          padding='SAME', name=name)\n",
+    "\n",
+    "def norm(name, l_input, lsize=4):\n",
+    "    return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=name)\n",
+    "\n",
+    "def alex_net(_X, _weights, _biases, _dropout):\n",
+    "    # Reshape input picture\n",
+    "    _X = tf.reshape(_X, shape=[-1, 28, 28, 1])\n",
+    "\n",
+    "    # Convolution Layer\n",
+    "    conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'])\n",
+    "    # Max Pooling (down-sampling)\n",
+    "    pool1 = max_pool('pool1', conv1, k=2)\n",
+    "    # Apply Normalization\n",
+    "    norm1 = norm('norm1', pool1, lsize=4)\n",
+    "    # Apply Dropout\n",
+    "    norm1 = tf.nn.dropout(norm1, _dropout)\n",
+    "\n",
+    "    # Convolution Layer\n",
+    "    conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'])\n",
+    "    # Max Pooling (down-sampling)\n",
+    "    pool2 = max_pool('pool2', conv2, k=2)\n",
+    "    # Apply Normalization\n",
+    "    norm2 = norm('norm2', pool2, lsize=4)\n",
+    "    # Apply Dropout\n",
+    "    norm2 = tf.nn.dropout(norm2, _dropout)\n",
+    "\n",
+    "    # Convolution Layer\n",
+    "    conv3 = conv2d('conv3', norm2, _weights['wc3'], _biases['bc3'])\n",
+    "    # Max Pooling (down-sampling)\n",
+    "    pool3 = max_pool('pool3', conv3, k=2)\n",
+    "    # Apply Normalization\n",
+    "    norm3 = norm('norm3', pool3, lsize=4)\n",
+    "    # Apply Dropout\n",
+    "    norm3 = tf.nn.dropout(norm3, _dropout)\n",
+    "\n",
+    "    # Fully connected layer\n",
+    "    # Reshape conv3 output to fit dense layer input\n",
+    "    dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]]) \n",
+    "    # Relu activation\n",
+    "    dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc1')\n",
+    "    \n",
+    "    # Relu activation\n",
+    "    dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc2') \n",
+    "\n",
+    "    # Output, class prediction\n",
+    "    out = tf.matmul(dense2, _weights['out']) + _biases['out']\n",
+    "    return out"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 8,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Store layers weight & bias\n",
+    "weights = {\n",
+    "    'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64])),\n",
+    "    'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128])),\n",
+    "    'wc3': tf.Variable(tf.random_normal([3, 3, 128, 256])),\n",
+    "    'wd1': tf.Variable(tf.random_normal([4*4*256, 1024])),\n",
+    "    'wd2': tf.Variable(tf.random_normal([1024, 1024])),\n",
+    "    'out': tf.Variable(tf.random_normal([1024, 10]))\n",
+    "}\n",
+    "biases = {\n",
+    "    'bc1': tf.Variable(tf.random_normal([64])),\n",
+    "    'bc2': tf.Variable(tf.random_normal([128])),\n",
+    "    'bc3': tf.Variable(tf.random_normal([256])),\n",
+    "    'bd1': tf.Variable(tf.random_normal([1024])),\n",
+    "    'bd2': tf.Variable(tf.random_normal([1024])),\n",
+    "    'out': tf.Variable(tf.random_normal([n_classes]))\n",
+    "}"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 9,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Construct model\n",
+    "pred = alex_net(x, weights, biases, keep_prob)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 10,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Define loss and optimizer\n",
+    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))\n",
+    "optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 11,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Evaluate model\n",
+    "correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))\n",
+    "accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.types.float32))"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 12,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Initializing the variables\n",
+    "init = tf.initialize_all_variables()"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 18,
+   "metadata": {
+    "collapsed": false
+   },
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "Iter 6400, Minibatch Loss= 29666.185547, Training Accuracy= 0.59375\n",
+      "Iter 12800, Minibatch Loss= 22125.562500, Training Accuracy= 0.60938\n",
+      "Iter 19200, Minibatch Loss= 22631.134766, Training Accuracy= 0.59375\n",
+      "Iter 25600, Minibatch Loss= 18498.414062, Training Accuracy= 0.62500\n",
+      "Iter 32000, Minibatch Loss= 11318.283203, Training Accuracy= 0.70312\n",
+      "Iter 38400, Minibatch Loss= 12076.280273, Training Accuracy= 0.70312\n",
+      "Iter 44800, Minibatch Loss= 8195.520508, Training Accuracy= 0.82812\n",
+      "Iter 51200, Minibatch Loss= 5176.181641, Training Accuracy= 0.84375\n",
+      "Iter 57600, Minibatch Loss= 8951.896484, Training Accuracy= 0.81250\n",
+      "Iter 64000, Minibatch Loss= 10096.946289, Training Accuracy= 0.78125\n",
+      "Iter 70400, Minibatch Loss= 11466.641602, Training Accuracy= 0.68750\n",
+      "Iter 76800, Minibatch Loss= 7469.824219, Training Accuracy= 0.78125\n",
+      "Iter 83200, Minibatch Loss= 4147.449219, Training Accuracy= 0.89062\n",
+      "Iter 89600, Minibatch Loss= 5904.782227, Training Accuracy= 0.82812\n",
+      "Iter 96000, Minibatch Loss= 718.493713, Training Accuracy= 0.93750\n",
+      "Iter 102400, Minibatch Loss= 2184.151367, Training Accuracy= 0.93750\n",
+      "Iter 108800, Minibatch Loss= 2354.463135, Training Accuracy= 0.89062\n",
+      "Iter 115200, Minibatch Loss= 8612.959961, Training Accuracy= 0.81250\n",
+      "Iter 121600, Minibatch Loss= 2225.773926, Training Accuracy= 0.84375\n",
+      "Iter 128000, Minibatch Loss= 160.583618, Training Accuracy= 0.96875\n",
+      "Iter 134400, Minibatch Loss= 1524.846069, Training Accuracy= 0.93750\n",
+      "Iter 140800, Minibatch Loss= 3501.871094, Training Accuracy= 0.89062\n",
+      "Iter 147200, Minibatch Loss= 661.977051, Training Accuracy= 0.96875\n",
+      "Iter 153600, Minibatch Loss= 367.857788, Training Accuracy= 0.98438\n",
+      "Iter 160000, Minibatch Loss= 1735.458740, Training Accuracy= 0.90625\n",
+      "Iter 166400, Minibatch Loss= 209.320374, Training Accuracy= 0.95312\n",
+      "Iter 172800, Minibatch Loss= 1788.553955, Training Accuracy= 0.90625\n",
+      "Iter 179200, Minibatch Loss= 912.995544, Training Accuracy= 0.93750\n",
+      "Iter 185600, Minibatch Loss= 2534.074463, Training Accuracy= 0.87500\n",
+      "Iter 192000, Minibatch Loss= 73.052612, Training Accuracy= 0.96875\n",
+      "Iter 198400, Minibatch Loss= 1609.606323, Training Accuracy= 0.93750\n",
+      "Iter 204800, Minibatch Loss= 1823.219727, Training Accuracy= 0.96875\n",
+      "Iter 211200, Minibatch Loss= 578.051086, Training Accuracy= 0.96875\n",
+      "Iter 217600, Minibatch Loss= 1532.326172, Training Accuracy= 0.89062\n",
+      "Iter 224000, Minibatch Loss= 769.775269, Training Accuracy= 0.95312\n",
+      "Iter 230400, Minibatch Loss= 2614.737793, Training Accuracy= 0.92188\n",
+      "Iter 236800, Minibatch Loss= 938.664368, Training Accuracy= 0.95312\n",
+      "Iter 243200, Minibatch Loss= 1520.495605, Training Accuracy= 0.93750\n",
+      "Iter 249600, Minibatch Loss= 657.419739, Training Accuracy= 0.95312\n",
+      "Iter 256000, Minibatch Loss= 522.802124, Training Accuracy= 0.90625\n",
+      "Iter 262400, Minibatch Loss= 211.188477, Training Accuracy= 0.96875\n",
+      "Iter 268800, Minibatch Loss= 520.451172, Training Accuracy= 0.92188\n",
+      "Iter 275200, Minibatch Loss= 1418.759155, Training Accuracy= 0.89062\n",
+      "Iter 281600, Minibatch Loss= 241.748596, Training Accuracy= 0.96875\n",
+      "Iter 288000, Minibatch Loss= 0.000000, Training Accuracy= 1.00000\n",
+      "Iter 294400, Minibatch Loss= 1535.772827, Training Accuracy= 0.92188\n",
+      "Optimization Finished!\n",
+      "Testing Accuracy: 0.980469\n"
+     ]
+    }
+   ],
+   "source": [
+    "# Launch the graph\n",
+    "with tf.Session() as sess:\n",
+    "    sess.run(init)\n",
+    "    step = 1\n",
+    "    # Keep training until reach max iterations\n",
+    "    while step * batch_size < training_iters:\n",
+    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
+    "        # Fit training using batch data\n",
+    "        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout})\n",
+    "        if step % display_step == 0:\n",
+    "            # Calculate batch accuracy\n",
+    "            acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})\n",
+    "            # Calculate batch loss\n",
+    "            loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})\n",
+    "            print \"Iter \" + str(step*batch_size) + \", Minibatch Loss= \" \\\n",
+    "                  + \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \"{:.5f}\".format(acc)\n",
+    "        step += 1\n",
+    "    print \"Optimization Finished!\"\n",
+    "    # Calculate accuracy for 256 mnist test images\n",
+    "    print \"Testing Accuracy:\", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], \n",
+    "                                                             y: mnist.test.labels[:256], \n",
+    "                                                             keep_prob: 1.})"
+   ]
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "IPython (Python 2.7)",
+   "language": "python",
+   "name": "python2"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 2
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython2",
+   "version": "2.7.8"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}

+ 176 - 0
notebooks/4 - Multi GPU/multigpu_basics.ipynb

@@ -0,0 +1,176 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 1,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Basic Multi GPU computation example using TensorFlow library.\n",
+    "\n",
+    "# Author: Aymeric Damien\n",
+    "# Project: https://github.com/aymericdamien/TensorFlow-Examples/\n",
+    "\n",
+    "# This tutorial requires your machine to have 2 GPUs\n",
+    "# \"/cpu:0\": The CPU of your machine.\n",
+    "# \"/gpu:0\": The first GPU of your machine\n",
+    "# \"/gpu:1\": The second GPU of your machine"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 2,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "import numpy as np\n",
+    "import tensorflow as tf\n",
+    "import datetime"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 3,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "#Processing Units logs\n",
+    "log_device_placement = True\n",
+    "\n",
+    "#num of multiplications to perform\n",
+    "n = 10"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "metadata": {
+    "collapsed": false
+   },
+   "outputs": [],
+   "source": [
+    "# Example: compute A^n + B^n on 2 GPUs\n",
+    "\n",
+    "# Create random large matrix\n",
+    "A = np.random.rand(1e4, 1e4).astype('float32')\n",
+    "B = np.random.rand(1e4, 1e4).astype('float32')\n",
+    "\n",
+    "# Creates a graph to store results\n",
+    "c1 = []\n",
+    "c2 = []\n",
+    "\n",
+    "# Define matrix power\n",
+    "def matpow(M, n):\n",
+    "    if n < 1: #Abstract cases where n < 1\n",
+    "        return M\n",
+    "    else:\n",
+    "        return tf.matmul(M, matpow(M, n-1))"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 6,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Single GPU computing\n",
+    "\n",
+    "with tf.device('/gpu:0'):\n",
+    "    a = tf.constant(A)\n",
+    "    b = tf.constant(B)\n",
+    "    #compute A^n and B^n and store results in c1\n",
+    "    c1.append(matpow(a, n))\n",
+    "    c1.append(matpow(b, n))\n",
+    "\n",
+    "with tf.device('/cpu:0'):\n",
+    "  sum = tf.add_n(c1) #Addition of all elements in c1, i.e. A^n + B^n\n",
+    "\n",
+    "t1_1 = datetime.datetime.now()\n",
+    "with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess:\n",
+    "    # Runs the op.\n",
+    "    sess.run(sum)\n",
+    "t2_1 = datetime.datetime.now()"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 7,
+   "metadata": {
+    "collapsed": true
+   },
+   "outputs": [],
+   "source": [
+    "# Multi GPU computing\n",
+    "# GPU:0 computes A^n\n",
+    "with tf.device('/gpu:0'):\n",
+    "    #compute A^n and store result in c2\n",
+    "    a = tf.constant(A)\n",
+    "    c2.append(matpow(a, n))\n",
+    "\n",
+    "#GPU:1 computes B^n\n",
+    "with tf.device('/gpu:1'):\n",
+    "    #compute B^n and store result in c2\n",
+    "    b = tf.constant(B)\n",
+    "    c2.append(matpow(b, n))\n",
+    "\n",
+    "with tf.device('/cpu:0'):\n",
+    "  sum = tf.add_n(c2) #Addition of all elements in c2, i.e. A^n + B^n\n",
+    "\n",
+    "t1_2 = datetime.datetime.now()\n",
+    "with tf.Session(config=tf.ConfigProto(log_device_placement=log_device_placement)) as sess:\n",
+    "    # Runs the op.\n",
+    "    sess.run(sum)\n",
+    "t2_2 = datetime.datetime.now()"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 8,
+   "metadata": {
+    "collapsed": false
+   },
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "Single GPU computation time: 0:00:11.833497\n",
+      "Multi GPU computation time: 0:00:07.085913\n"
+     ]
+    }
+   ],
+   "source": [
+    "print \"Single GPU computation time: \" + str(t2_1-t1_1)\n",
+    "print \"Multi GPU computation time: \" + str(t2_2-t1_2)"
+   ]
+  },
+ "metadata": {
+  "kernelspec": {
+   "display_name": "Python 2",
+   "language": "python",
+   "name": "python2"
+  },
+  "language_info": {
+   "codemirror_mode": {
+    "name": "ipython",
+    "version": 2
+   },
+   "file_extension": ".py",
+   "mimetype": "text/x-python",
+   "name": "python",
+   "nbconvert_exporter": "python",
+   "pygments_lexer": "ipython2",
+   "version": "2.7.10"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}