09.05.2023 Views

pdfcoffee

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

TensorFlow 1.x and 2.x

Here, we used the optional argument name to give a name to a variable as defined

in the computational graph. In all the preceding examples, the source of variable

initialization is a constant. We can also specify a variable to be initialized from

another variable. The following statement will initialize weight2 from the weights

defined above:

weight2=tf.Variable(weights.initialized_value(), name='w2')

Initializing variables: The definition of variables specifies how they are to

be initialized, since we must explicitly initialize all declared variables. In the

definition of the computational graph, we do so by declaring an Operation Object:

intial_op = tf.global_variables_initializer()

Each variable can also be initialized separately using tf.Variable.initializer

while running the graph:

bias = tf.Variable(tf.zeros([100,100]))

with tf.Session() as sess:

sess.run(bias.initializer)

Saving variables: We can save all the variables using the Saver class. To do so, we

define a saver operation object:

saver = tf.train.Saver()

Placeholders: We define a placeholder using:

tf.placeholder(dtype, shape=None, name=None)

dtype specifies the data type of placeholder and must be specified while declaring

the placeholder. Next, we define the placeholder for x and calculate y=2x using

feed_dict for a random 4×5 matrix (remember that feed_dict is used to feed

values to TensorFlow placeholders):

x = tf.placeholder("float")

y = 2 * x

data = tf.random_uniform([4,5],10)

with tf.Session() as sess:

x_data = sess.run(data)

print(sess.run(y, feed_dict = {x:x_data}))

All variables and placeholders are defined in the Computational Graph section of

the code. If we use a print statement in the definition section, we will only get

information about the type of tensor and not about its value.

[ 58 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!