Common placeholders in numpy arrays
The underlying data block for numpy is the n-dimensional array. Often, the elements of an array are not known (especially in data science), and we need some kind of placeholders for the values in the arrays. Numpy is an indispensable library for anyone performing data manipulation or calculations. But some of the features of this powerful library may not be that straightforward for beginners. Here we take a look at the different placeholder functions that numpy offers and analyze them in-depth.
Creating an array in numpy
Before all else, let’s create an array in numpy that can be manipulated. Numpy offers many ways to create an array, including converting existing lists and tuples to arrays. Although not necessary, it is generally best practice to define the data type that you want in the ‘dtype’ argument. Numpy automatically extracts the datatype from the given data and upcasts them if required. That is, if you provide a mix of integers and floats, it converts the integers into floats too. The following is the simplest way to make a new numpy array from scratch:
The shape of a numpy array (sometimes referred to as their size) defines the number of rows and columns (and other dimensions) in a numpy array. As shown in the figures below, a 1-dimensional array has only one axis, and its shape is given by (n), where n is the number of elements in the axis. A 2-dimensional array has two axes, and the shape is provided by the form (m,n) where m denotes the number of rows and n denotes the number of columns. The extra dimension in a 3-dimensional array defines its depth and so on.
Now that we know how to create a simple array, we move on to placeholders.
Placeholders
Except when making tutorials (or giving examples), we seldom know what is in an array. Many instances of initiation of an array use some numbers as the placeholders for the real unknown values. It comes in play more often in data science (in my experience), where one has to initially randomly assign values (or sometimes zeros and ones) for weights or bias in a given numpy array that is later modified by the algorithm while training. Numpy offers about six types of placeholders that one can use while creating a new array. They span six functions and some additional functions that are discussed below.
np.zeros
As the name suggests, the np.zeros function fills the whole array with zeros. A simple example is given below:
The zeros function accepts shapes as the first parameter and dtype as an optional parameter. The dtype by default is float, and thus in the first example, all the zeros are floats.
np.ones
The np.ones function fills the whole array with ones. Here also, the default data type is float. Like the previous function, we provide the shape of the output array as the first argument to the function.
np.empty
Now that I think of it, all the functions are perfectly named in python. (My brain to me: That’s what happens in any language you dumbass.) So, the empty function effectively produces an empty array. As opposed to np.zeros, here we do not get a zero value array, but the placeholders are uninitialized. Thus, one has to enter the values manually later if one chooses to use this function. As the values cannot be blanks, the values are tiny numbers that are not recognized as entries for the array. The array values are not initialized; thus, it is marginally faster than other methods where the values are initialized. The first argument, as always, is the shape of the output array.
np.full
The np.full function structure is a bit different from the others until now. Along with the shape and datatype, it also takes another argument called ‘fill_value.’ It returns an array of the given shape filled with the fill_value. The fill_value needs to be a scalar (a simple number).
The like functions
Instead of providing the shape of the output array, one can provide a given array to the respective ‘like’ functions and obtain the results as before. The above four functions have corresponding ‘like’ functions named np.zeros_like, np.ones_like, np.empty_like, and np.full_like. The following example makes things clearer.
np.eye
Okay, the terminology is not that good at times, I guess. The np.eye function produces a diagonal matrix. It returns a 2-D array with 1’s on the diagonals, and 0’s everywhere else. Unlike the previous functions that take a tuple or list for shape, the np.eye function takes two individual parameters for rows and columns. It also takes a third argument called ‘k’ which denotes the diagonal that should be filled with ones. A value of 0 fills the main diagonal, a positive value fills the upper diagonal, and a negative value fills the lower diagonal. An example will make things clearer.
np.random.random
As mentioned earlier, there are times when we want certain randomness in the values initialized in an array. The np.random.random function serves the purpose. The purpose of this function is to return random values from a continuous uniform distribution in the range [0.0, 1.0), i.e., the values returned range from 0.0 to 1.0 (1.0 excluded), and all the values have an equal chance of being selected. We can use this function to return a single number or an array of a given shape by providing the shape of the array as an input parameter.
Conclusion
We have seen a lot of ways to introduce placeholders into arrays in numpy. The sheer number of different functions present tells us that using placeholders in numpy as a very critical task. I prefer using np.empty as it is just a bit faster, and then I can assign values accordingly. Another thing to note is that the np.eye function always returns a two-dimensional array. Which one did you like the most?
Before you go…
Connect with me on Instagram and Facebook.
If you liked this story, hit the clap button (you can clap up to 50 times with just one button!) and follow me for more such articles!
Share, recommend, and comment away! Engagement helps us communicate and be more human!
numpy.eye¶
Return a 2-D array with ones on the diagonal and zeros elsewhere.
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to N.
k : int, optional
Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
dtype : data-type, optional
Data-type of the returned array.
I : ndarray of shape (N,M)
An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.
identity (almost) equivalent function diag diagonal 2-D array from a 1-D array specified by the user.
numpy.eye#
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters : N int
Number of rows in the output.
M int, optional
Number of columns in the output. If None, defaults to N.
k int, optional
Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
dtype data-type, optional
Data-type of the returned array.
order <‘C’, ‘F’>, optional
Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory.
New in version 1.14.0.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.
Python и DataScience: изучаем возможности универсальной библиотеки Numpy
От переводчика: это перевод материала Ракшита Васудева, давно и плотно изучающего DataScience и применение в ней языка Python. Автор рассказывает о мощной библиотеке Numpy, который позволяет реализовать многие возможности машинного обучения и работы с большими данными.
Numpy — математическая библиотека для Python. Она позволяет выполнять разного рода вычисления эффективно и быстро. Она значительно расширяет функциональность Python благодаря специальным решениям, которые в ней применяются. В этой статье рассказывается о базовых возможностях Numpy, и это только первая часть; чуть позже будут опубликованы и другие. Статья для тех, кто только начинает изучать Numpy, вступая в дивный мир математики в Python.
Импорт библиотеки
В этом месте мы говорим Python, что np — это референс для Numpy, который и будет использоваться впредь.
Теперь создадим массив python и массив np.
Большой разницы при выводе нет.
Хорошо, почему в таком случае лучше использовать массив numpy вместо обычного? Ответ — потому что np позволит нам быстрее производить вычисления и модифицировать общую архитектуру приложения.
np.arange()
([start],stop,[step]) упорядочивает цифры. Вот что это означает для машины.
Формируем np-список, начиная с 0 до 10, но не включаем 10, плюс увеличиваем цифры на 2 каждый раз.
Таким образом, у нас получается вот что:
array([0, 2, 4, 6, 8])
Важно помнить, что последняя цифра не включается в список.
Этот массив можно также назвать матрицей или вектором. Поэтому не переживайте, когда я говорю, например: «Форма матрицы — 2*3». Все это означает, что наш массив в итоге будет выглядеть примерно так:
Теперь давайте поговорим о таком параметре, как shape для массива np по умолчанию. Shape здесь — атрибут. Пример его использования — ниже.
Это матрица из чисел, где в ряду всего 9 элементов. В принципе, идеальной является матрица 1*9, не так ли?
В принципе, да, и для этого reshape() вступает в игру. Это метод, который изменяет размеры оригинальной матрицы так, как хотелось бы нам.
Вот пример использования reshape() на практике.
Обратите внимание, что reshape возвращает многомерную матрицу. На это указывают две квадратных скобки в начале. [[1, 2, 3, 4, 5, 6, 7, 8, 9]] является потенциально многомерной матрицей в отличие от [1, 2, 3, 4, 5, 6, 7, 8, 9].
Если взять параметр shape для B, то им будет (3,3):
Перейдем к np.zeros()
Что прописано в этом коде?
Именно: здесь задана матрица формата 3*4, заполненная нулями. Вот вывод:
np.zeros((n,m)) возвращает матрицу формата n*m, заполненную нулями. Все просто.
А что делает np.eye()?
Возвращает нам единичную матрицу с определенными характеристиками.
Как умножить две матрицы?
Нет проблем: для этого используется np.dot(), Эта функция — скалярное произведение, если в нее передали вектора и произведение матриц (самое обыкновенное).
Пример: A = (2,3) & B = (3,2). Здесь число столбцов в А — 3. Число строк в В — 3. Поскольку характеристики совпадают, умножение возможно.
Мы подготовили матрицы к умножению. Далее — действуем.
А теперь давайте добавим отдельные элементы в матрицу
np.sum() добавляет элементы в матрицу.
Однако у нас есть два варианта.
1. Складываем по строкам
6 — сумма первой строки (1, 2, 3).
15 — второй (4, 5, 6).
24 — третьей (7, 8, 9).
2. Складываем по столбцам
12 — сумма по первому столбцу (1, 4, 7).
15 — по второму (2, 5, 7).
18 — по третьему (3, 6, 9).
Ниже — видео, созданное автором, где все, что описано выше, объясняется еще раз, более наглядно.