concept shape in category deep learning

This is an excerpt from Manning's book Deep Learning with Python, Second Edition.
Before training, we’ll preprocess the data by reshaping it into the shape the model expects and scaling it so that all values are in the
[0, 1]interval. Previously, our training images, for instance, were stored in an array of shape(60000, 28, 28)of typeuint8with values in the[0, 255]interval. We transform it into afloat32array of shape(60000, 28 * 28)with values between 0 and 1.
Images typically have three dimensions: height, width, and color depth. Although grayscale images (like our MNIST digits) have only a single color channel and could thus be stored in rank-2 tensors, by convention image tensors are always rank-3, with a one-dimensional color channel for grayscale images. A batch of 128 grayscale images of size 256 × 256 could thus be stored in a tensor of shape
(128, 256, 256, 1), and a batch of 128 color images could be stored in a tensor of shape(128, 256, 256, 3)(see figure 2.4).Figure 2.4. A rank-4 image data tensor (channels-first convention)
![]()
There are two conventions for shapes of images tensors: the channels-last convention (which is standard in TensorFlow) and the channels-first convention.
Listing 3.14. Stacking the two classes into an array with shape (2000, 2)
inputs = np.vstack((negative_samples, positive_samples)).astype(np.float32)

This is an excerpt from Manning's book Deep Learning for Vision Systems.
Lung cancer diagnosis:
Lung cancer is such a growing problem. Several computer vision companies decided to tackle this challenge using deep learning technology. The main reason lung cancer is very dangerous is that when doctors diagnose patients with lung cancer it is usually in the mid or later stages. When diagnosing lung cancer, doctors typically use their eyes to examine CT scan images looking for small nodules in the lungs. At early stages, the nodules are usually very small and harder to spot.
Almost every single lung cancer started as a smaller nodule and they appear in a big variety of shapes which takes a doctor years to learn all these different shapes. Doctors are very good at identifying mid and large size of nodules such as 6-10 millimeters. But looking at smaller nodules like 4 mm or smaller sometimes they have difficulties identifying them. Deep learning networks, specifically CNNs, are now able to learn these features automatically from XRay and CT scan images and detect small nodules early before they become deadly.
Alright, the Flatten layer in Keras takes care of this process for us. It takes the 2D image matrix input and converts it to a 1D vector. Note that the Flatten layer must be supplied a parameter value of the shape of the input image. Now the image is ready to be fed to the neural network. What’s next? Hidden layers.
# define the path to your input image base_image_path = 'input.jpg' img = preprocess_image(base_image_path) original_shape = img.shape[1:3] successive_shapes = [original_shape] for i in range(1, num_octave): shape = tuple([int(dim / (octave_scale ** i)) for dim in original_shape]) successive_shapes.append(shape) successive_shapes = successive_shapes[::-1] original_img = np.copy(img) shrunk_original_img = resize_img(img, successive_shapes[0]) for shape in successive_shapes: print('Processing image shape', shape) img = resize_img(img, shape) img = gradient_ascent(img, iterations=iterations, step=step, max_loss=max_loss) upscaled_shrunk_original_img = resize_img(shrunk_original_img, shape) same_size_original = resize_img(original_img, shape) lost_detail = same_size_original - upscaled_shrunk_original_img img += lost_detail shrunk_original_img = resize_img(original_img, shape) phil_img = deprocess_image(np.copy(img)) save_img('deepdream_output/dream_at_scale_' + str(shape) + '.png', phil_img) # save the result to disk final_img = deprocess_image(np.copy(img)) save_img('final_dream.png', final_img)

