Premiers pas avec Tensorflow 1

machine-learning

Dans cet article, les (mes) premiers pas pour prendre en main Tensorflow (1.15): installation, "hello world", quelques opérations arithmétiques de base et introduction aux, j'espère, principaux concepts et composants de Tensorflow.

Untitled

Nous allons:

  • installer localement Tensorflow
  • voir les concepts et composants de base liés à Tensorflow
  • éxécuter et décortiquer un "hello world"
  • éxécuter et décortiquer des opérations arithmétiques de base
  • voir les placeholders et variables
  • manipuler rapidement Tensorboard

Installation de Tensorflow

Pour ma part je suis en train de monter en compétence sur ce framework, et pour le moment,je suis très satisfait de cette procédure d'installation fournie par tensorflow.org et jouer avec l'outil en ligne de commande ou via des script python édités sous Vim. Cela changera certainement en m'attaquant à des exemples plus sophistoqués. Il y aura alors peut-être de nouveaux articles à ce moment.

Pour le reste de l'article, j'utiliserais un notebook Jupyter, et pour être honnête, l'installation a été un peu plus compliqué et je ne me souviens plus des détails. Je n'ai pas non plus envie de casser mon installation courante: pour suivre certains tutos, j'avais besoin d'une version spécifique de Keras avec tensorflow 1.13, j'ai effectué les installations via conda, mais pour le coup n'étant pas un wizard de Python, et étant habitué à Java et Maven, c'était juste très pénible.

foo@bar: virtualenv --no-site-packages tf-venv
foo@bar: source ./tf-venv/bin/activate
foo@bar: pip install tensorflow==1.15
foo@bar: python -c "import tensorflow; print(tensorflow.__version__)"

Hello World et quelques concepts de base de Tensorflow

Dans cette section, nous allons exécuter un "hello world" et des opérations arithmétiques de base, introduire au passage des concepts et composants de base de Tensorflow, et prendre en main Tensorboard.

In [1]:
import tensorflow as tf
print(tf.__version__)
1.13.1
In [2]:
hello = tf.constant("Hello, world")
with tf.Session() as sess:
    print(sess.run(hello))
b'Hello, world'

Essayons d'expliquer ces 2 lignes de code: Nous avons défini une "Session", qui, comme l'indique la documentation, est un objet encapsulant l'environnement dans lequel des objets de type Operation sont exécutés, et des objets de type Tenseur sont évalués.

Ainsi, on a donc décrit ici un graphe avec une seule "operation", ou noeud, qui est une constante, dont la valeur est "hello world".

image.png

On exécute sess.run() dans un with afin de s'assurer que la session est fermée à la fin du calcul.

Les opérations dans Tensorflow sont donc décrites sous la forme d'un graphe de calcul, où les noeuds sont les opérations et les données circulant entre les noeuds sont des tenseurs, d'où Tensorflow (malin Google).

On décrit le graphe de calcul simplement en créant des opérations.

On crée une Session pour effectuer un calcul, calcul qui sera déclenché via la commande sess.run($nom_du_noeud).

Il est à noter que sess.run() est "lazy", ainsi uniquement les noeuds du graphe qui sont nécessaires au résultat demandé sont éxécutés.

Par exemple, prenons le graphe suivant:

image.png

Que nous pourrions décrire avec les instructions suivantes

In [3]:
a=tf.constant(1)
b=tf.constant(3)
Add = tf.math.add(a,b)

c=tf.constant(5)
Mult = tf.math.multiply(Add,c)

une commande du genre sess.run(Add) n'effectuerait pas l'opération de multiplication:

image.png

In [4]:
with tf.Session() as sess:
    Add_result = sess.run(Add)
    print(Add_result)
4

exécuter l'opération Mult exécute alors l'ensemble du graphe.

image.png

image.png

In [5]:
with tf.Session() as sess:
    Mult_result = sess.run(Mult)
    print(Mult_result)
20

On peut aussi consulter le graphe des opérations via l'outil Tensorboard. Inspectons le graphe ci-dessus des opérations arithmétiques dans Tensorboard

