Defining multidimensional arrays using TensorFlow

Now we will try to define such arrays using TensorFlow:

salar_var = tf.constant([4])
vector_var = tf.constant([5,4,2])
matrix_var = tf.constant([[1,2,3],[2,2,4],[3,5,5]])
tensor = tf.constant( [ [[1,2,3],[2,3,4],[3,4,5]] , [[4,5,6],[5,6,7],[6,7,8]] , [[7,8,9],[8,9,10],[9,10,11]] ] )
with tf.Session() as session:
result = session.run(salar_var)
print "Scalar (1 entry): %s " % result
result = session.run(vector_var)
print "Vector (3 entries) : %s " % result
result = session.run(matrix_var)
print "Matrix (3x3 entries): %s " % result
result = session.run(tensor)
print "Tensor (3x3x3 entries) : %s " % result
Output:
Scalar (1 entry):
[2]

Vector (3 entries) :
[5 6 2]

Matrix (3x3 entries):
[[1 2 3]
[2 3 4]
[3 4 5]]

Tensor (3x3x3 entries) :
[[[ 1 2 3]
[ 2 3 4]
[ 3 4 5]]

[[ 4 5 6]
[ 5 6 7]
[ 6 7 8]]

[[ 7 8 9]
[ 8 9 10]
[ 9 10 11]]]

Now that you understand these data structures, I encourage you to play with them using some previous functions to see how they will behave, according to their structure types:

Matrix_one = tf.constant([[1,2,3],[2,3,4],[3,4,5]])
Matrix_two = tf.constant([[2,2,2],[2,2,2],[2,2,2]])
first_operation = tf.add(Matrix_one, Matrix_two)
second_operation = Matrix_one + Matrix_two
with tf.Session() as session:
result = session.run(first_operation)
print "Defined using tensorflow function :"
print(result)
result = session.run(second_operation)
print "Defined using normal expressions :"
print(result)
Output:
Defined using tensorflow function :
[[3 4 5]
[4 5 6]
[5 6 7]]
Defined using normal expressions :
[[3 4 5]
[4 5 6]
[5 6 7]]

With the regular symbol definition and also the tensorflow function, we were able to get an element-wise multiplication, also known as Hadamard product. But what if we want the regular matrix product? We need to use another TensorFlow function called tf.matmul():

Matrix_one = tf.constant([[2,3],[3,4]])
Matrix_two = tf.constant([[2,3],[3,4]])
first_operation = tf.matmul(Matrix_one, Matrix_two)
with tf.Session() as session:
result = session.run(first_operation)
print "Defined using tensorflow function :"
print(result)
Output:
Defined using tensorflow function :
[[13 18]
[18 25]]

We can also define this multiplication ourselves, but there is a function that already does that, so no need to reinvent the wheel!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset