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
Aug 18
High Performance And Low Overhead Graphs With KuzuDB
SummaryIn this episode of the Data Engineering Podcast Prashanth Rao, an AI engineer at KuzuDB, talks about their embeddable graph database. Prashanth explains how KuzuDB addresses performance shortcomings in existing solutions through columnar storage and novel join algorithms. ... Show More
1h 1m
Jul 2024
The Rise of Generative AI Video Tools
Episode 13: What impact will AI-generated content have on the entertainment industry? Matt Wolfe (https://x.com/mreflow) and Nathan Lands (https://x.com/NathanLands) dive into this topic, envisioning a future where AI generates interactive movies and complex gaming worlds with in ... Show More
43m 48s
Sep 18
From RAG to Relational: How Agentic Patterns Are Reshaping Data Architecture
SummaryIn this episode of the AI Engineering Podcast Mark Brooker, VP and Distinguished Engineer at AWS, talks about how agentic workflows are transforming database usage and infrastructure design. He discusses the evolving role of data in AI systems, from traditional models to m ... Show More
52m 58s
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
Apr 2025
Canva Create 2025 - What's New for Educators? - HoET261
In this exciting crossover episode, Chris Nesi teams up with Leena Marie Saleh (The EdTech Guru) for a detailed look into Canva’s latest educational innovations unveiled during Canva Create 2025. Whether you’re a teacher, instructional coach, or tech integrator, this episode is p ... Show More
54m 32s
Jun 2025
806 : Topical English Vocabulary Lesson With Teacher Tiffani about Digital Art
In today’s episode, you will learn a series of vocabulary words that are connected to a specific topic. This lesson will help you improve your ability to speak English fluently about a specific topic. It will also help you feel more confident in your English abilities.5 Vocabular ... Show More
13m 21s
Jul 2024
Rendering Revolutions: Chaos founder Vlado Koylazov's Journey from V-Ray to Virtual Production
This podcast episode features Vlado Koylazov, co-founder of Chaos and inventor of the widely-used V-Ray rendering software. Koylazov shares his journey in computer graphics, from his early fascination with the field to the development of V-Ray and the latest innovations at Chaos. ... Show More
42m 42s
Sep 2024
Pausing to think about scikit-learn & OpenAI o1
Recently the company stewarding the open source library scikit-learn announced their seed funding. Also, OpenAI released “o1” with new behavior in which it pauses to “think” about complex tasks. Chris and Daniel take some time to do their own thinking about o1 and the contrast to ... Show More
50m 10s
Aug 2023
Deepdub’s Ofir Krakowski on Redefining Dubbing from Hollywood to Bollywood - Ep. 202
In the global entertainment landscape, TV show and film production stretches far beyond Hollywood or Bollywood — it's a worldwide phenomenon. However, while streaming platforms have broadened the reach of content, dubbing and translation technology still has plenty of room for gr ... Show More
32m 37s
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