This is an excerpt from Manning's book Deep Learning with JavaScript: Neural networks in TensorFlow.js.
First off, what is a tensor? It is just a computer scientist’s way of saying “multidimensional array” concisely. In neural networks and deep learning, every piece of data and every computation result is represented as a tensor. For example, a grayscale image can be represented as a 2D array of numbers—a 2D tensor; a color image is usually represented as a 3D tensor, with the extra dimension being the color channels. Sounds, videos, text, and any other types of data can all be represented as tensors. Each tensor has two basic properties: the data type (such as float32 or int32) and the shape. Shape describes the size of the tensor along all its dimensions. For instance, a 2D tensor may have the shape [128, 256], and a 3D tensor may have the shape [10, 20, 128]. Once data is turned into a tensor of a given data type and shape, it can be fed into any type of layer that accepts that data type and shape, regardless of the data’s original meaning. Therefore, the tensor is the lingua franca of deep-learning models.
But why tensors? In the previous section, we learned that the bulk of the computations involved in running a deep neural network are performed as massively parallelized operations, commonly on GPUs, which require performing the same computation on multiple pieces of data. Tensors are containers that organize our data into structures that can be processed efficiently in parallel. When we add tensor A with shape [128, 128] to tensor B with shape [128, 128], it is very clear that there are 128 * 128 independent additions that need to take place.
Remember that a tensor is simply a data container. Every tensor has two fundamental properties: data type (dtype) and shape. dtype controls what kinds of values are stored within the tensor. A given tensor can store only one kind of value. At the time of this writing (version 0.13.5), the supported dtypes are float32, int32, and bool.
The shape is an array of integers indicating how many elements are in the tensor and how they are organized. It can be thought of as the “shape and size” of the container that is the tensor (see figure B.1).
The length of the shape is known as the tensor’s rank. For example, a 1D tensor, also known as a vector, has rank 1. The shape of a 1D tensor is an array containing one number, and that number tells us how long the 1D tensor is. Increasing rank by one, we get a 2D tensor, which can be visualized as a grid of numbers in a 2D plane (like a grayscale image). The shape of a 2D tensor has two numbers, which tell us how tall and how wide the grid is. Further increasing the rank by one, we get a 3D tensor. As shown in the example in figure B.1, you can visualize a 3D tensor as a 3D grid of numbers. The shape of a 3D tensor consists of three integers; they tell us the size of the 3D grid along the three dimensions. So, you see the pattern. Tensors of rank 4 (4D tensors) are harder to visualize directly because the world we live in has only three spatial dimensions. 4D tensors are frequently used in many models, such as deep convnets. TensorFlow.js supports tensors up to rank 6. In practice, rank-5 tensors are used only in some niche cases (for example, those involving video data), while rank-6 tensors are encountered even more rarely.
In the tf.tensor2d() call, we provided a nested JavaScript array as the argument. The argument consists of rows of arrays nested within another array. This nesting structure is used by tf.tensor2d() to infer the shape of the 2D tensor—that is, how many rows and how many columns there are, respectively. An alternative way to create the same 2D tensor with tf.tensor2d() is to provide the elements as a flat (non-nested) JavaScript array and accompany it by a second argument that specifies the shape of the 2D tensor:
> const myMatrix = tf.tensor2d([1, 2, 3, 40, 50, 60], [2, 3]); > myMatrix.shape; [2, 3] > myMatrix.rank; 2In this approach, the product of all the numbers in the shape argument must match the number of elements in the float array, or else an error will be thrown during the tf.tensor2d() call. For tensors of ranks higher than 2, there are also two analogous approaches to tensor creation: using either a single nested array as the argument or a flat array accompanied by a shape argument. You will see both approaches used in different examples throughout this book.

