<jupyter_start><jupyter_text>![book](https://raw.githubusercontent.com/ageron/tensorflow-safari-course/master/images/intro_to_tf_course.png) This Jupyter notebook accompanies my [Introduction to TensorFlow](https://www.safaribooksonline.com/live-training/courses/introduction-to-tensorflow/0636920079521/) live online training. It contains the code examples shown in the presentation, as well as the exercises and their solutions.**Try not to peek at the solutions when you go through the exercises. ;-)** First let's make sure this notebook works well in both Python 2 and Python 3:<jupyter_code>from __future__ import absolute_import, division, print_function, unicode_literals<jupyter_output><empty_output><jupyter_text>TensorFlow basics<jupyter_code>import tensorflow as tf
tf.__version__<jupyter_output><empty_output><jupyter_text>Construction Phase<jupyter_code>>>> a = tf.constant(3)
>>> b = tf.constant(5)
>>> s = a + b
a
b
s
tf.get_default_graph()
>>> graph = tf.Graph()
>>> with graph.as_default():
...     a = tf.constant(3)
...     b = tf.constant(5)
...     s = a + b
...<jupyter_output><empty_output><jupyter_text>Execution Phase<jupyter_code>>>> with tf.Session(graph=graph) as sess:
...     result = s.eval()
...
>>> result
>>> with tf.Session(graph=graph) as sess:
...     result = sess.run(s)
...
>>> result
>>> with tf.Session(graph=graph) as sess:
...     result = sess.run([a,b,s])
...
>>> result<jupyter_output><empty_output><jupyter_text>Exercise 1 ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) 1.1) Create a simple graph that calculates $ c = \exp(\sqrt 8 + 3) $.**Tip**: TensorFlow's API documentation is available at:https://www.tensorflow.org/versions/master/api_docs/python/ 1.2) Now create a `Session()` and evaluate the operation that gives you the result of the equation above: 1.3) Create a graph that evaluates and prints both $ b = \sqrt 8 $ and $ c = \exp(\sqrt 8 + 3) $. Try to implement this in a way that only evaluates $ \sqrt 8 $ once. 1.4) The following code is needed to display TensorFlow graphs in Jupyter. Just run this cell then visualize your graph by calling `show_graph(`_your graph_`)`:<jupyter_code>import numpy as np
from IPython.display import display, HTML

def strip_consts(graph_def, max_const_size=32):
    """Strip large constant values from graph_def."""
    strip_def = tf.GraphDef()
    for n0 in graph_def.node:
        n = strip_def.node.add() 
        n.MergeFrom(n0)
        if n.op == 'Const':
            tensor = n.attr['value'].tensor
            size = len(tensor.tensor_content)
            if size > max_const_size:
                tensor.tensor_content = b"<stripped %d bytes>"%size
    return strip_def

def show_graph(graph_def=None, max_const_size=32):
    """Visualize TensorFlow graph."""
    graph_def = graph_def or tf.get_default_graph()
    if hasattr(graph_def, 'as_graph_def'):
        graph_def = graph_def.as_graph_def()
    strip_def = strip_consts(graph_def, max_const_size=max_const_size)
    code = """
        <script>
          function load() {{
            document.getElementById("{id}").pbtxt = {data};
          }}
        </script>
        <link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
        <div style="height:600px">
          <tf-graph-basic id="{id}"></tf-graph-basic>
        </div>
    """.format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))

    iframe = """
        <iframe seamless style="width:1200px;height:620px;border:0" srcdoc="{}"></iframe>
    """.format(code.replace('"', '&quot;'))
    display(HTML(iframe))<jupyter_output><empty_output><jupyter_text>Try not to peek at the solution below before you have done the exercise! :) ![thinking](https://upload.wikimedia.org/wikipedia/commons/0/06/Filos_segundo_logo_%28flipped%29.jpg)  Exercise 1 - Solution 1.1)<jupyter_code>graph = tf.Graph()
with graph.as_default():
    c = tf.exp(tf.sqrt(tf.constant(8.)) + tf.constant(3.))
    # or simply...
    c = tf.exp(tf.sqrt(8.) + 3.)<jupyter_output><empty_output><jupyter_text>1.2)<jupyter_code>with tf.Session(graph=graph):
    c_val = c.eval()
c_val<jupyter_output><empty_output><jupyter_text>1.3)<jupyter_code>graph = tf.Graph()
with graph.as_default():
    b = tf.sqrt(8.)
    c = tf.exp(b + 3)
with tf.Session(graph=graph) as sess:
    b_val, c_val = sess.run([b, c])
b_val
c_val<jupyter_output><empty_output><jupyter_text>**Important**: the following implementation gives the right result, but it runs the graph twice, once to evaluate `b`, and once to evaluate `c`.  Since `c` depends on `b`, it means that `b` will be evaluated twice. Not what we wanted.<jupyter_code># WRONG!
with tf.Session(graph=graph):
    b_val = b.eval()  # evaluates b
    c_val = c.eval()  # evaluates c, which means evaluating b again!
b_val
c_val<jupyter_output><empty_output><jupyter_text>1.4)<jupyter_code>show_graph(graph)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1436944219886823, 'fraction_numerical': 0.019401778496362168, 'mean_word_length': 4.165970772442589, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 85, 'https://': 6, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '264203', 'license': 'Apache-2.0', 'n_tokens_mistral': 1759, 'n_tokens_neox': 1665, 'n_words': 399, 'path': '01_basics_phases_ex1.ipynb', 'repo_name': 'suryapa1/introduction-to-tensorflow', 'size': '4948'}