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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

print(np.identity(4))

which produces an output of:

[[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]

Note that an identity matrix contains all ones on the diagonal. Finding the inverse of a scalar is quite easy (the scalar number n has an inverse of n –1that is 1/n). It's a different story for a matrix. Matrix inversion involves quite a large number of computations. The inverse of a matrix A is indicated as A –1. When working with numpy, you use the linalg.inv()function to create an inverse. The following example shows how to create an inverse, use it to obtain a dot product, and then compare that dot product to the identity matrix by using the allclose()function.

a = np.array([[1,2], [3,4]])b = np.linalg.inv(a) print(np.allclose(np.dot(a,b), np.identity(2)))

Algorithms For Dummies - изображение 64The output of Truetells you bis the inverse of a. Sometimes, finding the inverse of a matrix is impossible. When a matrix cannot be inverted, it is referred to as a singular matrix or a degenerate matrix. Singular matrixes aren't the norm; they’re quite rare.

Creating Combinations the Right Way

Shaping data often involves viewing the data in multiple ways. Data isn’t simply a sequence of numbers — it presents a meaningful sequence that, when ordered the proper way, conveys information to the viewer. Creating the right data combinations by manipulating data sequences is an essential part of making algorithms do what you want them to do. The following sections look at three data-shaping techniques: permutations, combinations, and repetitions.

Distinguishing permutations

When you receive raw data, it appears in a specific order. The order can represent just about anything, such as the log of a data input device that monitors something like a production line. Perhaps the data is a series of numbers representing the number of products made at any particular moment in time. The reason that you receive the data in a particular order is important, but that order might not lend itself to obtaining the output you need from an algorithm. Creating a data permutation, a reordering of the data so that it presents a different view, might help to achieve a desired result.

You can view permutations in a number of ways. One method of viewing a permutation is as a random presentation of the sequence order. In this case, you can use the numpy random.permutation()function, as shown here:

a = np.array([1,2,3])print(np.random.permutation(a))

What you see is a randomized version of the original data, such as [2 1 3]. Each time you run this code, you receive a different random ordering of the data sequence, which comes in handy with algorithms that require you to randomize the dataset to obtain the desired results. For example, sampling is an essential part of data analytics, and the technique shown is an efficient way to perform this task.

Another way to view the issue is the need to obtain all the permutations for a dataset so that you can try each one in turn. To perform this task, you need to import the itertoolspackage. The following code shows a technique you can use to obtain a list of all the permutations of a particular vector:

from itertools import permutations a = np.array([1,2,3]) for p in permutations(a): print(p)

The output you see looks like this:

(1, 2, 3)(1, 3, 2)(2, 1, 3)(2, 3, 1)(3, 1, 2)(3, 2, 1)

If you want to use the list comprehension ( https://www.w3schools.com/python/python_lists_comprehension.asp ) approach, which is a shorter method of performing repetitive tasks, you can use [print(p) for p in permutations(a)]instead. You can read more about itertoolsat https://docs.python.org/3/library/itertools.html .

Shuffling combinations

In some cases, you don't need an entire dataset; all you really need are a few of the members in combinations of a specific length. For example, you might have a dataset containing four numbers and want only two-number combinations from it. (The ability to obtain parts of a dataset is a key function for generating a fully connected graph, which is described in Part 3of the book.) The following code shows how to obtain such combinations:

from itertools import combinations a = np.array([1,2,3,4]) for comb in combinations(a, 2): print(comb)

which produces this output:

(1, 2)(1, 3)(1, 4)(2, 3)(2, 4)(3, 4)

The output contains all the possible two-number combinations of a. Note that this example uses the itertools combinations()function (the permutations()function appears in the previous section). Of course, you might not need all those combinations; perhaps a random subset of them would work better. In this case, you can rely on the random.sample()function to come to your aid, as shown here:

import random pool = [] for comb in combinations(a, 2): pool.append(comb) print(random.sample(pool, 3))

The precise combinations you see as output will vary, such as [(1, 2), (2, 3), (1, 4)]. However, the idea is that you've limited your dataset in two ways. First, you’re not using all the data elements all the time, and second, you’re not using all the possible combinations of those data elements. The effect is to create a relatively random-looking set of data elements that you can use as input to an algorithm. Python provides a whole host of randomizing methods that you can see at https://docs.python.org/3/library/random.html . Many of the later examples in this book also rely on randomization to help obtain the correct output from algorithms.

Facing repetitions

Repeated data can unfairly weight the output of an algorithm so that you get inaccurate results. Sometimes you need unique values to determine the outcome of a data manipulation. Fortunately, Python makes it easy to remove certain types of repeated data. Consider this example:

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

The output contains only the unique elements:

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

Algorithms For Dummies - изображение 65In this case, abegins with an assortment of numbers in no particular order and with plenty of repetitions. In Python, a set never contains repeated data. Consequently, by converting the list in ato a setand then back to a list, and then placing that list in an array, you obtain a vector that has no repeats.

Getting the Desired Results Using Recursion

Recursion, an elegant method of solving many computer problems, relies on the capability of a function to continue calling itself until it satisfies a particular condition. The term recursion actually comes from the Latin verb recurrere, which means to run back.

When you use recursion, you solve a problem by calling the same function multiple times but modifying the terms under which you call it. The main reason for using recursion is that it provides an easier way to solve problems when working with some algorithms because it mimics the way a human would solve it. Unfortunately, recursion is not an easy tool because it requires some effort to understand how to build a recursive routine, and it can cause out-of-memory problems on your computer if you don't set some memory settings. The following sections detail how recursion works and give you an example of how recursion works in Python.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x