{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Data Manipulation\n", "\n", ":label:`sec_ndarray`\n", "\n", "\n", "In order to get anything done, we need some way to store and manipulate data. \n", "Generally, there are two important things we need to do with data: \n", "(i) acquire them; and (ii) process them once they are inside the computer. \n", "There is no point in acquiring data without some way to store it, \n", "so let us get our hands dirty first by playing with synthetic data. \n", "To start, we introduce the $n$-dimensional array (`ndarray`), \n", "MXNet's primary tool for storing and transforming data.\n", "In MXNet, `ndarray` is a class and we call any instance \"an `ndarray`\".\n", "\n", "If you have worked with NumPy, the most widely-used \n", "scientific computing package in Python, \n", "then you will find this section familiar.\n", "That's by design. We designed MXNet's `ndarray` to be \n", "an extension to NumPy's `ndarray` with a few killer features.\n", "First, MXNet's `ndarray` supports asynchronous computation \n", "on CPU, GPU, and distributed cloud architectures, \n", "whereas NumPy only supports CPU computation. \n", "Second, MXNet's `ndarray` supports automatic differentiation. \n", "These properties make MXNet's `ndarray` suitable for deep learning.\n", "Throughout the book, when we say `ndarray`, \n", "we are referring to MXNet's `ndarray` unless otherwise stated.\n", "\n", "\n", "\n", "## Getting Started\n", "\n", "In this section, we aim to get you up and running,\n", "equipping you with the basic math and numerical computing tools\n", "that you will build on as you progress through the book. \n", "Do not worry if you struggle to grok some of \n", "the mathematical concepts or library functions. \n", "The following sections will revisit this material \n", "in the context of practical examples and it will sink. \n", "On the other hand, if you already have some background \n", "and want to go deeper into the mathematical content, just skip this section.\n", "\n", "To start, we import the `api` and `mxnet-engine` modules from Deep Java Library on maven. \n", "Here, the `api` module includes all high level Java APIs that will be used for data processing, training and inference. The `mxnet-engine` includes the implementation of those high level APIs using Apache MXnet framework.\n", "Using the DJL automatic engine mode, the MXNet native libraries with basic operations and functions implemented in C++ will be downloaded automatically when DJL is first used." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "1" } }, "outputs": [], "source": [ "%load ../utils/djl-imports" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An `ndarray` represents a (possibly multi-dimensional) array of numerical values.\n", "With one axis, an `ndarray` corresponds (in math) to a *vector*. \n", "With two axes, an `ndarray` corresponds to a *matrix*. \n", "Arrays with more than two axes do not have special \n", "mathematical names---we simply call them *tensors*.\n", "\n", "To start, we can use `arange` to create a row vector `x` \n", "containing the first $12$ integers starting with $0$, \n", "though they are created as floats by default.\n", "Each of the values in an `ndarray` is called an *element* of the `ndarray`.\n", "For instance, there are $12$ elements in the `ndarray` `x`.\n", "Unless otherwise specified, a new `ndarray` \n", "will be stored in main memory and designated for CPU-based computation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "2" } }, "outputs": [], "source": [ "NDManager manager = NDManager.newBaseManager();\n", "var x = manager.arange(12);\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we are using a [`NDManager`](https://javadoc.io/doc/ai.djl/api/latest/ai/djl/ndarray/NDManager.html) to create the `ndarray` x. `NDManager` implements the [AutoClosable](https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html) interface and manages the life cycles of the `ndarray`s it created. This is needed to help manage native memory consumption that Java Garbage Collector does not have control of. We usually wrap NDManager with try blocks so all `ndarray`s will be closed in time. To know more about memory management, read DJL's [documentation](https://github.com/deepjavalibrary/djl/blob/master/docs/development/memory_management.md)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "try(NDManager manager = NDManager.newBaseManager()){\n", " NDArray x = manager.arange(12);\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can access an `ndarray`'s *shape* (the length along each axis)\n", "by inspecting its `shape` property." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "3" } }, "outputs": [], "source": [ "x.getShape()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we just want to know the total number of elements in an `ndarray`,\n", "i.e., the product of all of the shape elements, \n", "we can inspect its `size` property. \n", "Because we are dealing with a vector here, \n", "the single element of its `shape` is identical to its `size`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "4" } }, "outputs": [], "source": [ "x.size()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To change the shape of an `ndarray` without altering \n", "either the number of elements or their values,\n", "we can invoke the `reshape` function.\n", "For example, we can transform our `ndarray`, `x`, \n", "from a row vector with shape ($12$,) to a matrix with shape ($3$, $4$).\n", "This new `ndarray` contains the exact same values, \n", "but views them as a matrix organized as $3$ rows and $4$ columns. \n", "To reiterate, although the shape has changed, \n", "the elements in `x` have not. \n", "Note that the `size` is unaltered by reshaping." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "5" } }, "outputs": [], "source": [ "x = x.reshape(3, 4);\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Reshaping by manually specifying every dimension is unnecessary. \n", "If our target shape is a matrix with shape (height, width),\n", "then after we know the width, the height is given implicitly.\n", "Why should we have to perform the division ourselves? \n", "In the example above, to get a matrix with $3$ rows, \n", "we specified both that it should have $3$ rows and $4$ columns. \n", "Fortunately, `ndarray` can automatically work out one dimension given the rest. \n", "We invoke this capability by placing `-1` for the dimension\n", "that we would like `ndarray` to automatically infer. \n", "In our case, instead of calling `x.reshape(3, 4)`, \n", "we could have equivalently called `x.reshape(-1, 4)` or `x.reshape(3, -1)`.\n", "\n", "Passing `create` method with only `Shape` will grab a chunk of memory and hands us back a matrix \n", "without bothering to change the value of any of its entries. \n", "This is remarkably efficient but we must be careful because \n", "the entries might take arbitrary values, including very big ones!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "6" } }, "outputs": [], "source": [ "manager.create(new Shape(3, 4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Typically, we will want our matrices initialized \n", "either with zeros, ones, some other constants, \n", "or numbers randomly sampled from a specific distribution.\n", "We can create an `ndarray` representing a tensor with all elements \n", "set to $0$ and a shape of ($2$, $3$, $4$) as follows:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "7" } }, "outputs": [], "source": [ "manager.zeros(new Shape(2, 3, 4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, we can create tensors with each element set to 1 as follows:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "8" } }, "outputs": [], "source": [ "manager.ones(new Shape(2, 3, 4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Often, we want to randomly sample the values\n", "for each element in an `ndarray`\n", "from some probability distribution.\n", "For example, when we construct arrays to serve\n", "as parameters in a neural network, we will\n", "typically initialize their values randomly.\n", "The following snippet creates an `ndarray` with shape ($3$, $4$).\n", "Each of its elements is randomly sampled\n", "from a standard Gaussian (normal) distribution\n", "with a mean of $0$ and a standard deviation of $1$." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "10" } }, "outputs": [], "source": [ "manager.randomNormal(0f, 1f, new Shape(3, 4), DataType.FLOAT32)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also just pass the shape and it will use default values for mean and standard deviation (0 and 1)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "manager.randomNormal(new Shape(3, 4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also specify the exact values for each element in the desired `ndarray`\n", "by supplying an array containing the numerical values and the desired shape." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "9" } }, "outputs": [], "source": [ "manager.create(new float[]{2, 1, 4, 3, 1, 2, 3, 4, 4, 3, 2, 1}, new Shape(3, 4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Operations\n", "\n", "This book is not about software engineering.\n", "Our interests are not limited to simply \n", "reading and writing data from/to arrays.\n", "We want to perform mathematical operations on those arrays.\n", "Some of the simplest and most useful operations \n", "are the *elementwise* operations. \n", "These apply a standard scalar operation \n", "to each element of an array.\n", "For functions that take two arrays as inputs,\n", "elementwise operations apply some standard binary operator \n", "on each pair of corresponding elements from the two arrays. \n", "We can create an elementwise function from any function \n", "that maps from a scalar to a scalar. \n", "\n", "In mathematical notation, we would denote such\n", "a *unary* scalar operator (taking one input)\n", "by the signature $f: \\mathbb{R} \\rightarrow \\mathbb{R}$.\n", "This just means that the function is mapping\n", "from any real number ($\\mathbb{R}$) onto another.\n", "Likewise, we denote a *binary* scalar operator\n", "(taking two real inputs, and yielding one output)\n", "by the signature $f: \\mathbb{R}, \\mathbb{R} \\rightarrow \\mathbb{R}$.\n", "Given any two vectors $\\mathbf{u}$ and $\\mathbf{v}$ *of the same shape*,\n", "and a binary operator $f$, we can produce a vector\n", "$\\mathbf{c} = F(\\mathbf{u},\\mathbf{v})$\n", "by setting $c_i \\gets f(u_i, v_i)$ for all $i$,\n", "where $c_i, u_i$, and $v_i$ are the $i^\\mathrm{th}$ elements\n", "of vectors $\\mathbf{c}, \\mathbf{u}$, and $\\mathbf{v}$.\n", "Here, we produced the vector-valued\n", "$F: \\mathbb{R}^d, \\mathbb{R}^d \\rightarrow \\mathbb{R}^d$\n", "by *lifting* the scalar function to an elementwise vector operation.\n", "\n", "In DJL, the common standard arithmetic operators\n", "(`+`, `-`, `*`, `/`, and `**`)\n", "have all been *lifted* to elementwise operations \n", "for any identically-shaped tensors of arbitrary shape. \n", "We can call elementwise operations on any two tensors of the same shape.\n", "In the following example, we use commas to formulate a $5$-element tuple,\n", "where each element is the result of an elementwise operation. Note: you need to use `add`, `sub`, `mul`, `div`, and `pow` as Java does not support overloading of these operators." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "11" } }, "outputs": [], "source": [ "var x = manager.create(new float[]{1f, 2f, 4f, 8f});\n", "var y = manager.create(new float[]{2f, 2f, 2f, 2f});\n", "x.add(y);" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "11" } }, "outputs": [], "source": [ "x.sub(y);" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "11" } }, "outputs": [], "source": [ "x.mul(y);" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "11" } }, "outputs": [], "source": [ "x.div(y);" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "11" } }, "outputs": [], "source": [ "x.pow(y);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Many more operations can be applied elementwise,\n", "including unary operators like exponentiation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "12" } }, "outputs": [], "source": [ "x.exp()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to elementwise computations, \n", "we can also perform linear algebra operations, \n", "including vector dot products and matrix multiplication.\n", "We will explain the crucial bits of linear algebra \n", "(with no assumed prior knowledge) in :numref:`sec_linear-algebra`.\n", "\n", "We can also *concatenate* multiple `ndarray`s together,\n", "stacking them end-to-end to form a larger `ndarray`. \n", "We just need to provide a list of `ndarray`s \n", "and tell the system along which axis to concatenate. \n", "The example below shows what happens when we concatenate \n", "two matrices along rows (axis $0$, the first element of the shape)\n", "vs. columns (axis $1$, the second element of the shape).\n", "We can see that the first output `ndarray`'s axis-$0$ length ($6$)\n", "is the sum of the two input `ndarray`s' axis-$0$ lengths ($3 + 3$);\n", "while the second output `ndarray`'s axis-$1$ length ($8$)\n", "is the sum of the two input `ndarray`s' axis-$1$ lengths ($4 + 4$)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "14" } }, "outputs": [], "source": [ "x = manager.arange(12f).reshape(3, 4);\n", "y = manager.create(new float[]{2, 1, 4, 3, 1, 2, 3, 4, 4, 3, 2, 1}, new Shape(3, 4));\n", "x.concat(y) // default axis = 0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "14" } }, "outputs": [], "source": [ "x.concat(y, 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes, we want to construct a binary `ndarray` via *logical statements*. \n", "Take `x.eq(y)` as an example. \n", "For each position, if `x` and `y` are equal at that position,\n", "the corresponding entry in the new `ndarray` takes a value of $1$,\n", "meaning that the logical statement `x.eq(y)` is true at that position;\n", "otherwise that position takes $0$." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "15" } }, "outputs": [], "source": [ "x.eq(y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Summing all the elements in the `ndarray` yields an `ndarray` with only one element." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "16" } }, "outputs": [], "source": [ "x.sum()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For stylistic convenience, we can write `x.sum()` as `np.sum(x)`.\n", "\n", "## Broadcasting Mechanism\n", "\n", "In the above section, we saw how to perform elementwise operations\n", "on two `ndarray`s of the same shape. Under certain conditions, \n", "even when shapes differ, we can still perform elementwise operations\n", "by invoking the *broadcasting mechanism*.\n", "This mechanism works in the following way:\n", "First, expand one or both arrays\n", "by copying elements appropriately \n", "so that after this transformation, \n", "the two `ndarray`s have the same shape.\n", "Second, carry out the elementwise operations\n", "on the resulting arrays.\n", "\n", "In most cases, we broadcast along an axis where an array\n", "initially only has length $1$, such as in the following example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "17" } }, "outputs": [], "source": [ "var a = manager.arange(3f).reshape(3, 1);\n", "var b = manager.arange(2f).reshape(1, 2);\n", "a" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "17" } }, "outputs": [], "source": [ "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since `a` and `b` are $3\\times1$ and $1\\times2$ matrices respectively, \n", "their shapes do not match up if we want to add them. \n", "We *broadcast* the entries of both matrices into a larger $3\\times2$ matrix as follows: \n", "for matrix `a` it replicates the columns\n", "and for matrix `b` it replicates the rows\n", "before adding up both elementwise." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "18" } }, "outputs": [], "source": [ "a.add(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Indexing and Slicing\n", "\n", "DJL use the same syntax as Numpy in Python for indexing and slicing. Just as in any other Python array, elements in an `ndarray` can be accessed by index. \n", "As in any Python array, the first element has index $0$\n", "and ranges are specified to include the first but *before* the last element. \n", "As in standard Python lists, we can access elements \n", "according to their relative position to the end of the list \n", "by using negative indices.\n", "\n", "Thus, `[-1]` selects the last element and `[1:3]` \n", "selects the second and the third elements as follows:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "19" } }, "outputs": [], "source": [ "x.get(\":-1\");" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "19" } }, "outputs": [], "source": [ "x.get(\"1:3\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Beyond reading, we can also write elements of a matrix by specifying indices." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "20" } }, "outputs": [], "source": [ "x.set(new NDIndex(\"1, 2\"), 9);\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want to assign multiple elements the same value, \n", "we simply index all of them and then assign them the value. \n", "For instance, `[0:2, :]` accesses the first and second rows,\n", "where `:` takes all the elements along axis $1$ (column).\n", "While we discussed indexing for matrices, \n", "this obviously also works for vectors \n", "and for tensors of more than $2$ dimensions." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "21" } }, "outputs": [], "source": [ "x.set(new NDIndex(\"0:2, :\"), 12);\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Saving Memory\n", "\n", "Running operations can cause new memory to be\n", "allocated to host results. \n", "For example, if we write `y = x.add(y)`, \n", "we will dereference the `ndarray` that `y` used to point to \n", "and instead point `y` at the newly allocated memory. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This might be undesirable for two reasons.\n", "First, we do not want to run around \n", "allocating memory unnecessarily all the time. \n", "In machine learning, we might have \n", "hundreds of megabytes of parameters \n", "and update all of them multiple times per second. \n", "Typically, we will want to perform these updates *in place*. \n", "Second, we might point at the same parameters from multiple variables. \n", "If we do not update in place, other references will still point to\n", "the old memory location, making it possible for parts of our code\n", "to inadvertently reference stale parameters.\n", "\n", "Fortunately, performing in-place operations in DJL is easy. \n", "We can assign the result of an operation \n", "to a previously allocated array using inplace operators like `addi`, `subi`, `muli`, and `divi`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "attributes": { "classes": [], "id": "", "n": "23" } }, "outputs": [], "source": [ "var original = manager.zeros(y.getShape());\n", "var actual = original.addi(x);\n", "original == actual" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary\n", "\n", "* DJL's `ndarray` is an extension to NumPy's `ndarray` \n", " with a few killer advantages that make it suitable for deep learning.\n", "* DJL's `ndarray` provides a variety of functionalities including \n", " basic mathematics operations, broadcasting, indexing, slicing, \n", " memory saving, and conversion to other Python objects.\n", "\n", "\n", "## Exercises\n", "\n", "1. Run the code in this section. Change the conditional statement `x.eq(y)` in this section to `x.lt(y)` (less than) or `x.gt(y)` (greater than), and then see what kind of `ndarray` you can get.\n", "1. Replace the two `ndarray`s that operate by element in the broadcasting mechanism with other shapes, e.g., three dimensional tensors. Is the result the same as expected?\n", "\n" ] } ], "metadata": { "kernelspec": { "display_name": "Java", "language": "java", "name": "java" }, "language_info": { "codemirror_mode": "java", "file_extension": ".jshell", "mimetype": "text/x-java-source", "name": "Java", "pygments_lexer": "java", "version": "14.0.2+12" } }, "nbformat": 4, "nbformat_minor": 4 }