TensorFlow Cheat Sheet
TensorFlow 2 model building, training loops, and deployment basics.
3 PagesAdvancedApr 22, 2026
Building a Model
Define a simple sequential model.
python
import tensorflow as tffrom tensorflow.keras import layersmodel = tf.keras.Sequential([ layers.Dense(64, activation='relu', input_shape=(784,)), layers.Dense(10, activation='softmax'),])
Compile & Train
Configure and run the training loop.
python
model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'],)model.fit(x_train, y_train, epochs=5, validation_split=0.1)
Tensors
Create and manipulate tensors.
python
t = tf.constant([[1, 2], [3, 4]])tf.reduce_sum(t)tf.reshape(t, [4])tf.cast(t, tf.float32)
Save & Deploy
Persist a trained model.
python
model.save('my_model.keras')loaded = tf.keras.models.load_model('my_model.keras')loaded.predict(x_test[:1])
tf.data Input Pipeline
Build a performant, batched, prefetched dataset.
python
import tensorflow as tfds = tf.data.Dataset.from_tensor_slices((x_train, y_train))ds = (ds .shuffle(buffer_size=10000) .batch(32) .map(lambda x, y: (x / 255.0, y), num_parallel_calls=tf.data.AUTOTUNE) .cache() .prefetch(tf.data.AUTOTUNE))model.fit(ds, epochs=10)
Custom Training Loop
Fine-grained control with GradientTape.
python
optimizer = tf.keras.optimizers.Adam()loss_fn = tf.keras.losses.SparseCategoricalCrossentropy()@tf.functiondef train_step(x, y): with tf.GradientTape() as tape: logits = model(x, training=True) loss = loss_fn(y, logits) grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) return lossfor epoch in range(epochs): for x_batch, y_batch in ds: loss = train_step(x_batch, y_batch)
Training Callbacks
Early stopping, checkpointing, and LR scheduling.
python
callbacks = [ tf.keras.callbacks.EarlyStopping( monitor='val_loss', patience=3, restore_best_weights=True), tf.keras.callbacks.ModelCheckpoint( 'best.keras', save_best_only=True, monitor='val_loss'), tf.keras.callbacks.ReduceLROnPlateau( monitor='val_loss', factor=0.5, patience=2), tf.keras.callbacks.TensorBoard(log_dir='./logs'),]model.fit(ds, validation_data=val_ds, epochs=50, callbacks=callbacks)
Distributed Training
Scale across multiple GPUs with MirroredStrategy.
python
strategy = tf.distribute.MirroredStrategy()print('Devices:', strategy.num_replicas_in_sync)with strategy.scope(): model = build_model() model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# Batch size is global; TF splits it across replicasmodel.fit(ds, epochs=10)
Pro Tip
Use model.summary() after building a model to sanity-check layer shapes before you spend time training.
Was this cheat sheet helpful?
Explore Topics
#TensorFlow#TensorFlowCheatSheet#DataScience#Advanced#BuildingAModel#CompileTrain#Tensors#SaveDeploy#MachineLearning#DevOps#CheatSheet#SkillVeris