TensorFlow
Tensor Basics
Create and operate on TensorFlow tensors.
By EZ4Code Team
tensorbasics
Code
import tensorflow as tf
# Creation
a = tf.constant([1, 2, 3], dtype=tf.float32)
b = tf.zeros((2, 3))
c = tf.ones((3, 3))
d = tf.random.normal((2, 2))
e = tf.range(0, 10, 2)
# Operations
print(a + a, a * 2, tf.matmul(tf.reshape(a, (1, 3)), tf.reshape(a, (3, 1))))
print(tf.reduce_sum(a), tf.reduce_mean(a), tf.reduce_max(a))
# Eager conversion to NumPy
np_val = a.numpy()
# Variables are mutable, tracked for training
v = tf.Variable([1.0, 2.0])
v.assign([3.0, 4.0])
v.assign_add([1.0, 1.0])
# Gradients with GradientTape
with tf.GradientTape() as tape:
y = tf.reduce_sum(v ** 2)
grad = tape.gradient(y, v)
print(grad)Explanation
Constants hold immutable values and Variables hold mutable trainable parameters that GradientTape can differentiate. reduce_sum, reduce_mean, and reduce_max collapse axes like NumPy reductions. The eager default mode lets you call .numpy() for inspection and GradientTape for on-demand autodiff.
More TensorFlow Snippets
Keras Model
Build models with Sequential and the functional API.
Layers
Use core layers and build a custom one.
Compile and Train
Compile, fit, and evaluate a Keras model.
Custom Training Loop
Step through batches with GradientTape.
Callbacks
Monitor and control training with callbacks.
Save and Load
Persist models in SavedModel and Keras formats.