Creating Tensors From Numpy Arrays

In [1]:
import tensorflow as tf
import numpy as np
In [2]:
npArrOne = np.arange(1,25, dtype=np.int32)
npArrOne
Out [2]:
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20, 21, 22, 23, 24], dtype=int32)
In [3]:
tensorFromNpArr = tf.constant(npArrOne)
tensorFromNpArr
Out [3]:
<tf.Tensor: shape=(24,), dtype=int32, numpy=
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20, 21, 22, 23, 24], dtype=int32)>

Converting Between the Two

In [14]:
backToNPArr = np.array(tensorFromNpArr)
backToNPArr, type(backToNPArr)
Out [14]:
(array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
        18, 19, 20, 21, 22, 23, 24], dtype=int32),
 numpy.ndarray)

Changing The Shape

Tensor shapes can be changed &/or set during tesnsor creation.
In order to do this, the multiplied dimensions must equal the number of elements in the tensor:

  • EXAMPLES: a tensor, above, with 24 elements, can be shaped (2,3,4) or (12,2) or (6,2,1,2)
In [7]:
changedShape = tf.constant(npArrOne, shape=(2,3,4))
changedShape
Out [7]:
<tf.Tensor: shape=(2, 3, 4), dtype=int32, numpy=
array([[[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]],

       [[13, 14, 15, 16],
        [17, 18, 19, 20],
        [21, 22, 23, 24]]], dtype=int32)>
In [9]:
changedShapeTwo = tf.constant(npArrOne, shape=(6,2,2))
changedShapeTwo
Out [9]:
<tf.Tensor: shape=(6, 2, 2), dtype=int32, numpy=
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]],

       [[13, 14],
        [15, 16]],

       [[17, 18],
        [19, 20]],

       [[21, 22],
        [23, 24]]], dtype=int32)>