Table Of Contents
Creating Tensors
In [27]:
import tensorflow as tf
print(f'tensorflow version: {tf.__version__}')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.ndimOut [28]:
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]:
In [30]:
arrTensor.ndimOut [30]:
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]:
In [32]:
matrixTensor.ndimOut [32]:
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)
arrDotTensorOut [34]:
In [35]:
arrDotTensor.ndimOut [35]:
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)
biggerTensorOut [36]:
In [37]:
biggerTensor.ndimOut [37]: