logo
episode-header-image
Jun 2018
27m 18s

MLA 005 Shapes and Sizes: Tensors and ND...

OCDevel
About this episode

Explains the fundamental differences between tensor dimensions, size, and shape, clarifying frequent misconceptions—such as the distinction between the number of features (“columns”) and true data dimensions—while also demystifying reshaping operations like expand_dims, squeeze, and transpose in NumPy. Through practical examples from images and natural language processing, listeners learn how to manipulate tensors to match model requirements, including scenarios like adding dummy dimensions for grayscale images or reordering axes for sequence data.

Links Definitions
  • Tensor: A general term for an array of any number of dimensions.

    • 0D Tensor (Scalar): A single number (e.g., 5).
    • 1D Tensor (Vector): A simple list of numbers.
    • 2D Tensor (Matrix): A grid of numbers (rows and columns).
    • 3D+ Tensors: Higher-dimensional arrays, such as images or batches of images.
  • NDArray (NumPy): Stands for "N-dimensional array," the foundational array type in NumPy, synonymous with "tensor."

Tensor Properties Dimensions
  • Number of nested levels in the array (e.g., a matrix has two dimensions: rows and columns).
  • Access in NumPy: Via .ndim property (e.g., array.ndim).
Size
  • Total number of elements in the tensor.
  • Examples:
    • Scalar: size = 1
    • Vector: size equals number of elements (e.g., 5 for [1, 2, 3, 4, 5])
    • Matrix: size = rows × columns (e.g., 10×10 = 100)
  • Access in NumPy: Via .size property.
Shape
  • Tuple listing the number of elements per dimension.
  • Example: An image with 256×256 pixels and 3 color channels has shape = (256, 256, 3).
Common Scenarios & Examples Data Structures in Practice
  • CSV/Spreadsheet Example: Dataset with 1 million housing examples and 50 features:
    • Shape: (1_000_000, 50)
    • Size: 50,000,000
  • Image Example (RGB): 256×256 pixel image:
    • Shape: (256, 256, 3)
    • Dimensions: 3 (width, height, channels)
  • Batching for Models:
    • For a convolutional neural network, shape might become (batch_size, width, height, channels), e.g., (32, 256, 256, 3).
Conceptual Clarifications
  • The term "dimensions" in data science often refers to features (columns), but technically in tensors it means the number of structural axes.
  • The "curse of dimensionality" often uses "dimensions" to refer to features, not tensor axes.
Reshaping and Manipulation in NumPy Reshaping Tensors
  • Adding Dimensions:

    • Useful when a model expects higher-dimensional input than currently available (e.g., converting grayscale image from shape (256, 256) to (256, 256, 1)).
    • Use np.expand_dims or array.reshape.
  • Removing Singleton Dimensions:

    • Occurs when, for example, model output is (N, 1) and single dimension should be removed to yield (N,).
    • Use np.squeeze or array.reshape.
  • Wildcard with -1:

    • In reshaping, -1 is a placeholder for NumPy to infer the correct size, useful when batch size or another dimension is variable.
  • Flattening:

    • Use np.ravel to turn a multi-dimensional tensor into a contiguous 1D array.
Axis Reordering
  • Transposing Axes:
    • Needed when model input or output expects axes in a different order (e.g., sequence length and embedding dimensions in NLP).
    • Use np.transpose for general axis permutations.
    • Use np.swapaxes to swap two specific axes but prefer transpose for clarity and flexibility.
Practical Example
  • In NLP sequence models:
    • 3D tensor with (batch_size, sequence_length, embedding_dim) might need to be reordered to (batch_size, embedding_dim, sequence_length) for certain models.
    • Achieved using: array.transpose(0, 2, 1)
Core NumPy Functions for Manipulation
  • reshape: General function for changing the shape of a tensor, including adding or removing dimensions.
  • expand_dims: Adds a new axis with size 1.
  • squeeze: Removes axes with size 1.
  • ravel: Flattens to 1D.
  • transpose: Changes the order of axes.
  • swapaxes: Swaps specified axes (less general than transpose).
Summary Table of Operations Operation NumPy Function Purpose Add dimension np.expand_dims Convert (256,256) to (256,256,1) Remove dimension np.squeeze Convert (N,1) to (N,) General reshape np.reshape Any change matching total size Flatten np.ravel Convert (a,b) to (a*b,) Swap axes np.swapaxes Exchange positions of two axes Permute axes np.transpose Reorder any sequence of axes Closing Notes
  • A deep understanding of tensor structure - dimensions, size, and shape - is vital for preparing data for machine learning models.
  • Reshaping, expanding, squeezing, and transposing tensors are everyday tasks in model development, especially for adapting standard datasets and models to each other.
