TensorFlow Variables and Constants

I am new to tensorflow, I can’t understand the difference in variable and constant, I understand that we use variables for equations and constants for direct values, but why is code # 1 only working and why not code # 2 and # 3, and please , explain in which cases we must first run our graph (a), and then our variable (b), i.e.

 (a) session.run(model)
 (b) print(session.run(y))

and in this case, I can directly execute this iee command

print(session.run(y))

Code No. 1:

x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')

model = tf.global_variables_initializer() 

with tf.Session() as session:
    session.run(model)
    print(session.run(y))

Code No. 2:

x = tf.Variable(35, name='x')
y = tf.Variable(x + 5, name='y')

model = tf.global_variables_initializer() 

with tf.Session() as session:
    session.run(model)
    print(session.run(y))

Code No. 3:

x = tf.constant(35, name='x')
y = tf.constant(x + 5, name='y')

model = tf.global_variables_initializer() 

with tf.Session() as session:
    session.run(model)
    print(session.run(y))
+16
source share
2 answers

TensorFlow , , ( , ).

, , tf.assign() ( ).

tf.global_variables_initializer() , , , , .

(# 1) , , .

(# 2) - tf.global_variables_initializer(). tf.variables_initializer() :

x = tf.Variable(35, name='x')
model_x = tf.variables_initializer([x])

y = tf.Variable(x + 5, name='y')
model_y = tf.variables_initializer([y])


with tf.Session() as session:
   session.run(model_x)
   session.run(model_y)
   print(session.run(y))

(# 3) , , . (# 1).

. (a) session.run(model) (b) print(session.run(y)).

+24

.

Tensorflow 2.0.b1, Variables Constant tf.GradientTape tf.GradientTape. , .

https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/GradientTape

x = tf.constant(3.0)
with tf.GradientTape(persistent=True) as g:
  g.watch(x)
  y = x * x
  z = y * y
dz_dx = g.gradient(z, x)  # 108.0 (4*x^3 at x = 3)
dy_dx = g.gradient(y, x)  # 6.0
del g  # Drop the reference to the tape

x Constant. GradientTape . , GradientTape. Constant, GradientTape s. ,

x = tf.constant(3.0)
x2 = tf.constant(3.0)
with tf.GradientTape(persistent=True) as g:
  g.watch(x)
  with tf.GradientTape(persistent=True) as g2:
    g2.watch(x2)

    y = x * x
    y2 = y * x2

dy_dx = g.gradient(y, x)       # 6
dy2_dx2 = g2.gradient(y2, x2)  # 9
del g, g2  # Drop the reference to the tape

, Variable GradientTape.

GradientTape , . : https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/GradientTape

, ,

x = tf.Variable(3.0)
x2 = tf.Variable(3.0)
with tf.GradientTape(persistent=True) as g:
    y = x * x
    y2 = y * x2

dy_dx = g.gradient(y, x)       # 6
dy2_dx2 = g.gradient(y2, x2)   # 9
del g  # Drop the reference to the tape
print(dy_dx)
print(dy2_dx2)

, , watch_accessed_variables=False. , , .

0

All Articles