In this second part of the introduction to TensorFlow we add two new node types: variables and placeholders.
Let's use the same example that we have used in the first part. We start by importing TensorFlow:
import tensorflow as tf
Let's use the same example that we have used in the first part. We start by importing TensorFlow:
import tensorflow as tf
Next we start a session, but before let's make a reset to the graph internal state:
tf.reset_default_graph()
sess=tf.Session()
And now we create two variables of type 32 bit float:
x = tf.Variable(2.0,tf.float32)
y = tf.Variable(3.0,tf.float32)
Since we are using variables we must initialize them:
init = tf.global_variables_initializer()
sess.run(init)
The mathematical expression is this:
sumnodes = x + y
To evaluate the expression:
print(sess.run(sumnodes))
Because we are using variables we can change the values like so:
sess.run(x.assign(5.0))
As always we must execute the assign operation inside a TF session. To make multiple assigns we create references to the operations and execute them with one line:
NewX = x.assign(5.0)
NewY = y.assign(10.0)
sess.run([NewX,NewY])
Now the expression evaluates to a diferente result:
print(sess.run(sumnodes))
Placeholders have a different behavior as they allow to define the value only when the expression is evaluated and they can be assign to one value or a range of values.
Something like this, first define the placeholder:
a = tf.placeholder(tf.float32)
As you can see there is no value set. Next, let's change the expression:
sumnodes = x*a + y
To evaluate the expression we must use:
print(sess.run(sumnodes,{a: 10}))
The parameter defines the value of the placeholder. It's possible to use this:
print(sess.run(sumnodes,{a: range(10)}))
or this:
print(sess.run(sumnodes,{a: [2,5,8,11]}))
As we are working with placeholders and variables it's very important to close the TensorFlow session:
sess.close()
The video on youtube
The code on GitHub
Comentários
Enviar um comentário