Order of sess.run([op1, op2...]) in Tensorflow

2024/10/12 22:30:08

I wonder what's the running order of the op list in sess.run(ops_list, ...). for example:for a typical classification scenario: _, loss = sess.run([train_op, loss_op]), if train_op run first,then the loss is the loss after current backprop. But if loss run first, then the loss is the loss before current backprop.anyone help me? Thanks.

Answer

loss will be the value of the loss before the update caused by train_op. Note that loss_op is an input to the optimizer, so it necessarily goes "before" train_op in the graph. loss_op is computed with the variable values at the beginning of the run operation. If you wanted to compute the loss after train_op, you could do that for example using a tf.control_dependencies block with the optimizer and computing the loss again, but in that case you would be doing two forward passes of your model on each step, with the associated cost. Usually, if you just want to plot the loss for monitorization or something like that it is okay to use the value from the previous step.

For further explanation, in general the order in which TensorFlow operations are executed is only guaranteed to the extent that these operations depend on each other, and it is not related to the order in which the are passed to run. In your case, train_op depends on loss_op, so loss_op has to go first. However, in other cases operations do not depend directly on each other, and in that case the order is not guaranteed. Many times that does not really matter, but in some cases it does. Consider the next example:

import tensorflow as tfv = tf.Variable(0)
v2 = 2 * v
v_update = v.assign(v + 1)
init = tf.global_variables_initializer()
with tf.Session() as sess:sess.run(init)for i in range(5):print(sess.run([v_update, v2]))

A run in my computer produced this output:

[1, 0]
[2, 2]
[3, 4]
[4, 8]
[5, 10]

As you see, v2 is sometimes twice the updated value and sometimes twice the non-updated value. If for example we wanted to make sure that v2 always runs before v_update we could do:

import tensorflow as tfv = tf.Variable(0)
v2 = 2 * v
with tf.control_dependencies([v2]):v_update = v.assign(v + 1)
init = tf.global_variables_initializer()
with tf.Session() as sess:sess.run(init)for i in range(5):print(sess.run([v_update, v2]))

Which consistently produces:

[1, 0]
[2, 2]
[3, 4]
[4, 6]
[5, 8]
https://en.xdnf.cn/q/69606.html

Related Q&A

Django form validation: get errors in JSON format

I have this very simple Django formfrom django import formsclass RegistrationForm(forms.Form):Username = forms.CharField()Password = forms.CharField()I manage this manually and dont use the template en…

Django inheritance and polymorphism with proxy models

Im working on a Django project that I did not start and I am facing a problem of inheritance. I have a big model (simplified in the example) called MyModel that is supposed to represents different kind…

L suffix in long integer in Python 3.x

In Python 2.x there was a L suffix after long integer. As Python 3 treats all integers as long integer this has been removed. From Whats New In Python 3.0:The repr() of a long integer doesn’t include …

Custom Colormap

I want to plot a heatmap with a custom colormap similar to this one, although not exactly.Id like to have a colormap that goes like this. In the interval [-0.6, 0.6] the color is light grey. Above 0.6,…

Whats the point of @staticmethod in Python?

Ive developed this short test/example code, in order to understand better how static methods work in Python.class TestClass:def __init__(self, size):self.size = sizedef instance(self):print("regul…

logical or on list of pandas masks

I have a list of boolean masks obtained by applying different search criteria to a dataframe. Here is an example list containing 4 masks: mask_list = [mask1, mask2, mask3, mask4]I would like to find th…

How to view the implementation of pythons built-in functions in pycharm?

When I try to view the built-in function all() in PyCharm, I could just see "pass" in the function body. How to view the actual implementation so that I could know what exactly the built-in f…

How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?

While using read_csv with Pandas, if i want a given column to be converted to a type, a malformed value will interrupt the whole operation, without an indication about the offending value.For example, …

Python - object layout

can somebody describe the following exception? What is the "object layout" and how it is defined? ThanksTraceback (most recent call last):File "test_gui.py", line 5, in <module…

Using Tor proxy with scrapy

I need help setting up Tor in Ubuntu and to use it within scrapy framework.I did some research and found out this guide:class RetryChangeProxyMiddleware(RetryMiddleware):def _retry(self, request, reaso…