domingo, 18 de fevereiro de 2018

TensorFlow Variables and Placeholders

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

Next we start a session, but before let's make a reset to the graph internal state:


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()

The mathematical expression is this:

sumnodes = x + y

To evaluate the expression:


Because we are using variables we can change the values like so:

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)[NewX,NewY])

Now the expression evaluates to a diferente result:


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(,{a: 10}))

The parameter defines the value of the placeholder. It's possible to use this:

print(,{a: range(10)}))

or this:

print(,{a: [2,5,8,11]}))

As we are working with placeholders and variables it's very important to close the TensorFlow session:


The video on youtube

The code on GitHub

Sem comentários:

Enviar um comentário