Test basic Python code


In [1]:
print "hello, there"


hello, there

In [2]:
a=2
c=a+2
print c


4

Test Python package import


In [3]:
import numpy as np

In [4]:
import tensorflow as tf

Run basic TensorFlow code


In [5]:
a1=tf.ones([10])
sess = tf.Session()
print(sess.run(a1))


[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]

this is different from print a0 itself


In [6]:
print(a1)


Tensor("ones:0", shape=(10,), dtype=float32)

In [7]:
hello = tf.constant('Hello, Joe!')
print(sess.run(hello))
print(hello)


Hello, Joe!
Tensor("Const:0", shape=(), dtype=string)

Note that sess.run() gives us the actual output value, it takes tf variable The following tf.constant is required, otherwise it will generate error


In [8]:
a = tf.constant(10)
b = tf.constant(20)
c=a+b
print(sess.run(c))


30

Put everything in a session, no need to call session, just use .eval()


In [9]:
with tf.Session():
    a = tf.constant(10)
    b = tf.constant(20)
    c=a+b
    print c
    print(c.eval())


Tensor("add_1:0", shape=(), dtype=int32)
30

the following code will generate error, that because c is not tf variable, thus cannot be run by sess.run


In [21]:



Out[21]:
<tf.Tensor 'Add:0' shape=(4,) dtype=float32>

See different tensor dimensions


In [10]:
a2=tf.ones([10,3])
print(sess.run(a2))


[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

In [11]:
a3=tf.ones([10,3,2])
print(sess.run(a3))


[[[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]

 [[ 1.  1.]
  [ 1.  1.]
  [ 1.  1.]]]

b1 = tf.ones([4]) b2 = tf.constant([2.0, 2.0, 2.0, 2.0]) c = tf.add(b1, b2) print c


In [12]:
print(sess.run(c))


30

In [13]:
with tf.Session():
  b1 = tf.ones([4])
  b2 = tf.constant([2.0, 2.0, 2.0, 2.0])
  c = tf.add(b1, b2)
  print c.eval()


[ 3.  3.  3.  3.]

Get random number and data type


In [14]:
shape=[2,3]
x=tf.random_normal(shape, stddev=0.7) 
with tf.Session():
    print x.eval()


[[-0.40981114  0.88485193 -0.27486104]
 [ 0.83717912 -0.34084049  0.35752657]]

In [15]:
shape=[2,2]
x=tf.truncated_normal(shape, stddev=0.1) 
with tf.Session():
    print x.eval()


[[-0.12661348 -0.15962534]
 [-0.12176304 -0.0294427 ]]

Exercise: Print out the sigmoid value of a 2x2 marix of 1's, using TensorFlow


In [25]:
with tf.Session():
    ones = tf.ones([2,2])
    print ones.eval()
    sigmoid = tf.sigmoid(ones, name="sigmoid")
    print sigmoid.eval()


[[ 1.  1.]
 [ 1.  1.]]
[[ 0.7310586  0.7310586]
 [ 0.7310586  0.7310586]]

In [ ]: