<jupyter_start><jupyter_text>Manipulate data the MXNet way with `ndarray`It's impossible to get anything done if we can't manipulate data. Generally, there are two important things we need to do with: (i) acquire it! and (ii) process it once it's inside the computer.There's no point in trying to acquire data if we don't even know how to store it,so let's get our hands dirty first by playing with synthetic data.We'll start by introducing NDArrays, MXNet's primary tool for storing and transforming data. If you've worked with NumPy before, you'll notice that NDArrays are, by design, similar to NumPy's multi-dimensional array. However, they confer a few key advantages. First, NDArrays support asynchronous computation on CPU, GPU, and distributed cloud architectures. Second, they provide support for automatic differentiation. These properties make NDArray an ideal library for machine learning, both for researchers and engineers launching production systems. Getting startedIn this chapter, we'll get you going with the basic functionality. Don't worry if you don't understand any of the basic math, like element-wise operations or normal distributions. In the next two chapters we'll take another pass at NDArray, teaching you both the math you'll need and how to realize it in code.To get started, let's import `mxnet`. We'll also import `ndarray` from `mxnet` for convenience. We’ll make a habit of setting a random seed so that you always get the same results that we do.<jupyter_code>#load watermark
%load_ext watermark
%watermark -a 'Gopala KR' -u -d -v -p watermark,numpy,matplotlib,nltk,sklearn,tensorflow,theano,mxnet,chainer,seaborn,keras,tflearn,bokeh,gensim
import mxnet as mx
from mxnet import nd
mx.random.seed(1)<jupyter_output><empty_output><jupyter_text>Next, let's see how to create an NDArray, without any values initialized. Specifically, we'll create a 2D array (also called a *matrix*) with 3 rows and 4 columns.<jupyter_code>x = nd.empty((3, 4))
print(x)<jupyter_output>[[7.467339e-36 0.000000e+00 0.000000e+00 0.000000e+00]
 [0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00]
 [0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00]]
<NDArray 3x4 @cpu(0)><jupyter_text>The `empty` method just grabs some memory and hands us back a matrix without setting the values of any of its entries. This means that the entries can have any form of values, including very big ones! But typically, we'll want our matrices initialized. Commonly, we want a matrix of all zeros.<jupyter_code>x = nd.zeros((3, 5))
x<jupyter_output><empty_output><jupyter_text>Similarly, `ndarray` has a function to create a matrix of all ones.<jupyter_code>x = nd.ones((3, 4))
x<jupyter_output><empty_output><jupyter_text>Often, we'll want to create arrays whose values are sampled randomly. This is especially common when we intend to use the array as a parameter in a neural network. In this snippet, we initialize with values drawn from a standard normal distribution with zero mean and unit variance.<jupyter_code>y = nd.random_normal(0, 1, shape=(3, 4))
y<jupyter_output><empty_output><jupyter_text>As in NumPy, the dimensions of each NDArray are accessible via the `.shape` attribute.<jupyter_code>y.shape<jupyter_output><empty_output><jupyter_text>We can also query its size, which is equal to the product of the components of the shape. Together with the precision of the stored values, this tells us how much memory the array occupies.<jupyter_code>y.size<jupyter_output><empty_output><jupyter_text>OperationsNDArray supports a large number of standard mathematical operations. Such as element-wise addition:<jupyter_code>x + y<jupyter_output><empty_output><jupyter_text>Multiplication:<jupyter_code>x * y<jupyter_output><empty_output><jupyter_text>And exponentiation:<jupyter_code>nd.exp(y)<jupyter_output><empty_output><jupyter_text>We can also grab a matrix's transpose to compute a proper matrix-matrix product.<jupyter_code>nd.dot(x, y.T)<jupyter_output><empty_output><jupyter_text>We'll explain these operations and present even more operators in the [linear algebra](P01-C03-linear-algebra.ipynb) chapter. But for now, we'll stick with the mechanics of working with NDArrays.  In-place operationsIn the previous example, every time we ran an operation, we allocated new memory to host its results. For example, if we write `y = x + y`, we will dereference the matrix that `y` used to point to and instead point it at the newly allocated memory. In the following example we demonstrate this with Python's `id()` function, which gives us the exact address of the referenced object in memory. After running `y = y + x`, we'll find that `id(y)` points to a different location. That's because Python first evaluates `y + x`, allocating new memory for the result and then subsequently redirects `y` to point at this new location in memory.<jupyter_code>print('id(y):', id(y))
y = y + x
print('id(y):', id(y))<jupyter_output>id(y): 140048447603656
id(y): 140048447605896<jupyter_text>This might be undesirable for two reasons. First, we don't want to run around allocating memory unnecessarily all the time. In machine learning, we might have hundreds of megabytes of paramaters and update all of them multiple times per second. Typically, we'll want to perform these updates in place. Second, we might point at the same parameters from multiple variables. If we don't update in place, this could cause a memory leak, and could cause us to inadvertently reference stale parameters. Fortunately, performing in-place operations in MXNet is easy. We can assign the result of an operation to a previously allocated array with slice notation, e.g., `y[:] = `.<jupyter_code>print('id(y):', id(y))
y[:] = x + y
print('id(y):', id(y))<jupyter_output>id(y): 140048447605896
id(y): 140048447605896<jupyter_text>While this syntacically nice, `x+y` here will still allocate a temporary buffer to store the result before copying it to `y[:]`. To make even better use of memory, we can directly invoke the underlying `ndarray` operation, in this case `elemwise_add`, avoiding temporary buffers. We do this by specifying the `out` keyword argument, which every `ndarray` operator supports:<jupyter_code>nd.elemwise_add(x, y, out=y)<jupyter_output><empty_output><jupyter_text>If we're not planning to re-use ``x``, then we can assign the result to ``x`` itself. There are two ways to do this in MXNet. 1. By using slice notation x[:] = x op y2. By using the op-equals operators like `+=`<jupyter_code>print('id(x):', id(x))
x += y
x
print('id(x):', id(x))<jupyter_output>id(x): 140048447603376
id(x): 140048447603376<jupyter_text>SlicingMXNet NDArrays support slicing in all the ridiculous ways you might imagine accessing your data. Here's an example of reading the second and third rows from `x`.<jupyter_code>x[1:3]<jupyter_output><empty_output><jupyter_text>Now let's try writing to a specific element.<jupyter_code>x[1,2] = 9.0
x<jupyter_output><empty_output><jupyter_text>Multi-dimensional slicing is also supported.<jupyter_code>x[1:2,1:3]
x[1:2,1:3] = 5.0
x<jupyter_output><empty_output><jupyter_text>BroadcastingYou might wonder, what happens if you add a vector `y` to a matrix `X`? These operations, where we compose a low dimensional array `y` with a high-dimensional array `X` invoke a functionality called broadcasting. Here, the low-dimensional array is duplicated along any axis with dimension $1$ to match the shape of the high dimensional array. Consider the following example.<jupyter_code>x = nd.ones(shape=(3,3))
print('x = ', x)
y = nd.arange(3)
print('y = ', y)
print('x + y = ', x + y)<jupyter_output>x =  
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
<NDArray 3x3 @cpu(0)>
y =  
[0. 1. 2.]
<NDArray 3 @cpu(0)>
x + y =  
[[1. 2. 3.]
 [1. 2. 3.]
 [1. 2. 3.]]
<NDArray 3x3 @cpu(0)><jupyter_text>While `y` is initially of shape (3), MXNet infers its shape to be (1,3), and then broadcasts along the rows to form a (3,3) matrix). You might wonder, why did MXNet choose to interpret `y` as a (1,3) matrix and not (3,1). That's because broadcasting prefers to duplicate along the left most axis. We can alter this behavior by explicitly giving `y` a 2D shape.<jupyter_code>y = y.reshape((3,1))
print('y = ', y)
print('x + y = ', x+y)<jupyter_output>y =  
[[0.]
 [1.]
 [2.]]
<NDArray 3x1 @cpu(0)>
x + y =  
[[1. 1. 1.]
 [2. 2. 2.]
 [3. 3. 3.]]
<NDArray 3x3 @cpu(0)><jupyter_text>Converting from MXNet NDArray to NumPyConverting MXNet NDArrays to and from NumPy is easy. The converted arrays do not share memory.<jupyter_code>a = x.asnumpy()
type(a)
y = nd.array(a) 
y<jupyter_output><empty_output><jupyter_text>Managing contextYou might have noticed that MXNet NDArray looks almost identical to NumPy. But there are a few crucial differences.One of the key features that differentiates MXNet from NumPy is its support for diverse hardware devices.In MXNet, every array has a context. One context could be the CPU. Other contexts might be various GPUs. Things can get even hairier when we deploy jobs across multiple servers. By assigning arrays to contexts intelligently, we can minimize the time spent transferring data between devices. For example, when training neural networks on a server with a GPU, we typically prefer for the model's parameters to live on the GPU. To start, let's try initializing an array on the first GPU.<jupyter_code>z = nd.ones(shape=(3,3), ctx=mx.gpu(0))
z<jupyter_output><empty_output><jupyter_text>Given an NDArray on a given context, we can copy it to another context by using the copyto() method.<jupyter_code>x_gpu = x.copyto(mx.gpu(0))
print(x_gpu)<jupyter_output><empty_output><jupyter_text>The result of an operator will have the same context as the inputs.<jupyter_code>x_gpu + z<jupyter_output><empty_output><jupyter_text>If we ever want to check the context of an NDArray programmaticaly, we can just call its `.context` attribute.<jupyter_code>print(x_gpu.context)
print(z.context)<jupyter_output><empty_output><jupyter_text>In order to perform an operation on two ndarrays `x1` and `x2`,we need them both to live on the same context. And if they don't already, we may need to explicitly copy data from one context to another.You might think that's annoying. After all, we just demonstrated that MXNet knows where each NDArray lives. So why can't MXNet just automatically copy `x1` to `x2.context` and then add them?In short, people use MXNet to do machine learningbecause they expect it to be fast. But transferring variables between different contexts is slow. So we want you to be 100% certain that you want to do something slow before we let you do it. If MXNet just did the copy automatically without crashingthen you might not realize that you had written some slow code.We don't want you to spend your entire life on StackOverflow,so we make some mistakes impossible. ![](../img/operator-context.png)  Watch out!Imagine that your variable z already lives on your second GPU (`gpu(0)`). What happens if we call `z.copyto(gpu(0))`? It will make a copy and allocate new memory, even though that variable already lives on the desired device!There are times where depending on the environment our code is running in,two variables may already live on the same device.So we only want to make a copy if the variables currently lives on different contexts. In these cases, we can call `as_in_context()`. If the variable is already the specified context then this is a no-op.<jupyter_code>print('id(z):', id(z))
z = z.copyto(mx.gpu(0))
print('id(z):', id(z))
z = z.as_in_context(mx.gpu(0))
print('id(z):', id(z))
print(z)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09101889396945906, 'fraction_numerical': 0.02717625744111811, 'mean_word_length': 5.4186046511627906, 'pattern_counts': {'":': 0, '<': 105, '<?xml version=': 0, '>': 105, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '26', 'dir': 'jupyter-structured-clean-dedup', 'id': '71521', 'license': 'MIT', 'n_tokens_mistral': 3799, 'n_tokens_neox': 3485, 'n_words': 1535, 'path': 'tests/maxnet/ndarray.ipynb', 'repo_name': 'gopala-kr/ds-notebooks', 'size': '11591'}