liveBook · Manning

Chapter 4: Real-world data representation using tensors

What you will learn in chapter 4 of Deep Learning with PyTorch, Second Edition

This introduction explains why representing real-world data as tensors matters for using PyTorch neural networks.

After this chapter you will be able to

What it builds on

Section by section

Introduction

This introduction explains why representing real-world data as tensors matters for using PyTorch neural networks.

Key terms: tensors, inputs, outputs, parameters, weights, biases

4.1 Working with images

This section introduces images as grids of numerical pixel values and explains why those values must be represented appropriately as PyTorch tensors.

Key terms: pixels, grayscale image, scalar value, tensor representation, 8-bit integers, 12-bit, 16-bit, numerical precision

4.1.1 Adding color channels

This section explains how RGB represents image colors with three intensity channels and how to interpret each channel as a grayscale map.

Key terms: RGB, color channel, intensity, grayscale intensity map

4.1.2 Loading an image file

This section introduces loading an image with imageio and explains how the resulting array’s dimensions relate to the layout PyTorch image modules require.

Key terms: img_arr, NumPy array-like object, red, green, and blue channels, C × H × W, imageio, TorchVision, NumPy array

4.1.3 Changing the layout

This section changes image tensors to a channel-first layout and shows how to store multiple images in a batch tensor.

Key terms: permute, H × W × C, size, stride, underlying storage, batch, N × C × H × W, RGB, 8-bit integer

4.1.4 Normalizing the data

Explains why image tensors are converted to floating point and normalized, and compares two ways to scale pixel values.

Key terms: floating-point tensors, normalize, 255, standardization, mean, standard deviation, channel

4.2 3D images: Volumetric data

This section explains how stacked CT slices become volumetric tensors and what their intensity values represent.

Key terms: slice, volumetric data, depth, channel dimension, N × C × D × H × W, intensity, density, single intensity channel, native data formats

4.2.1 Loading a specialized format

Shows how to load a DICOM CT series as a volume and add the channel dimension expected by PyTorch.

Key terms: volread, imageio, DICOM, NumPy 3D array, unsqueeze, channel dimension, batch direction, [D, H, W], [1, D, H, W]

4.3 Representing tabular data

This section describes the structure of tabular data and explains why its mixed column types must be represented numerically for PyTorch models.

Key terms: sample, record, column, independent samples, time series, tabular data, homogeneous, numerical values, labels, PyTorch tensors

4.3.1 Using a real-world dataset

Introduces the Wine Quality table as a real-world example of using chemical measurements to predict a sensory quality score.

Key terms: Wine Quality dataset, chemical variables, sensory quality score

4.3.2 Loading a wine data tensor

The section loads a wine CSV into a PyTorch tensor and explains what different kinds of numerical values do—and do not—mean.

Key terms: CSV, NumPy array, 32-bit floating-point, torch.Tensor, quality score, continuous values, ratio scale, interval scale, ordinal values, categorical values

4.3.3 Representing scores

The section shows how a wine score can serve as either a continuous regression target or a classification label, kept separate from the model’s inputs.

Key terms: score, continuous variable, regression task, label, classification task, ground truth, target tensor, labels, integer vector, string labels

4.3.4 One-hot encoding

This section explains when to represent wine scores as one-hot categories rather than integers and how to construct that representation with PyTorch.

Key terms: one-hot encoding, ordering, equal intervals, categorical data, scatter_, index tensor, unsqueeze, singleton dimension, in place, class indices

4.3.5 When to categorize

The section explains the trade-offs in treating ordinal data as categorical or continuous, then shows how to normalize the wine data column by column.

Key terms: ordinal, categorical, continuous, dim=0, reduction, mean, standard deviation, normalize

4.3.6 Finding thresholds

The section uses tensor masks to inspect wine-quality groups, tries a single-feature threshold, and checks how well its predictions match the actual ratings.

Key terms: advanced indexing, torch.bool, bad_indexes, bad_data, target, good, middling, and bad categories, .mean(), total sulfur dioxide, threshold, midpoint

4.4 Working with time series

The section contrasts independent rows in a flat table with data whose order conveys information over time, introducing bike-sharing counts as the example.

Key terms: flat table, year column

4.4.1 Adding a time dimension

The section explains why hourly bike-sharing data should be reshaped to preserve time order and separate days, hours, and recorded variables for neural-network input.

Key terms: time-series data, day, hour of the day, columns of data, time-series dataset, successive timepoints, ordering, causal relationships across time

4.4.2 Shaping the data by time period

This section reshapes hourly bike-sharing data into daily tensor sequences and explains why the chosen dimension order and continuous time periods matter.

Key terms: N × C × L, N × L × C, channels, sequences, view, storage, stride, transpose, daily_bikes, 24 hours

4.4.3 Ready for training

The section prepares hourly bike-rental data for training by encoding weather categories, handling the daily time-series layout, and rescaling quantitative variables.

Key terms: weather situation, ordinal, categorical, continuous variable, one-hot-encoded vector, one-hot encoding, scatter, unsqueeze, cat, daily_bikes

4.5 Representing text

This introduction explains why text must be represented as a tensor of numbers for neural networks and places that task in the context of modern NLP.

Key terms: tensor of numbers, reshaping the data, multistage pipelines, end to end, large corpora, recurrent neural networks (RNNs), transformers, past information

4.5.1 Converting text to numbers

This subsection introduces character-level and word-level text processing and identifies one-hot encoding as a way to represent either in tensors.

Key terms: character level, word level, one-hot encoding, tensor form

4.5.2 One-hot-encoding characters

The section explains character encodings, how to choose a useful character set, and how to represent each character in a line of text as a one-hot tensor row.

Key terms: ASCII, Unicode, UTF-8, UTF-16, UTF-32, character set, lowercase, one-hot encoding, letter_t, vector

4.5.3 One-hot encoding whole words

The section shows how to one-hot encode whole words, explains the tradeoff between character- and word-level representations, and introduces byte pair encoding as an intermediate approach.

Key terms: clean_words, word2index_dict, one-hot-encoded vector, vocabulary, character-level, word-level, dictionary, byte pair encoding, subunits

4.5.4 Text embeddings

This section explains why word embeddings offer a compact, meaningfully structured alternative to one-hot encoding and contrasts classic embeddings with context-sensitive ones.

Key terms: one-hot encoding, vocabulary, embedding, embedding vector, embedding space, context, neighboring regions, axes, corpus, neural networks

4.5.5 Text embeddings as a blueprint

The section uses text embeddings as a blueprint for representing categorical data and for thinking about co-occurrence and sequence problems beyond text.

Key terms: embeddings, one-hot encoding, embedding vectors, categorical data, prelearned embeddings, fine-tuning, word embeddings, co-occurrences, context, recommender systems

4.6 Conclusion

The conclusion recaps preparing common kinds of data for neural networks and notes that the book does not cover every data format.

Key terms: tensors, shape, neural network

4.7 Exercises

4.8 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 3: It starts with a tensor Chapter 5: The mechanics of learning →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.