In [7]:
writer=tf.summary.FileWriter('toto', tf.get_default_graph()) 
writer.close()
In [8]:
!tensorboard --logdir="toto"
TensorBoard 1.13.1 at http://joseph-ThinkPad-T480:6006 (Press CTRL+C to quit)
I0114 05:47:10.838987 140575365723904 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:10] "GET / HTTP/1.1" 200 -
I0114 05:47:10.977563 140575365723904 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:10] "GET /tf-interactive-inference-dashboard/editedexample.png HTTP/1.1" 200 -
I0114 05:47:10.978560 140575407671040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:10] "GET /tf-interactive-inference-dashboard/distance.png HTTP/1.1" 200 -
I0114 05:47:10.979344 140575516727040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:10] "GET /tf-interactive-inference-dashboard/explorecounterfactuals.png HTTP/1.1" 200 -
I0114 05:47:10.980227 140574700857088 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:10] "GET /tf-interactive-inference-dashboard/pdplots.png HTTP/1.1" 200 -
I0114 05:47:11.227873 140575407671040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:11] "GET /font-roboto/oMMgfZMQthOryQo9n22dcuvvDin1pK8aKteLpeZ5c0A.woff2 HTTP/1.1" 200 -
I0114 05:47:11.833554 140574700857088 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:11] "GET /data/runs HTTP/1.1" 200 -
I0114 05:47:11.833780 140575365723904 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:11] "GET /data/experiments HTTP/1.1" 200 -
I0114 05:47:11.834233 140575516727040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:11] "GET /data/environment HTTP/1.1" 200 -
I0114 05:47:11.835901 140575407671040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:11] "GET /data/plugins_listing HTTP/1.1" 200 -
I0114 05:47:11.856652 140575407671040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:11] "GET /font-roboto/RxZJdnzeo3R5zSexge8UUZBw1xU1rKptJj_0jans920.woff2 HTTP/1.1" 200 -
I0114 05:47:11.994559 140575407671040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:11] "GET /data/plugins_listing HTTP/1.1" 200 -
I0114 05:47:12.104041 140575407671040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:12] "GET /data/plugin/graphs/runs HTTP/1.1" 200 -
I0114 05:47:12.104774 140575516727040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:12] "GET /data/plugin/graphs/run_metadata_tags HTTP/1.1" 200 -
I0114 05:47:12.270431 140575407671040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:12] "GET /data/plugin/graphs/graph?run=.&limit_attr_size=1024&large_attrs_key=_too_large_attrs HTTP/1.1" 200 -
I0114 05:47:12.678438 140575407671040 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:47:12] "GET /data/plugins_listing HTTP/1.1" 200 -
^C

Intéressant de voir que l'on peut démarrer tensorboard depuis un notebook Jupyter :) !

Voici ce que l'on peut observer à l'url indiquée dans la sortie précédente:

image.png

On peut donc voir le graphe qui a été décrit précédemment. On peut nommer manuellement les noeuds si on le souhaite

In [10]:
a=tf.constant(1, name="a")
b=tf.constant(3, name="b")
Add = tf.math.add(a,b)

c=tf.constant(5)
Mult = tf.math.multiply(Add,c)

