John Paul Mueller - Algorithms For Dummies

Здесь есть возможность читать онлайн «John Paul Mueller - Algorithms For Dummies» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Algorithms For Dummies: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Algorithms For Dummies»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Your secret weapon to understanding—and using!—one of the most powerful influences in the world today
Algorithms For Dummies,
Algorithms For Dummies

Algorithms For Dummies — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Algorithms For Dummies», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Creating a matrix is the right way to start

Many of the same techniques you use with vectors also work with matrixes. To create a basic matrix, you simply use the array()function as you would with a vector, but you define additional dimensions. A dimension is a direction in the matrix. For example, a two-dimensional matrix contains rows (one direction) and columns (a second direction). The array call myMatrix = np.array([[1,2,3], [4,5,6], [7,8,9]])produces a matrix containing three rows and three columns, like this:

[[1 2 3] [4 5 6] [7 8 9]]

Note how you embed three lists within a container list to create the two dimensions. To access a particular array element, you provide a row and column index value, such as myMatrix[0, 0]to access the first value of 1. You can find a full listing of vector and matrix array-creation functions at https://numpy.org/doc/stable/reference/routines.array-creation.html .

Algorithms For Dummies - изображение 59The NumPy package supports an actual matrixclass. The matrixclass supports special features that make it easier to perform matrix-specific tasks. You discover these features later in the chapter. For now, all you really need to know is how to create a matrix of the matrixdata type. The easiest method is to make a call similar to the one you use for the arrayfunction, but using the matfunction instead, such as myMatrix = np.mat([[1,2,3], [4,5,6], [7,8,9]]), which produces the following matrix:

[[1 2 3] [4 5 6] [7 8 9]]

To determine that this actually is a matrix, try print(type(myMatrix)), which outputs . You can also convert an existing array to a matrix using the asmatrix()function. Use the asarray()function to convert a matrixobject back to an arrayform.

Algorithms For Dummies - изображение 60The only problem with the matrixclass is that it works on only two-dimensional matrixes. If you attempt to convert a three-dimensional matrix to the matrixclass, you see an error message telling you that the shape is too large to be a matrix.

Multiplying matrixes

Multiplying two matrixes involves the same concerns as multiplying two vectors (as discussed in the “ Performing vector multiplication” section, earlier in this chapter). The following code produces an element-by-element multiplication of two matrixes:

a = np.array([[1,2,3],[4,5,6]])b = np.array([[1,2,3],[4,5,6]]) print(a*b)

The output looks like this:

[[ 1 4 9] [16 25 36]]

Algorithms For Dummies - изображение 61Note that aand bare the same shape: two rows and three columns. To perform an element-by-element multiplication, the two matrixes must be the same shape. Otherwise, you see an error message telling you that the shapes are wrong. As with vectors, the multiply()function also produces an element-by-element result.

Dot products work completely differently with matrixes. In this case, the number of columns in matrix amust match the number of rows in matrix b. However, the number of rows in matrix acan be any number, and the number of columns in matrix bcan be any number as long as you multiply aby b. For example, the following code produces a correct dot product:

a = np.array([[1,2,3],[4,5,6]])b = np.array([[1,2,3],[3,4,5],[5,6,7]]) print(a.dot(b))

with an output of:

[[22 28 34] [49 64 79]]

Note that the output contains the number of rows found in matrix aand the number of columns found in matrix b. So how does this all work? To obtain the value found in the output array at index [0,0] of 22, you sum the values of a[0,0] * b[0,0] (which is 1), a[0,1] * b[1,0] (which is 6), and a[0,2] * b[2,0] (which is 15) to obtain the value of 22. The other entries work precisely the same way.

Algorithms For Dummies - изображение 62To perform an element-by-element multiplication using two matrixobjects, you must use the numpy multiply()function.

Defining advanced matrix operations

This book takes you through all sorts of interesting matrix operations, but you use some of them commonly, which is why they appear in this chapter. When working with arrays, you sometimes get data in a shape that doesn't work with the algorithm. Fortunately, numpycomes with a special reshape()function that lets you put the data into any shape needed. In fact, you can use it to reshape a vector into a matrix, as shown in the following code:

changeIt = np.array([1,2,3,4,5,6,7,8])print(changeIt) changeIt = changeIt.reshape(2,4)print(changeIt) changeIt = changeIt.reshape(2,2,2)print(changeIt)

When you run this code, you see these outputs (spaces added for clarity):

[1 2 3 4 5 6 7 8] [[1 2 3 4] [5 6 7 8]] [[[1 2] [3 4]] [[5 6] [7 8]]]

Algorithms For Dummies - изображение 63The starting shape of changeItis a vector, but using the reshape()function turns it into a matrix. In addition, you can shape the matrix into any number of dimensions that work with the data. However, you must provide a shape that fits with the required number of elements. For example, calling changeIt.reshape(2,3,2)will fail because there aren't enough elements to provide a matrix of that size.

You may encounter two important matrix operations in some algorithm formulations. They are the transposition and inverse of a matrix. Transposition occurs when a matrix of shape n x m is transformed into a matrix m x n by exchanging the rows with the columns. Most texts indicate this operation by using the superscript T, as in A T. You see this operation used most often for multiplication in order to obtain the right dimensions. When working with numpy, you use the transposefunction to perform the required work. For example, when starting with a matrix that has two rows and four columns, you can transpose it to contain four rows with two columns each, as shown in this example:

changeIt = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])print(changeIt) changeIt = np.transpose(changeIt)print(changeIt)

The outputs look like this:

[[1 2 3 4] [5 6 7 8]] [[1 5] [2 6] [3 7] [4 8]]

You apply matrix inversion to matrixes of shape m x m, which are square matrixes that have the same number of rows and columns. This operation is quite important because it allows the immediate resolution of equations involving matrix multiplication, such as y = bX, where you know vector y and matrix X, and you have to discover the values in the vector b. Because most scalar numbers (exceptions include zero) have a number whose multiplication results in a value of 1, the idea is to find a matrix inverse whose multiplication will result in a special matrix called the identity matrix. To see an identity matrix in numpy, use the identityfunction, like this:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Algorithms For Dummies»

Представляем Вашему вниманию похожие книги на «Algorithms For Dummies» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Algorithms For Dummies»

Обсуждение, отзывы о книге «Algorithms For Dummies» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x