Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Eager execution, tensors, and automatic differentiation
tf.keras is now the recommended high-level API for building modelsCPU, GPU, TPU, and mobile; supports distributed trainingimport tensorflow as tf
print("TensorFlow Version:", tf.__version__)
print("Is GPU available?:", tf.config.list_physical_devices('GPU'))tf.Tensor: immutable n-dimensional array, the fundamental data structuretf.Variable: mutable tensor, used to store trainable parameterstf.TensorArray: dynamically sized array of tensors (used in RNNs)tf.RaggedTensor: tensors with variable row lengthstf.SparseTensor: efficient storage for mostly-zero dataRank-0
scalar, no axes
Rank-1
vector, one axis
Rank-2
matrix, two axes
rank_0 = tf.constant(4)
rank_1 = tf.constant([2.0, 3.0, 4.0])
rank_2 = tf.constant([[1, 2], [3, 4], [5, 6]], dtype=tf.float16).shape gives size along each axis; .dtype gives the element data typetensor.numpy() or np.array(tensor)tensor = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
tensor.shape # (2, 2)
tensor.dtype # float32
tensor[0, 0] # element access
tensor[:, 0] # slicingtf.VariableVariable is forvar = tf.Variable([[5.0, 6.0], [7.0, 8.0]])
var.assign([[1, 2], [3, 4]]) # replace values
var.assign_add([[1, 1], [1, 1]]) # increment in placetf.RaggedTensorragged = tf.ragged.constant([[1, 2], [3, 4, 5], [6]])tf.SparseTensorsparse = tf.SparseTensor(indices=[[0,3],[2,4]], values=[10,20], dense_shape=[3,10])
tf.sparse.to_dense(sparse)tf.add, tf.subtract, tf.multiply, tf.dividetf.linalg.matmul, .det, .inv, .eig, .svdA = tf.constant([[2.0, 3.0], [1.0, 4.0]])
B = tf.constant([[1.0, 2.0], [3.0, 4.0]])
tf.linalg.matmul(A, B)tf.random.normal([3, 3], mean=0.0, stddev=1.0)
tf.random.uniform([2, 2], minval=0, maxval=10)
tf.random.set_seed(42) # reproducibilitytf.reduce_meanx = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32)
tf.reduce_mean(x) # 3.5 (all elements)
tf.reduce_mean(x, axis=0) # [2.5 3.5 4.5] (column means)
tf.reduce_mean(x, axis=1) # [2. 5.] (row means)@tf.function: traces Python code into a static computation graph, much faster on repeated callsPython function
@tf.function
trace
Computation graph
Faster repeated execution
@tf.function
def computation_graph(x1, x2):
return (x1 + x2) - (x1 * x2)tf.GradientTape(), then call .gradient()x = 2.0, what is dy/dx?x = tf.Variable(2.0)
with tf.GradientTape() as tape:
y = x ** 3
dy_dx = tape.gradient(y, x) # 12.0, since d/dx(x^3) = 3x^2tf.Tensor is immutable; tf.Variable is the mutable container for trainable parameters@tf.function compiles Python into a graph for significant performance gainstf.GradientTape powers automatic differentiation, the core of model trainingtf.keras does at a higher levelMahmoud Abas|Introduction to TensorFlow 2.x