writer=tf.summary.FileWriter('toto', tf.get_default_graph()) 
writer.close()
In [11]:
!tensorboard --logdir="toto"
W0114 05:52:20.973693 139813787256576 plugin_event_accumulator.py:294] Found more than one graph event per run, or there was a metagraph containing a graph_def, as well as one or more graph events.  Overwriting the graph with the newest event.
W0114 05:52:20.973854 139813787256576 plugin_event_accumulator.py:302] Found more than one metagraph event per run. Overwriting the metagraph with the newest event.
TensorBoard 1.13.1 at http://joseph-ThinkPad-T480:6006 (Press CTRL+C to quit)
I0114 05:52:32.049096 139813795649280 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:32] "GET / HTTP/1.1" 200 -
I0114 05:52:32.977031 139813795649280 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:32] "GET /tf-interactive-inference-dashboard/editedexample.png HTTP/1.1" 200 -
I0114 05:52:32.977891 139813804041984 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:32] "GET /tf-interactive-inference-dashboard/distance.png HTTP/1.1" 200 -
I0114 05:52:32.978822 139813812434688 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:32] "GET /tf-interactive-inference-dashboard/explorecounterfactuals.png HTTP/1.1" 200 -
I0114 05:52:32.979836 139813013608192 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:32] "GET /tf-interactive-inference-dashboard/pdplots.png HTTP/1.1" 200 -
I0114 05:52:33.093799 139813812434688 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:33] "GET /data/environment HTTP/1.1" 200 -
I0114 05:52:33.094067 139813013608192 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:33] "GET /data/runs HTTP/1.1" 200 -
I0114 05:52:33.094769 139813795649280 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:33] "GET /data/experiments HTTP/1.1" 200 -
I0114 05:52:33.096251 139813804041984 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:33] "GET /data/plugins_listing HTTP/1.1" 200 -
I0114 05:52:33.282669 139813804041984 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:33] "GET /data/plugins_listing HTTP/1.1" 200 -
I0114 05:52:33.405052 139813804041984 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:33] "GET /data/plugin/graphs/runs HTTP/1.1" 200 -
I0114 05:52:33.405664 139813812434688 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:33] "GET /data/plugin/graphs/run_metadata_tags HTTP/1.1" 200 -
I0114 05:52:33.570759 139813804041984 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:33] "GET /data/plugin/graphs/graph?run=.&limit_attr_size=1024&large_attrs_key=_too_large_attrs HTTP/1.1" 200 -
I0114 05:52:34.089674 139813804041984 _internal.py:122] ::ffff:127.0.0.1 - - [14/Jan/2020 05:52:34] "GET /data/plugins_listing HTTP/1.1" 200 -
^C

Il est intéressant de constater la sortie suivante:

W0114 05:52:20.973693 139813787256576 plugin_event_accumulator.py:294] Found more than one graph event per run, or there was a metagraph containing a graph_def, as well as one or more graph events.  Overwriting the graph with the newest event.

En effet, la 2e fois, nous avons écrit le graphe dans le même répertoire que la 1e fois. Voyons ce que donne la sortie:

image.png

Ainsi en écrivant le graphe dans le même répertoire, on peut conserver les données des graphes d'exécutions précédentes.

Intéressant à savoir, voyons à l'avenir si cela est d'une quelconque utilité, ou au contraire si cela est une source d'ennuis.

Placeholders et variables

Examinons 2 nouveaux concepts et composants de base de Tensorflow, les placeholders et les variables.

les placeholders sont l'équivalents des variables final en java. Elles sont initialisées une seule fois, ensuite on ne peut pas modifier leur valeur.

Reprenons notre exemple arithmétique précédent en introduisant des placeholders.

In [29]:
a=tf.constant(1, name="a")
b=tf.placeholder(tf.int32, name="b")
Add = tf.math.add(a,b)

c=tf.constant(5)
Mult = tf.math.multiply(Add,c)

with tf.Session() as sess:
    mult_res = sess.run(Mult)
    print(mult_res)
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1333     try:
-> 1334       return fn(*args)
   1335     except errors.OpError as e:

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1318       return self._call_tf_sessionrun(
-> 1319           options, feed_dict, fetch_list, target_list, run_metadata)
   1320 

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1406         self._session, options, feed_dict, fetch_list, target_list,
-> 1407         run_metadata)
   1408 

InvalidArgumentError: You must feed a value for placeholder tensor 'b_11' with dtype int32
     [[{{node b_11}}]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-29-e26fe1108887> in <module>
      7 
      8 with tf.Session() as sess:
----> 9     mult_res = sess.run(Mult)
     10     print(mult_res)

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1150     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1151       results = self._do_run(handle, final_targets, final_fetches,
-> 1152                              feed_dict_tensor, options, run_metadata)
   1153     else:
   1154       results = []

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1326     if handle is None:
   1327       return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1328                            run_metadata)
   1329     else:
   1330       return self._do_call(_prun_fn, handle, feeds, fetches)

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1346           pass
   1347       message = error_interpolation.interpolate(message, self._graph)
-> 1348       raise type(e)(node_def, op, message)
   1349 
   1350   def _extend_graph(self):

InvalidArgumentError: You must feed a value for placeholder tensor 'b_11' with dtype int32
     [[node b_11 (defined at <ipython-input-29-e26fe1108887>:2) ]]

