A Visual Intro to NumPy and Data Representation
Discussions:
,
Translations: , ,
the package is the workhorse of data analysis, machine learning, and scientific computing in the python ecosystem. it vastly simplifies manipulating and crunching vectors and matrices. some of python’s leading package rely on numpy as a fundamental piece of their infrastructure (examples include scikitlearn, scipy, pandas, and tensorflow). beyond the ability to slice and dice numeric data, mastering numpy will give you an edge when dealing and debugging with advanced usecases in these libraries.
开心时时彩计划软件下载in this post, we’ll look at some of the main ways to use numpy and how it can represent different types of data (tables, images, text…etc) before we can serve them to machine learning models.
import numpy as np
Creating Arrays
we can create a numpy array (a.k.a. the mighty ) by passing a python list to it and using ` np.array()`. in this case, python creates the array we can see on the right here:
there are often cases when we want numpy to initialize the values of the array for us. numpy provides methods like ones(), zeros(), and random.random() for these cases. we just pass them the number of elements we want it to generate:
once we’ve created our arrays, we can start to manipulate them in interesting ways.
Array Arithmetic
Let’s create two NumPy arrays to showcase their usefulness. We’ll call them data
and ones
:
Adding them up positionwise (i.e. adding the values of each row) is as simple as typing data + ones
:
when i started learning such tools, i found it refreshing that an abstraction like this makes me not have to program such a calculation in loops. it’s a wonderful abstraction that allows you to think about problems at a higher level.
and it’s not only addition that we can do this way:
There are often cases when we want to carry out an operation between an array and a single number (we can also call this an operation between a vector and a scalar). Say, for example, our array represents distance in miles, and we want to convert it to kilometers. We simply say data * 1.6
:
See how NumPy understood that operation to mean that the multiplication should happen with each cell? That concept is called broadcasting开心时时彩计划软件下载, and it’s very useful.
Indexing
开心时时彩计划软件下载we can index and slice numpy arrays in all the ways we can slice python lists:
Aggregation
additional benefits numpy gives us are aggregation functions:
In addition to min
, max
, and sum
, you get all the greats like mean
to get the average, prod
to get the result of multiplying all the elements together, std
开心时时彩计划软件下载 to get standard deviation, and .
In more dimensions
all the examples we’ve looked at deal with vectors in one dimension. a key part of the beauty of numpy is its ability to apply everything we’ve looked at so far to any number of dimensions.
Creating Matrices
we can pass python lists of lists in the following shape to have numpy create a matrix to represent them:
np.array([[1,2],[3,4]])
We can also use the same methods we mentioned above (ones()
, zeros()
, and random.random()
) as long as we give them a tuple describing the dimensions of the matrix we are creating:
Matrix Arithmetic
We can add and multiply matrices using arithmetic operators (+*/
开心时时彩计划软件下载) if the two matrices are the same size. NumPy handles those as positionwise operations:
we can get away with doing these arithmetic operations on matrices of different size only if the different dimension is one (e.g. the matrix has only one column or one row), in which case numpy uses its broadcast rules for that operation:
Dot Product
A key distinction to make with arithmetic is the case of using the dot product. NumPy gives every matrix a dot()
开心时时彩计划软件下载 method we can use to carryout dot product operations with other matrices:
i’ve added matrix dimensions at the bottom of this figure to stress that the two matrices have to have the same dimension on the side they face each other with. you can visualize this operation as looking like this:
Matrix Indexing
indexing and slicing operations become even more useful when we’re manipulating matrices:
Matrix Aggregation
开心时时彩计划软件下载we can aggregate matrices the same way we aggregated vectors:
Not only can we aggregate all the values in a matrix, but we can also aggregate across the rows or columns by using the axis
开心时时彩计划软件下载 parameter:
Transposing and Reshaping
A common need when dealing with matrices is the need to rotate them. This is often the case when we need to take the dot product of two matrices and need to align the dimension they share. NumPy arrays have a convenient property called T
to get the transpose of a matrix:
In more advanced use case, you may find yourself needing to switch the dimensions of a certain matrix. This is often the case in machine learning applications where a certain model expects a certain shape for the inputs that is different from your dataset. NumPy’s reshape()
开心时时彩计划软件下载 method is useful in these cases. You just pass it the new dimensions you want for the matrix. You can pass 1 for a dimension and NumPy can infer the correct dimension based on your matrix:
Yet More Dimensions
numpy can do everything we’ve mentioned in any number of dimensions. its central data structure is called ndarray (ndimensional array) for a reason.
开心时时彩计划软件下载in a lot of ways, dealing with a new dimension is just adding a comma to the parameters of a numpy function:
Note: Keep in mind that when you print a 3dimensional NumPy array, the text output visualizes the array differently than shown here. NumPy’s order for printing ndimensional arrays is that the last axis is looped over the fastest, while the first is the slowest. Which means that np.ones((4,3,2))
would be printed as:
array([[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.],
[1., 1.]]])
Practical Usage
and now for the payoff. here are some examples of the useful things numpy will help you through.
Formulas
开心时时彩计划软件下载implementing mathematical formulas that work on matrices and vectors is a key use case to consider numpy for. it’s why numpy is the darling of the scientific python community. for example, consider the mean square error formula that is central to supervised machine learning models tackling regression problems:
implementing this is a breeze in numpy:
The beauty of this is that numpy does not care if predictions
and labels
contain one or a thousand values (as long as they’re both the same size). We can walk through an example stepping sequentially through the four operations in that line of code:
both the predictions and labels vectors contain three values. which means n has a value of three. after we carry out the subtraction, we end up with the values looking like this:
then we can square the values in the vector:
now we sum these values:
开心时时彩计划软件下载which results in the error value for that prediction and a score for the quality of the model.
Data Representation
think of all the data types you’ll need to crunch and build models around (spreadsheets, images, audio…etc). so many of them are perfectly suited for representation in an ndimensional array:
Tables and Spreadsheets
 A spreadsheet or a table of values is a two dimensional matrix. Each sheet in a spreadsheet can be its own variable. The most popular abstraction in python for those is the pandas dataframe, which actually uses NumPy and builds on top of it.
Audio and Timeseries
 An audio file is a onedimensional array of samples. Each sample is a number representing a tiny chunk of the audio signal. CDquality audio may have 44,100 samples per second and each sample is an integer between 32767 and 32768. Meaning if you have a tenseconds WAVE file of CDquality, you can load it in a NumPy array with length 10 * 44,100 = 441,000 samples. Want to extract the first second of audio? simply load the file into a NumPy array that we’ll call
audio
, and getaudio[:44100]
.
here’s a look at a slice of an audio file:
the same goes for timeseries data (for example, the price of a stock over time).
Images

开心时时彩计划软件下载an image is a matrix of pixels of size (height x width).
 If the image is black and white (a.k.a. grayscale), each pixel can be represented by a single number (commonly between 0 (black) and 255 (white)). Want to crop the top left 10 x 10 pixel part of the image? Just tell NumPy to get you
image[:10,:10]
.
 If the image is black and white (a.k.a. grayscale), each pixel can be represented by a single number (commonly between 0 (black) and 255 (white)). Want to crop the top left 10 x 10 pixel part of the image? Just tell NumPy to get you
开心时时彩计划软件下载here’s a look at a slice of an image file:

开心时时彩计划软件下载if the image is colored, then each pixel is represented by three numbers  a value for each of red, green, and blue. in that case we need a 3rd dimension (because each cell can only contain one number). so a colored image is represented by an ndarray of dimensions: (height x width x 3).
Language
If we’re dealing with text, the story is a little different. The numeric representation of text requires a step of building a vocabulary (an inventory of all the unique words the model knows) and an embedding step. Let us see the steps of numerically representing this (translated) quote by an ancient spirit:
开心时时彩计划软件下载“have the bards who preceded me left any theme unsung?”
a model needs to look at a large amount of text before it can numerically represent the anxious words of this warrior poet. we can proceed to have it process a and use it to build a vocabulary (of 71,290 words):
开心时时彩计划软件下载the sentence can then be broken into an array of tokens (words or parts of words based on common rules):
we then replace each word by its id in the vocabulary table:
These ids still don’t provide much information value to a model. So before feeding a sequence of words to a model, the tokens/words need to be replaced with their embeddings (50 dimension word2vec embedding in this case):
You can see that this NumPy array has the dimensions [embedding_dimension x sequence_length]. In practice these would be the other way around, but I’m presenting it this way for visual consistency. For performance reasons, deep learning models tend to preserve the first dimension for batch size (because the model can be trained faster if multiple examples are trained in parallel). This is a clear case where reshape()
becomes super useful. A model like BERT开心时时彩计划软件下载, for example, would expect its inputs in the shape: [batch_size, sequence_length, embedding_size].
this is now a numeric volume that a model can crunch and do useful things with. i left the other rows empty, but they’d be filled with other examples for the model to train on (or predict).
(it turned out the in our example were immortalized more so than those of the other poets which trigger his anxieties. born a slave owned by his father, valor and command of language gained him his freedom and the mythical status of having his poem as one of in preislamic arabia).