Up next
Jul 14
MLA 027 AI Video End-to-End Workflow
How to maintain character consistency, style consistency, etc in an AI video. Prosumers can use Google Veo 3’s "High-Quality Chaining" for fast social media content. Indie filmmakers can achieve narrative consistency by combining Midjourney V7 for style, Kling for lip-synced dial ... Show More
1h 11m
Jul 12
MLA 026 AI Video Generation: Veo 3 vs Sora, Kling, Runway, Stable Video Diffusion
Google Veo leads the generative video market with superior 4K photorealism and integrated audio, an advantage derived from its YouTube training data. OpenAI Sora is the top tool for narrative storytelling, while Kuaishou Kling excels at animating static images with realistic, hig ... Show More
40m 39s
Jul 9
MLA 025 AI Image Generation: Midjourney vs Stable Diffusion, GPT-4o, Imagen & Firefly
The AI image market has split: Midjourney creates the highest quality artistic images but fails at text and precision. For business use, OpenAI's GPT-4o offers the best conversational control, while Adobe Firefly provides the strongest commercial safety from its exclusively licen ... Show More
58m 51s
Recommended Episodes
Sep 2024
Large Language Model (LLM) Risks and Mitigation Strategies
As machine learning algorithms continue to evolve, Large Language Models (LLMs) like GPT-4 are gaining popularity. While these models hold great promise in revolutionizing various functions and industries—ranging from content generation and customer service to research and develo ... Show More
28m 58s
Jul 28
Revolutionizing Python Notebooks with Marimo
SummaryIn this episode of the Data Engineering Podcast Akshay Agrawal from Marimo discusses the innovative new Python notebook environment, which offers a reactive execution model, full Python integration, and built-in UI elements to enhance the interactive computing experience. ... Show More
51m 56s
Apr 2025
Andriy Burkov - The TRUTH About Large Language Models and Agentic AI (with Andriy Burkov, Author "The Hundred-Page Language Models Book")
Andriy Burkov is a renowned machine learning expert and leader. He's also the author of (so far) three books on machine learning, including the recently-released "The Hundred-Page Language Models Book", which takes curious people from the very basics of language models all the wa ... Show More
1h 24m
Jul 2024
Building Real-World LLM Products with Fine-Tuning and More with Hamel Husain - #694
Today, we're joined by Hamel Husain, founder of Parlance Labs, to discuss the ins and outs of building real-world products using large language models (LLMs). We kick things off discussing novel applications of LLMs and how to think about modern AI user experiences. We then dig i ... Show More
1h 20m
Aug 2024
Episode 201 - Introduction to KitOps for MLOps
Join Allen and Mark in this episode of Two Voice Devs as they dive into the world of MLOps and explore KitOps, an open-source tool for packaging and versioning machine learning models and related artifacts. Learn how KitOps leverages the Open Container Initiative (OCI) standard t ... Show More
33m 59s
Apr 2025
Simplifying Data Pipelines with Durable Execution
Summary In this episode of the Data Engineering Podcast Jeremy Edberg, CEO of DBOS, about durable execution and its impact on designing and implementing business logic for data systems. Jeremy explains how DBOS's serverless platform and orchestrator provide local resilience and r ... Show More
39m 49s
Aug 2024
Metrics Driven Development
How do you systematically measure, optimize, and improve the performance of LLM applications (like those powered by RAG or tool use)? Ragas is an open source effort that has been trying to answer this question comprehensively, and they are promoting a “Metrics Driven Development” ... Show More
42m 12s
Nov 2024
Code Generation & Synthetic Data With Loubna Ben Allal #51
Our guest today is Loubna Ben Allal, Machine Learning Engineer at Hugging Face 🤗 . In our conversation, Loubna first explains how she built two impressive code generation models: StarCoder and StarCoder2. We dig into the importance of data when training large models and what can ... Show More
47m 6s
Feb 2025
LLMs and Graphs Synergy
In this episode, Garima Agrawal, a senior researcher and AI consultant, brings her years of experience in data science and artificial intelligence. Listeners will learn about the evolving role of knowledge graphs in augmenting large language models (LLMs) for domain-specific task ... Show More
34m 47s
Dec 2024
The Art of Database Selection and Evolution
Summary In this episode of the Data Engineering Podcast Sam Kleinman talks about the pivotal role of databases in software engineering. Sam shares his journey into the world of data and discusses the complexities of database selection, highlighting the trade-offs between differen ... Show More
59m 56s