Caused by op 'b_11', defined at:
  File "/home/joseph/opt/anaconda3/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/joseph/opt/anaconda3/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/traitlets/config/application.py", line 664, in launch_instance
    app.start()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/kernelapp.py", line 563, in start
    self.io_loop.start()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/platform/asyncio.py", line 148, in start
    self.asyncio_loop.run_forever()
  File "/home/joseph/opt/anaconda3/lib/python3.7/asyncio/base_events.py", line 534, in run_forever
    self._run_once()
  File "/home/joseph/opt/anaconda3/lib/python3.7/asyncio/base_events.py", line 1771, in _run_once
    handle._run()
  File "/home/joseph/opt/anaconda3/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/ioloop.py", line 690, in <lambda>
    lambda f: self._run_callback(functools.partial(callback, future))
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/ioloop.py", line 743, in _run_callback
    ret = callback()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 787, in inner
    self.run()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 748, in run
    yielded = self.gen.send(value)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 365, in process_one
    yield gen.maybe_future(dispatch(*args))
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 272, in dispatch_shell
    yield gen.maybe_future(handler(stream, idents, msg))
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 542, in execute_request
    user_expressions, allow_stdin,
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/ipkernel.py", line 294, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/zmqshell.py", line 536, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 2855, in run_cell
    raw_cell, store_history, silent, shell_futures)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 2881, in _run_cell
    return runner(coro)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/async_helpers.py", line 68, in _pseudo_sync_runner
    coro.send(None)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3058, in run_cell_async
    interactivity=interactivity, compiler=compiler, result=result)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3249, in run_ast_nodes
    if (await self.run_code(code, result,  async_=asy)):
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-29-e26fe1108887>", line 2, in <module>
    b=tf.placeholder(tf.int32, name="b")
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py", line 2077, in placeholder
    return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 5791, in placeholder
    "Placeholder", dtype=dtype, shape=shape, name=name)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py", line 788, in _apply_op_helper
    op_def=op_def)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/util/deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 3300, in create_op
    op_def=op_def)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 1801, in __init__
    self._traceback = tf_stack.extract_stack()

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'b_11' with dtype int32
     [[node b_11 (defined at <ipython-input-29-e26fe1108887>:2) ]]

ah, nous avons une erreur, en effet, nous n'avons pas initialisé le placeholder 'b'. Comme en java, si nous avions une varible final non-initialisée, sauf qu'en java on l'aurait su à la compilation, et pour ceux qui utilisent un IDE (qui n'en utilise pas ?!) l'ide nous l'aurait immédiatement signalé et aurait purement et simplement refusé d'exécuter notre code.

On initialise un placeholder dans la commande sess.run(), avec un paramètre feed_dict, qui est un dictionnaire Python classique, dans lequel les clés sont les noms des placeholders, et les valeurs sont les valeurs avec lesquelles ont les initialise.

In [31]:
a=tf.constant(1, name="a")
b=tf.placeholder(tf.int32, name="b")
Add = tf.math.add(a,b)

c=tf.constant(5)
Mult = tf.math.multiply(Add,c)

with tf.Session() as sess:
    mult_res = sess.run(Mult, feed_dict={b:5})
    print(mult_res)
30

Maintenant les variables. Les variables sont des tenseurs (article à venir à ce sujet) mutables, dont la valeur peut changer au cours du temps, contrairement aux constantes et placeholders, et qui sont recalculés à la demande.

In [40]:
a=tf.constant(2, name="a")
b=tf.Variable(1,tf.int32, name="b")

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(5):
        b = tf.math.multiply(a,b)
        print(sess.run(b))
2
4
8
16
32

Il est important d'ajouter la ligne sess.run(tf.global_variables_initializer()), autrement, nous nous retrouverions avec l'erreur suivante Attempting to use uninitialized value:

In [41]:
a=tf.constant(2, name="a")
b=tf.Variable(1,tf.int32, name="b")

with tf.Session() as sess:

    for i in range(5):
        b = tf.math.multiply(a,b)
        print(sess.run(b))
