Step 1 : Import Library

import tensorflow as tf

Step 2:  Implement TensorFlow Program

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
bias = tf.Variable(1.0)
y_pred = tf.pow(x, 2) + bias # x -> x^2 + bias
#loss = tf.pow(x, 2) + bias # x -> x^2 + bias
y = tf.pow( (y - y_pred) , 2) # l2 loss?
loss = x + y

Step 3:  Prepare Tensorflow program (Compile).
You can think of it as compile, for easiness. This step initializes  tensorflow variables, that will be used in the tensorflow progam, prepares  tensorflow session. Tensorflow session is corollary to the scope binding. All the variables, exist within this session scope i.e is not accessible outside the session scope.

sess = tf.Session()
## TF variables are not intialised until the following is called
init = tf.initialize_all_variables()
#init = tf.global_variables_initializer()  ##  Variable intitalisation call for new tensorflow version
sess.run(init)

Step 4: Run TensorFlow Program (Session)

#  TEST CASE 2 : OK, print 1.000 = (3**2 + 1 - 9)**2
_loss = sess.run(loss, {x: 3.0, y: 9.0})
print(_loss)

 

Complete Program:

############
## Import Library
############
import tensorflow as tf

############
## Simple Tensor Flow Program
############
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
bias = tf.Variable(1.0)
y_pred = tf.pow(x, 2) + bias # x -> x^2 + bias
loss = tf.pow(x, 2) + bias # x -> x^2 + bias
y = tf.pow( (y - y_pred) , 2) # l2 loss?
loss = x + y

############
## Session Initialistion (Compile Session)
############
sess = tf.Session()
## TF variables are not intialised until the following is called
init = tf.initialize_all_variables()
#init = tf.global_variables_initializer()  ##  Variable intitalisation call for new tensorflow version
sess.run(init)


############
## Run TensorFlow Program
############
print('Loss(x,y) = %.3f' % sess.run(loss, {x: 3.0, y: 9.0}))
try:
    print('Loss(x,y) = %.3f' % sess.run(loss, {x: 3.0}))
except:
    print('Session run code is invalid. Error occured')

 

Advertisements