Table Of Contents

Creating Tensors

In [27]:
import tensorflow as tf
print(f'tensorflow version: {tf.__version__}')
tensorflow version: 2.14.0

A Constant: from scalar

In [28]:
# DOCS
# https://www.tensorflow.org/api_docs/python/tf/constant

myVal = 7
firstTensor = tf.constant(myVal)
print(firstTensor)

# shows...
# tf.Tensor(7, shape=(), dtype=int32)

# show number of dimensions
# returns 0
firstTensor.ndim
tf.Tensor(7, shape=(), dtype=int32)
Out [28]:
0

A Constant: from array

In [29]:
firstArr = [10,10]
arrTensor = tf.constant(firstArr)
arrTensor
# <tf.Tensor: shape=(2,), dtype=int32, numpy=array([10, 10], dtype=int32)>
Out [29]:
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([10, 10], dtype=int32)>
In [30]:
arrTensor.ndim
Out [30]:
1

A Constant: from matrix

In [31]:
firstMatrix = [
    [10,7],
    [7,10]
]
matrixTensor = tf.constant(firstMatrix)
matrixTensor
# <tf.Tensor: shape=(2, 2), dtype=int32, numpy=
# array([[10,  7],
#        [ 7, 10]], dtype=int32)>
Out [31]:
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[10,  7],
       [ 7, 10]], dtype=int32)>
In [32]:
matrixTensor.ndim
Out [32]:
2

A Constant: from matrix of type-defined floats

As seen above, the tensors created get a "default" datatype (dtype) of int32.
The datatype can be defined during tensor creation by setting a dtype parameter:

In [34]:
arrWithDots = [
    [10., 7.],
    [3., 2.],
    [8., 9.]
]

arrDotTensor = tf.constant(arrWithDots,dtype=tf.float16)
arrDotTensor
Out [34]:
<tf.Tensor: shape=(3, 2), dtype=float16, numpy=
array([[10.,  7.],
       [ 3.,  2.],
       [ 8.,  9.]], dtype=float16)>
In [35]:
arrDotTensor.ndim
Out [35]:
2

A Constant: from a more complex array

In [36]:
bigArr = [
    [
        [1,2,3],
        [4,5,6]
    ],
    [
        [7,8,9],
        [10,11,12]
    ],
    [
        [13,14,15],
        [16,17,18]
    ],
    
]
biggerTensor = tf.constant(bigArr)
biggerTensor
Out [36]:
<tf.Tensor: shape=(3, 2, 3), dtype=int32, numpy=
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]],

       [[13, 14, 15],
        [16, 17, 18]]], dtype=int32)>
In [37]:
biggerTensor.ndim
Out [37]:
3