---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1333     try:
-> 1334       return fn(*args)
   1335     except errors.OpError as e:

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1318       return self._call_tf_sessionrun(
-> 1319           options, feed_dict, fetch_list, target_list, run_metadata)
   1320 

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1406         self._session, options, feed_dict, fetch_list, target_list,
-> 1407         run_metadata)
   1408 

FailedPreconditionError: Attempting to use uninitialized value b_23
     [[{{node b_23/read}}]]

During handling of the above exception, another exception occurred:

FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-41-046a2c6ce082> in <module>
      6     for i in range(5):
      7         b = tf.math.multiply(a,b)
----> 8         print(sess.run(b))

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1150     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1151       results = self._do_run(handle, final_targets, final_fetches,
-> 1152                              feed_dict_tensor, options, run_metadata)
   1153     else:
   1154       results = []

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1326     if handle is None:
   1327       return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1328                            run_metadata)
   1329     else:
   1330       return self._do_call(_prun_fn, handle, feeds, fetches)

~/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1346           pass
   1347       message = error_interpolation.interpolate(message, self._graph)
-> 1348       raise type(e)(node_def, op, message)
   1349 
   1350   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value b_23
     [[node b_23/read (defined at <ipython-input-41-046a2c6ce082>:2) ]]

Caused by op 'b_23/read', defined at:
  File "/home/joseph/opt/anaconda3/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/joseph/opt/anaconda3/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/traitlets/config/application.py", line 664, in launch_instance
    app.start()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/kernelapp.py", line 563, in start
    self.io_loop.start()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/platform/asyncio.py", line 148, in start
    self.asyncio_loop.run_forever()
  File "/home/joseph/opt/anaconda3/lib/python3.7/asyncio/base_events.py", line 534, in run_forever
    self._run_once()
  File "/home/joseph/opt/anaconda3/lib/python3.7/asyncio/base_events.py", line 1771, in _run_once
    handle._run()
  File "/home/joseph/opt/anaconda3/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/ioloop.py", line 690, in <lambda>
    lambda f: self._run_callback(functools.partial(callback, future))
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/ioloop.py", line 743, in _run_callback
    ret = callback()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 787, in inner
    self.run()
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 748, in run
    yielded = self.gen.send(value)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 365, in process_one
    yield gen.maybe_future(dispatch(*args))
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 272, in dispatch_shell
    yield gen.maybe_future(handler(stream, idents, msg))
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/kernelbase.py", line 542, in execute_request
    user_expressions, allow_stdin,
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/ipkernel.py", line 294, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/ipykernel/zmqshell.py", line 536, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 2855, in run_cell
    raw_cell, store_history, silent, shell_futures)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 2881, in _run_cell
    return runner(coro)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/async_helpers.py", line 68, in _pseudo_sync_runner
    coro.send(None)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3058, in run_cell_async
    interactivity=interactivity, compiler=compiler, result=result)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3249, in run_ast_nodes
    if (await self.run_code(code, result,  async_=asy)):
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-41-046a2c6ce082>", line 2, in <module>
    b=tf.Variable(1,tf.int32, name="b")
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/variables.py", line 213, in __call__
    return cls._variable_v1_call(*args, **kwargs)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/variables.py", line 176, in _variable_v1_call
    aggregation=aggregation)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/variables.py", line 155, in <lambda>
    previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/variable_scope.py", line 2495, in default_variable_creator
    expected_shape=expected_shape, import_scope=import_scope)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/variables.py", line 217, in __call__
    return super(VariableMetaclass, cls).__call__(*args, **kwargs)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/variables.py", line 1395, in __init__
    constraint=constraint)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/variables.py", line 1557, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/util/dispatch.py", line 180, in wrapper
    return target(*args, **kwargs)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py", line 81, in identity
    ret = gen_array_ops.identity(input, name=name)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 3890, in identity
    "Identity", input=input, name=name)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py", line 788, in _apply_op_helper
    op_def=op_def)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/util/deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 3300, in create_op
    op_def=op_def)
  File "/home/joseph/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 1801, in __init__
    self._traceback = tf_stack.extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value b_23
     [[node b_23/read (defined at <ipython-input-41-046a2c6ce082>:2) ]]

Voila pour

Previous Post Next Post