This is an excerpt from Manning's book Deep Learning with R.
Before training, we’ll preprocess the data by reshaping it into the shape the network expects and scaling it so that all values are in the [0, 1] interval. Previously, our training images, for instance, were stored in an array of shape (60000, 28, 28) of type integer with values in the [0, 255] interval. We transform it into a double array of shape (60000, 28 * 28) with values between 0 and 1.
Images typically have three dimensions: height, width, and color depth. Although grayscale images (like our MNIST digits) have only a single color channel and could thus be stored in 2D tensors, by convention image tensors are always 3D, with a one-dimensional color channel for grayscale images. A batch of 128 grayscale images of size 256 × 256 could thus be stored in a tensor of shape (128, 256, 256, 1), and a batch of 128 color images could be stored in a tensor of shape (128, 256, 256, 3) (see figure 2.4).
There are two conventions for shapes of images tensors: the channels-last convention (used by TensorFlow) and the channels-first convention (used by Theano). The TensorFlow machine-learning framework, from Google, places the color-depth axis at the end: (samples, height, width, color_depth). Meanwhile, Theano places the color depth axis right after the batch axis: (samples, color_depth, height, width). With the Theano convention, the previous examples would become (128, 1, 256, 256) and (128, 3, 256, 256). The Keras framework provides support for both formats.
Vector data—2D tensors of shape (samples, features) Timeseries data or sequence data—3D tensors of shape (samples, timesteps, features) Images—4D tensors of shape (samples, height, width, channels) or (samples, channels, height, width) Video—5D tensors of shape (samples, frames, height, width, channels) or (samples, frames, channels, height, width)
Listing 8.12. Running gradient ascent over different successive scales
step <- 0.01 12 num_octave <- 3 13 octave_scale <- 1.4 14 iterations <- 20 15 max_loss <- 10 6 base_image_path <- "..." 7 img <- preprocess_image(base_image_path) 8 original_shape <- dim(img)[-1] 9 successive_shapes <- list(original_shape) for (i in 1:num_octave) { shape <- as.integer(original_shape / (octave_scale ^ i)) successive_shapes[[length(successive_shapes) + 1]] <- shape } successive_shapes <- rev(successive_shapes) 10 original_img <- img shrunk_original_img <- resize_img(img, successive_shapes[[1]]) 11 for (shape in successive_shapes) { cat("Processsing image shape", shape, "\n") img <- resize_img(img, shape) 12 img <- gradient_ascent(img, 13 iterations = iterations, step = step, max_loss = max_loss) upscaled_shrunk_original_img <- resize_img(shrunk_original_img, shape) 14 same_size_original <- resize_img(original_img, shape) 15 lost_detail <- same_size_original - upscaled_shrunk_original_img 16 img <- img + lost_detail 17 shrunk_original_img <- resize_img(original_img, shape) save_img(img, fname = sprintf("dream_at_scale_%s.png", paste(shape, collapse = "x"))) }

This is an excerpt from Manning's book Deep Learning with Python.
Before training, we’ll preprocess the data by reshaping it into the shape the network expects and scaling it so that all values are in the [0, 1] interval. Previously, our training images, for instance, were stored in an array of shape (60000, 28, 28) of type uint8 with values in the [0, 255] interval. We transform it into a float32 array of shape (60000, 28 * 28) with values between 0 and 1.
Images typically have three dimensions: height, width, and color depth. Although grayscale images (like our MNIST digits) have only a single color channel and could thus be stored in 2D tensors, by convention image tensors are always 3D, with a one-dimensional color channel for grayscale images. A batch of 128 grayscale images of size 256 × 256 could thus be stored in a tensor of shape (128, 256, 256, 1), and a batch of 128 color images could be stored in a tensor of shape (128, 256, 256, 3) (see figure 2.4).
There are two conventions for shapes of images tensors: the channels-last convention (used by TensorFlow) and the channels-first convention (used by Theano). The TensorFlow machine-learning framework, from Google, places the color-depth axis at the end: (samples, height, width, color_depth). Meanwhile, Theano places the color depth axis right after the batch axis: (samples, color_depth, height, width). With the Theano convention, the previous examples would become (128, 1, 256, 256) and (128, 3, 256, 256). The Keras framework provides support for both formats.
Our earlier naive implementation of naive_add only supports the addition of 2D tensors with identical shapes. But in the Dense layer introduced earlier, we added a 2D tensor with a vector. What happens with addition when the shapes of the two tensors being added differ?
When possible, and if there’s no ambiguity, the smaller tensor will be broadcasted to match the shape of the larger tensor. Broadcasting consists of two steps:
import numpy as np x = np.random.random((64, 3, 32, 10)) #1 y = np.random.random((32, 10)) #2 z = np.maximum(x, y) #3 #1 - x is a random tensor with shape (64, 3, 32, 10). #2 - y is a random tensor with shape (32, 10). #3 - The output z has shape (64, 3, 32, 10) like x.