Machine learning and deep learning basics with code
Table of Contents
- 1. TensorFlow/Keras Image Pipeline
- 2. CNN with PyTorch-Style Training Loops
- 3. RNN/LSTM for Sequence Forecasting
- 4. Transformer Encoder for Vision Patches
- 5. Q-Learning with Gymnasium Visual Debugger
Preview: TensorFlow/Keras Image Pipeline
A short excerpt from “TensorFlow/Keras Image Pipeline”. The full book contains 5 chapters and 2,652 words.
OverviewA folder of image paths becomes model-ready only after metadata, decoding, resizing, batching, and visual validation are connected. The Data-to-Display Conveyor uses pandas for indexed metadata, tf.data for efficient input flow, and Keras preprocessing for consistent image tensors; use it whenever labels originate from a CSV or directory listing.
Quick ReferenceStage
API
Output
Metadata
pandas.read_csv()
DataFrame with paths and labels
Split
DataFrame.sample()
Training and validation rows
Decode
tf.io.read_file(), tf.image.decode_jpeg()
Image tensor
Resize
tf.image.resize()
Fixed-size tensor
Preprocess
keras.layers.Rescaling()
Floating-point values
Pipeline
tf.data.Dataset
Batched, prefetched data
Visual check
matplotlib.pyplot.imshow()
Image grid with labels
ParametersParameter
Type
Required
Description
csv_path
str
Yes
CSV containing filepath and label columns.
image_size
tuple[int, int]
No
Target height and width; default (224, 224).
batch_size
int
No
Images per batch; default 32.
validation_fraction
float
No
Fraction reserved for validation; default 0.2.
seed
int
No
Reproducible split and shuffle seed; default 42.
num_parallel_calls
int or tf.data.AUTOTUNE
No
Parallel mapping workers; default AUTOTUNE.
shuffle_buffer
int
No
Training shuffle buffer size; default 1000.
Code Exampleimport pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow import keras
CSV columns: filepath,label
df = pd.read_csv("images.csv")
df["label_id"] = df["label"].astype("category").cat.codes
train_df = df.sample(frac=0.8, random_state=42)
valid_df = df.drop(train_df.index)
image_size = (224, 224)
batch_size = 32
num_classes = df["label_id"].nunique()
def decode_image(path, label):
image = tf.io.read_file(path)
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, image_size)
image = tf.cast(image, tf.float32) / 255.0
return image, label
def make_dataset(frame, training=False):
paths = frame["filepath"].to_numpy()
labels = frame["label_id"].to_numpy()
ds = tf.data.Dataset.from_tensor_slices((paths, labels))
if training:
ds = ds.shuffle(1000, seed=42, reshuffle_each_iteration=True)
return (ds.map(decode_image, num_parallel_calls=tf.data.AUTOTUNE)
.batch(batch_size)
.prefetch(tf.data.AUTOTUNE))
train_ds = make_dataset(train_df, training=True)
valid_ds = make_dataset(valid_df)
Keras preprocessing can be inserted before a model.
preprocess = keras.Sequential([
keras.layers.RandomFlip("horizontal"),
keras.layers.RandomRotation(0.05),
])
images, labels = next(iter(train_ds))
augmented = preprocess(images, training=True)
plt.figure(figsize=(8, 8))
for i in range(min(9, len(images))):
plt.subplot(3, 3, i + 1)
plt.imshow(augmented[i])
plt.title(f"class={labels[i].numpy()}")
plt.axis("off")
plt.tight_layout()
plt.show()Response FormatThe pipeline returns batches with this structure:
{
"images": "float32 tensor with shape [batch_size, 224, 224, 3], values in [0, 1]",
"labels": "int32 tensor with shape [batch_size]",
"example": {
"image": "decoded RGB image resized to the configured dimensions",
"label": "integer class ID derived from the pandas category mapping"
}
}Notes & Best PracticesValidate paths before creating the dataset; missing files fail during iteration, not CSV loading.
Use stratified splitting when classes are imbalanced; a random split can omit rare labels from validation.
Match preprocessing to the model. Do not divide by 255 twice when using keras.layers.Rescaling(1./255).
Inspect unaugmented and augmented batches. Incorrect color channels, distorted aspect ratios, and label mismatches are easiest to detect before training.
About this book
"Deep Learning Foundations With Code" is a technical book by Wilson Adhikari with 5 chapters and approximately 2,652 words. Machine learning and deep learning basics with code.
This book was created using Inkfluence AI, an AI-powered book generation platform that helps authors write, design, and publish complete books. It was made with the AI Documentation Generator.
Frequently Asked Questions
What is "Deep Learning Foundations With Code" about?
Machine learning and deep learning basics with code
How many chapters are in "Deep Learning Foundations With Code"?
The book contains 5 chapters and approximately 2,652 words. Topics covered include TensorFlow/Keras Image Pipeline, CNN with PyTorch-Style Training Loops, RNN/LSTM for Sequence Forecasting, Transformer Encoder for Vision Patches, and more.
Who wrote "Deep Learning Foundations With Code"?
This book was written by Wilson Adhikari and created using Inkfluence AI, an AI book generation platform that helps authors write, design, and publish books.
How can I create a similar technical book?
You can create your own technical book using Inkfluence AI. Describe your idea, choose your style, and the AI writes the full book for you. It's free to start.
Write your own technical book with AI
Describe your idea and Inkfluence writes the whole thing. Free to start.
Start writingCreated with Inkfluence AI