{"id":47523,"date":"2026-11-24T22:04:51","date_gmt":"2026-11-24T22:04:51","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47523"},"modified":"2026-11-24T22:04:51","modified_gmt":"2026-11-24T22:04:51","slug":"tensorsflow-lab2-tensorsflow-v1sessions","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/tensorsflow-lab2-tensorsflow-v1sessions\/","title":{"rendered":"Tensorsflow Lab2 &#8211; Tensorsflow V1Sessions"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab shows how TensorFlow 1.x style graphs and sessions still work in TensorFlow 2 through the <code>tf.compat.v1<\/code> API. You will see why <code>Session.run()<\/code> fails while eager execution is on, how to turn eager execution off, and how to run constants, variables and placeholders with <code>feed_dict<\/code>. The last step writes the graph so you can view it in TensorBoard. Below the notebook you will find a corrected script, the TensorFlow 2 way to do the same thing, and fixes for the errors you are most likely to hit.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/073343db3d1838c1c72d11c3b264d8b0.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What the notebook demonstrates<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">TensorFlow 1.x worked in two phases. First you built a computation graph, and nothing was computed while you did that. Then you opened a <code>Session<\/code> and called <code>run()<\/code> to evaluate parts of the graph. TensorFlow 2 turns on <strong>eager execution<\/strong> by default, so every operation runs as soon as you call it and returns a concrete value. The <code>tf.compat.v1<\/code> module keeps the old graph and session API available so that legacy code can still run.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Notebook step<\/th><th>What happens<\/th><th>Why<\/th><\/tr><\/thead><tbody><tr><td><code>executing_eagerly()<\/code> returns <code>True<\/code><\/td><td>TF2 default mode<\/td><td>Ops run immediately<\/td><\/tr><tr><td><code>sess.run(c)<\/code> raises <code>The Session graph is empty<\/code><\/td><td>The session has nothing to execute<\/td><td><code>a<\/code>, <code>b<\/code> and <code>c<\/code> were computed eagerly and never added to a graph<\/td><\/tr><tr><td><code>c<\/code> shows <code>numpy=12<\/code><\/td><td>The value already exists<\/td><td>Eager tensors hold their result<\/td><\/tr><tr><td><code>disable_eager_execution()<\/code> and then <code>reset_default_graph()<\/code><\/td><td>Switches to graph mode with a clean graph<\/td><td>New ops go into the default graph<\/td><\/tr><tr><td><code>c<\/code> shows <code>&#039;sum:0&#039;<\/code> with no value<\/td><td>A symbolic tensor<\/td><td>It is only computed when a session runs it<\/td><\/tr><tr><td><code>sess.run(c)<\/code> returns <code>12<\/code>, <code>sess.run(d)<\/code> returns <code>35<\/code><\/td><td>The session evaluates graph nodes<\/td><td><code>d<\/code> was added to the same default graph after the session was created<\/td><\/tr><tr><td>Variables, placeholder, <code>feed_dict<\/code><\/td><td>Returns <code>[401. 501. 601.]<\/code><\/td><td>100 \u00d7 [4, 5, 6] + 1<\/td><\/tr><tr><td><code>FileWriter<\/code> and <code>%tensorboard<\/code><\/td><td>Saves and displays the graph<\/td><td>For visual inspection<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Python 3 with a current TensorFlow 2.x release (<code>pip install tensorflow<\/code>). The notebook output shows <code>python3.7<\/code> and <code>tensorflow_core<\/code> paths, which come from an early TF 2 install. Current TensorFlow releases no longer support Python 3.7, so use a newer interpreter.<\/li>\n\n\n<li>Jupyter Notebook or JupyterLab (<code>pip install notebook<\/code>). TensorBoard is installed together with the <code>tensorflow<\/code> package.<\/li>\n\n\n<li>A fresh kernel. Eager execution can only be switched off for the whole process, and the notebook ends by telling you to restart Jupyter for that reason.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">python -m venv tf-lab\nsource tf-lab\/bin\/activate\npip install tensorflow notebook\npython -c <span class=\"hljs-string\">\"import tensorflow as tf; print(tf.__version__, tf.executing_eagerly())\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Corrected, runnable version of the lab<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The script below runs the graph-mode part of the notebook in one go. It fixes the <code>tf.Variable<\/code> call, turns off eager execution before any tensors exist, and uses a <code>with<\/code> block so the session is always closed. Save it as <code>v1_sessions.py<\/code> and run it with <code>python v1_sessions.py<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import tensorflow <span class=\"hljs-keyword\">as<\/span> tf\n\n<span class=\"hljs-comment\"># Must run before any graphs, ops or tensors are created<\/span>\ntf.compat.v1.disable_eager_execution()\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Eager:\"<\/span>, tf.compat.v1.executing_eagerly())   <span class=\"hljs-comment\"># False<\/span>\n\n<span class=\"hljs-comment\"># Constants and simple ops<\/span>\na = tf.constant(<span class=\"hljs-number\">5<\/span>, name=<span class=\"hljs-string\">\"a\"<\/span>)\nb = tf.constant(<span class=\"hljs-number\">7<\/span>, name=<span class=\"hljs-string\">\"b\"<\/span>)\ntotal = tf.add(a, b, name=<span class=\"hljs-string\">\"sum\"<\/span>)\nproduct = tf.multiply(a, b, name=<span class=\"hljs-string\">\"product\"<\/span>)\n\n<span class=\"hljs-comment\"># Variables need dtype as a keyword argument<\/span>\nm = tf.Variable(&#91;<span class=\"hljs-number\">4.0<\/span>, <span class=\"hljs-number\">5.0<\/span>, <span class=\"hljs-number\">6.0<\/span>], dtype=tf.float32, name=<span class=\"hljs-string\">\"m\"<\/span>)\nc = tf.Variable(&#91;<span class=\"hljs-number\">1.0<\/span>, <span class=\"hljs-number\">1.0<\/span>, <span class=\"hljs-number\">1.0<\/span>], dtype=tf.float32, name=<span class=\"hljs-string\">\"c\"<\/span>)\n\n<span class=\"hljs-comment\"># Placeholder: a value supplied at run time through feed_dict<\/span>\nx = tf.compat.v1.placeholder(tf.float32, shape=&#91;<span class=\"hljs-number\">3<\/span>], name=<span class=\"hljs-string\">\"x\"<\/span>)\ny = m * x + c\n\ninit = tf.compat.v1.global_variables_initializer()\n\nwith tf.compat.v1.Session() <span class=\"hljs-keyword\">as<\/span> sess:\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"sum, product:\"<\/span>, sess.run(&#91;total, product]))\n    sess.run(init)\n    y_output = sess.run(y, feed_dict={x: &#91;<span class=\"hljs-number\">100.0<\/span>, <span class=\"hljs-number\">100.0<\/span>, <span class=\"hljs-number\">100.0<\/span>]})\n    <span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Final result: mx + c =\"<\/span>, y_output)\n\n    writer = tf.compat.v1.summary.FileWriter(<span class=\"hljs-string\">\".\/logs\"<\/span>, sess.graph)\n    writer.close()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">Eager: <span class=\"hljs-keyword\">False<\/span>\nsum, product: &#91;<span class=\"hljs-number\">12<\/span>, <span class=\"hljs-number\">35<\/span>]\n<span class=\"hljs-keyword\">Final<\/span> result: mx + c = &#91;<span class=\"hljs-number\">401.<\/span> <span class=\"hljs-number\">501.<\/span> <span class=\"hljs-number\">601.<\/span>]<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><code>sess.run([total, product])<\/code> fetches several tensors in one call and returns them as a list.<\/li>\n\n\n<li><code>global_variables_initializer()<\/code> only builds an op. Variables have no value until <code>sess.run(init)<\/code> runs it.<\/li>\n\n\n<li><code>feed_dict<\/code> maps each placeholder tensor to a concrete value for that single <code>run()<\/code> call. The value must match the placeholder&#039;s dtype and shape.<\/li>\n\n\n<li><code>FileWriter(logdir, sess.graph)<\/code> saves the graph definition as an event file that TensorBoard can read.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What was wrong in the original notebook<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The notebook runs, but some of its output comes from a bug and some from cells that were run more than once.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>tf.Variable([4.0, 5.0, 6.0], tf.float32, name=&#039;m&#039;)<\/code><\/strong>: the second positional parameter of <code>tf.Variable<\/code> is <code>trainable<\/code>, not <code>dtype<\/code>. The code sets <code>trainable=tf.float32<\/code>, and that causes the later warning <code>tf.float32 has type DType, but expected one of: int, long, bool<\/code> when the <code>variables<\/code> and <code>trainable_variables<\/code> collections are serialized. Pass <code>dtype=tf.float32<\/code> as a keyword and the warning goes away. The values are floats either way, because the initial value already contains floats.<\/li>\n\n\n<li><strong>Placeholder named <code>x_1:0<\/code> instead of <code>x:0<\/code><\/strong>: the cell was run twice, so TensorFlow gave the second node a unique name. In graph mode, every time you re-run a cell it adds new nodes to the default graph. Call <code>tf.compat.v1.reset_default_graph()<\/code> and rebuild the graph, or restart the kernel.<\/li>\n\n\n<li><strong>The first session is never closed<\/strong>: <code>sess = tf.compat.v1.Session()<\/code> in eager mode is left open. Prefer <code>with tf.compat.v1.Session() as sess:<\/code> blocks.<\/li>\n\n\n<li><strong>Calling <code>disable_eager_execution()<\/code> partway through the notebook<\/strong>: the TensorFlow documentation says to call it at program startup, before any graphs, ops or tensors are created. It happened to work in this demo, but in real code put it directly after the import.<\/li>\n\n\n<li><strong><code>!rm -rf .\/logs\/<\/code><\/strong> only works on Linux and macOS. On Windows, use <code>shutil.rmtree(&#039;.\/logs&#039;, ignore_errors=True)<\/code> in Python.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Viewing the graph in TensorBoard<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>%tensorboard<\/code> magic embeds TensorBoard in the notebook, but the graph explorer is easier to use in a separate browser tab. You can also start TensorBoard from a terminal:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">tensorboard --logdir .\/logs --port <span class=\"hljs-number\">6060<\/span>\n<span class=\"hljs-comment\"># then open http:\/\/localhost:6060 and select the Graphs tab<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Look for the nodes <code>m<\/code>, <code>c<\/code>, <code>x<\/code>, <code>mul<\/code> and <code>add<\/code>. Turn on <strong>Trace inputs<\/strong> and click <code>add<\/code> to highlight the path from <code>x<\/code> through <code>mul<\/code>. If you see duplicate nodes such as <code>x_1<\/code>, the graph was built more than once in the same kernel.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> If TensorBoard reports that it is reusing an existing instance, as in the notebook output, it may still be showing an old log directory. Stop the old process (<code>kill &lt;pid&gt;<\/code>) or pick a different <code>--port<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The same computation in TensorFlow 2 style<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>tf.compat.v1<\/code> only for migrating or maintaining legacy code. For new code, <code>tf.function<\/code> replaces sessions, normal function arguments replace placeholders, and variables are initialized when you create them. You can still export a graph for TensorBoard with the trace API:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">import tensorflow as tf   # fresh kernel, eager execution on\n\nm = tf.Variable(&#91;4.0, 5.0, 6.0], name=\"m\")\nc = tf.Variable(&#91;1.0, 1.0, 1.0], name=\"c\")\n\n@tf.function\ndef linear(x):\n    return m * x + c\n\nwriter = tf.summary.create_file_writer(\".\/logs\/tf2\")\ntf.summary.trace_on(graph=True)\ny = linear(tf.constant(&#91;100.0, 100.0, 100.0]))\nwith writer.as_default():\n    tf.summary.trace_export(name=\"linear\", step=0)\n\nprint(y.numpy())   # &#91;401. 501. 601.]<\/code><\/span><\/pre>\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>TF1 \/ compat.v1<\/th><th>TF2 equivalent<\/th><\/tr><\/thead><tbody><tr><td><code>Session.run(t)<\/code><\/td><td>Call the function; use <code>t.numpy()<\/code> for the value<\/td><\/tr><tr><td><code>placeholder<\/code> + <code>feed_dict<\/code><\/td><td>Function arguments<\/td><\/tr><tr><td><code>global_variables_initializer()<\/code><\/td><td>Not needed<\/td><\/tr><tr><td><code>summary.FileWriter(dir, graph)<\/code><\/td><td><code>summary.create_file_writer<\/code> + <code>trace_on<\/code> \/ <code>trace_export<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Error<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>RuntimeError: The Session graph is empty<\/code><\/td><td>The tensors were created in eager mode<\/td><td>Call <code>disable_eager_execution()<\/code> first, then rebuild the ops<\/td><\/tr><tr><td><code>RuntimeError: tf.placeholder() is not compatible with eager execution<\/code><\/td><td>Eager execution is still on<\/td><td>Disable it at startup or use a <code>tf.function<\/code> argument<\/td><\/tr><tr><td><code>InvalidArgumentError: You must feed a value for placeholder tensor &#039;x&#039;<\/code><\/td><td><code>feed_dict<\/code> is missing<\/td><td>Pass <code>feed_dict={x: ...}<\/code><\/td><\/tr><tr><td><code>FailedPreconditionError<\/code> mentioning an uninitialized variable<\/td><td><code>init<\/code> was not run<\/td><td>Call <code>sess.run(init)<\/code> before reading the variables<\/td><\/tr><tr><td><code>ValueError: Cannot feed value of shape (2,) for Tensor &#039;x:0&#039;<\/code><\/td><td>The fed value has the wrong shape<\/td><td>Match the placeholder shape, or use <code>shape=[None]<\/code><\/td><\/tr><tr><td><code>RuntimeError: Attempted to use a closed Session<\/code><\/td><td><code>run()<\/code> was called after <code>close()<\/code><\/td><td>Open a new session or keep the work inside the <code>with<\/code> block<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Does TensorFlow 2 still support tf.Session?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Not as <code>tf.Session<\/code>. It is available as <code>tf.compat.v1.Session<\/code>, and it works on graph tensors, which in practice means you need to disable eager execution first. It is meant for running legacy code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does sess.run() say the session graph is empty?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">With eager execution on, ops run immediately and are never added to the default graph, so the session has nothing to execute. Call <code>tf.compat.v1.disable_eager_execution()<\/code> at program start and build the graph again.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I re-enable eager execution after disabling it?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Restart the Python process or Jupyter kernel. Eager mode is a process-wide setting and should not be switched back and forth in the middle of a program.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What replaces placeholders and feed_dict in TensorFlow 2?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Write a Python function that takes the inputs as arguments, optionally decorate it with <code>@tf.function<\/code> for graph performance, and call it with tensors or NumPy arrays.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why do my node names end in _1 in TensorBoard?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The same cell ran more than once in graph mode, so TensorFlow added duplicate nodes and gave them unique names. Reset the default graph or restart the kernel before you rebuild it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/artificial-intelligence\/machine-learning\/\">More Machine Learning tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/staff-mlops-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/lead-machine-learning-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This lab shows how TensorFlow 1.x style graphs and sessions still work in TensorFlow 2 through the tf.compat.v1 API. You will see why Session.run() fails while eager&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[6512],"tags":[7380],"class_list":["post-47523","post","type-post","status-publish","format-standard","hentry","category-machine-learning","tag-tensorflow"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47523","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=47523"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47523\/revisions"}],"predecessor-version":[{"id":80200,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47523\/revisions\/80200"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47523"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47523"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47523"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}