Examples
Four working TensorFlow snippets you adapt to most projects: text classifier, image classifier with transfer learning, simple regression, and a custom training loop. Each is short enough to lift; the patterns scale to bigger models.
Four working TF examples
EXAMPLE
import tensorflow as tf
# ===== 1) Text classification with TF-IDF -> Dense =====
import numpy as np
texts = ['great product', 'awful service', 'love it', 'broken on arrival']
labels = np.array([1, 0, 1, 0])
vectorizer = tf.keras.layers.TextVectorization(
max_tokens=2000, output_mode='tf_idf', ngrams=2)
vectorizer.adapt(texts)
model = tf.keras.Sequential([
vectorizer,
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid'),
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(np.array(texts), labels, epochs=4, verbose=0)
print(model.predict(np.array(['really good'])))
# ===== 2) Image classification with transfer learning =====
IMG, BATCH = 224, 32
train = tf.keras.utils.image_dataset_from_directory('data/train',
image_size=(IMG, IMG), batch_size=BATCH, label_mode='int')
val = tf.keras.utils.image_dataset_from_directory('data/val',
image_size=(IMG, IMG), batch_size=BATCH, label_mode='int')
aug = tf.keras.Sequential([
tf.keras.layers.RandomFlip('horizontal'),
tf.keras.layers.RandomRotation(0.05),
tf.keras.layers.RandomZoom(0.1),
])
base = tf.keras.applications.MobileNetV3Small(
input_shape=(IMG, IMG, 3), include_top=False, weights='imagenet')
base.trainable = False # freeze the backbone
x = tf.keras.Input(shape=(IMG, IMG, 3))
y = aug(x)
y = tf.keras.applications.mobilenet_v3.preprocess_input(y)
y = base(y, training=False)
y = tf.keras.layers.GlobalAveragePooling2D()(y)
y = tf.keras.layers.Dropout(0.2)(y)
y = tf.keras.layers.Dense(10)(y)
model = tf.keras.Model(x, y)
model.compile(optimizer=tf.keras.optimizers.AdamW(1e-3),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train, validation_data=val, epochs=3)
# Fine-tune the last layers
base.trainable = True
for layer in base.layers[:-30]: layer.trainable = False
model.compile(optimizer=tf.keras.optimizers.AdamW(1e-5),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train, validation_data=val, epochs=2)
# ===== 3) Regression =====
import pandas as pd
df = pd.read_csv('houses.csv')
y = df.pop('price'); X = df.values.astype('float32')
norm = tf.keras.layers.Normalization(); norm.adapt(X)
reg = tf.keras.Sequential([
norm,
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(1),
])
reg.compile(optimizer='adam', loss='mae')
reg.fit(X, y, epochs=20, validation_split=0.2, verbose=0)
# ===== 4) Custom training loop with GradientTape =====
opt = tf.keras.optimizers.Adam(1e-3)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
@tf.function
def step(xb, yb, m):
with tf.GradientTape() as tape:
logits = m(xb, training=True)
loss = loss_fn(yb, logits)
grads = tape.gradient(loss, m.trainable_weights)
opt.apply_gradients(zip(grads, m.trainable_weights))
return loss
for epoch in range(3):
for xb, yb in train:
l = step(xb, yb, model)
print(f'epoch {epoch} loss {l.numpy():.4f}')
Why it matters
Wrap your training step in @tf.function — Keras `.fit()` does this for you, but the custom-loop version benefits identically and runs many times faster than the eager Python loop. Profile the FIRST step separately (it includes graph build time) and the steady-state speed is what you see in production.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…