{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "BsNwjQDRfmLY" }, "source": [ "## Библиотека Numpy" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "wu6r1-s7fmLe" }, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "zxRIdPO9gYyX" }, "source": [ "При работе с предыдущими ноутбуками вы познакомились с основами языка Python. Узнали, что Python -- довольно простой, понятный язык программирования, научились пользоваться jupyter notebook'ом и оценили плюсы и возможности python+jupyter -- написание кода в отдельных ячейках и последовательный запуск кода в ячейках.\n", "\n", "Но есть и обратная сторона медали -- Python очень медленный язык. Возможно, пока что это было не очень заметно, потому что мы не работали с большими массивами данных. Но в эпоху big data, при работе с огромными массивами данных даже небольшое отставание языка программирования по скорости становится заметно и критично. Есть, конечно, языки программирования, которые работают намного быстрее (например, С++), но они гораздо сложнее в написании и не интерпретируемы, а компилируемы (то есть, в jupyter notebook'е с такими языками работать бы не получилось). \n", "\n", "Как же найти компромисс? Ответ прост: написать python-библиотеку для работы с массивами данных, функции которой будут написаны на очень быстром языке С++, но которую можно было бы использовать из Python. Эта библиотека называется **NumPy** (НамПай)." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "BA9Po-oLfmLh" }, "source": [ "Пакет `numpy` предоставляет интерфейс для работы с $n$-мерными массивами. В `numpy` реализовано множество всевозможных операций над массивами в целом. Если задачу можно решить, произведя некоторую последовательность операций над массивами, то с помощью numpy в python это будет столь же эффективно, как в `C` или `matlab`.\n", "\n", "Конечно, тот факт, что код numpy написан на С++, накладывает некоторые ограничения на массивы этой библиотеки: в любом numpy-массиве могут храниться элементы только одного типа: например, все float или все string (как вы помните с прошлого урока, в обычном pythonв массивах могут быть элементы совершенно разных типов)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "clwpHv-Zk0qV" }, "source": [ "Этот ноутбук полностью посвещен знакомству с библиотекой numpy и работе с ней" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "0_vHg4rzfmLi" }, "source": [ "## Одномерные массивы" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "MFKSC2UUA7Ne" }, "source": [ "### Создание массива " ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "6DzqLBjjfmLk" }, "outputs": [], "source": [ "# принято, что numpy импортируют именно так\n", "import numpy as np" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "NTtvvXC6fmLq" }, "source": [ "Как же завести массив в numpy?\n", "\n", "Очень просто! Надо всего лишь перевести обычный python list в np.array:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "colab_type": "code", "executionInfo": { "elapsed": 446, "status": "ok", "timestamp": 1556908885417, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "u6O_T130fmLs", "outputId": "f255c89b-e913-4771-9e87-e509faada4fb" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3 4 1]\n" ] }, { "data": { "text/plain": [ "numpy.ndarray" ] }, "execution_count": 4, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "# 'перевести' python list в np.array -- это обернуть массив в np.array()\n", "a = np.array([3, 4, 1])\n", "print(a)\n", "type(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "y2U8lTuYfmLz" }, "source": [ "Обычный питоновский `print` печатает массивы в удобной форме (точно так же, как и list питона)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 405, "status": "ok", "timestamp": 1556908886479, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "gtJ0bdn5fmL1", "outputId": "29229fa9-1f73-4c62-b158-8416ec08a1b6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3 4 1]\n" ] } ], "source": [ "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Mth2u7nzAiqw" }, "source": [ "### Типы данных в массивах np.array" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "zbAeCr5HfmMJ" }, "source": [ "Поговорим о типах данных, хранящихся в массивах:\n", "\n", "Чаще всего мы будем работать с числовыми массивами, поэтому поговорим о инх.\n", "\n", "В отличие от чистого питона, в `numpy` есть несколько типов для целых чисел (`int16`, `int32`, `int64`) и чисел с плавающей точкой (`float32`, `float64`). Они отличаются тем, с какой точностью в памяти хранятся элементы массива. \n", "\n", "Чтобы посмотреть, какой тип у вашего массива, можно вывести его dtype:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 687, "status": "ok", "timestamp": 1556908888449, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "ga8UJa7yfmMK", "outputId": "7c1db2bb-c90f-48b8-a46d-e522b5373f55" }, "outputs": [ { "data": { "text/plain": [ "dtype('int64')" ] }, "execution_count": 6, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a.dtype" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "A3nr3k6F-4HT" }, "source": [ "Конечно, можно скастовать массив из одного типа в другой. \n", "\n", "Давайте переведем наш массив 'a' из типа np.int64 в тип np.float32:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 752, "status": "ok", "timestamp": 1556908889965, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "KiuqdCAi-3kw", "outputId": "b046cbb1-a90c-45ef-a965-e475b76a58ab" }, "outputs": [ { "data": { "text/plain": [ "dtype('float32')" ] }, "execution_count": 7, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a = a.astype(np.float32)\n", "a.dtype" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "E4doUPKdAGqm" }, "source": [ "Далее мы будем рассматривать n-мерный массивы, для них преобразование типов работает так же. И для них все еще все элементы должны иметь одинаковый тип." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ocm0D55sA3cg" }, "source": [ "### Изменение массивов np.array" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "3_7c9NLTfmMM" }, "source": [ "Как и list в питоне, массивы np.array - изменяемые объекты. Механика изменений значений в них такая же, как у питоновских list'ов. Давайте в этом убедимся:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 607, "status": "ok", "timestamp": 1556909790072, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "30ibLJJ-fmMM", "outputId": "954f316e-f337-4915-c8f7-d6dd63160f28" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 3, 1]\n" ] } ], "source": [ "a = np.array([3, 4 ,1])\n", "\n", "a[1] = 3\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Hi9VSwT-Dit1" }, "source": [ "Единственный (но логичный) нюанс: при изменении значения в массиве с элементами одного типа на элемент другого типа новый элемент будет приведен к типу массива:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 757, "status": "ok", "timestamp": 1556909953581, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "mq4wMhLIECvh", "outputId": "7e8c71e3-fb0c-4c22-f6af-2a4086f72019" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3 3 1]\n" ] } ], "source": [ "# или: a = np.array([3, 4 ,1], dtype=np.int64)\n", "a = np.array([3, 4 ,1]).astype(np.int64)\n", "\n", "# значение 3.5 будет приведено к типу int64, т.е. станет 3\n", "a[1] = 3.5\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 655, "status": "ok", "timestamp": 1556909994711, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "8Ju5yEg2EPl3", "outputId": "a76f7b0a-9bd4-4400-dcd4-3a83608e6a91" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3. 5. 1.]\n" ] } ], "source": [ "# обратите внимание -- если создается np.array с чисоами разных типов (int и float), \n", "# то все числа будут приведены к более точному типу, т.е. float\n", "# таким образом, 1 из целого числа станет числом с плавающей точкой 1.\n", "a = np.array([3., 4. ,1])\n", "\n", "# значение 5 будет приведено к типу int64, т.е. станет 5.\n", "a[1] = 5\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "TuZIz7kDEWCM" }, "source": [ "А вот добавить к массиву новый элемент в конец чуть сложнее, чем у list. Напримним, в list это делалось с помощью метода .append(). В numpy это также делается с помощью append, но чуть по-другому:\n", "\n", "Обратите внимание, что в numpy при append *создается новый массив*, а не происходит добавление элемента в уже существующий массив. Поэтому не рекомендуется создавать массивы с помощью append в numpy." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 614, "status": "ok", "timestamp": 1556910277887, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "2m_G3Op6EtCR", "outputId": "cd0cb866-2ad4-4410-f7b2-28e8a860e207" }, "outputs": [ { "data": { "text/plain": [ "array([3, 4, 1, 6])" ] }, "execution_count": 13, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a = np.array([3, 4 ,1])\n", "\n", "# вот так пишется append\n", "a = np.append(a, 6)\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "dZDih28zO0AZ" }, "source": [] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "51Tpu4P5O2JQ" }, "source": [ "## Многомерные массивы" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "D2I34jDFO7x0" }, "source": [ "Мы узнали, как создавать и изменять одномерные массивы, как они выглядят в numpy и нюансы приведения типов. Настало время познакомиться с многомерными массивами.\n", "\n", "Многомерный массив -- это массив, элементы которого тоже массивы. В принципе, ничего нового, все как и у list в питоне. " ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "colab_type": "code", "executionInfo": { "elapsed": 604, "status": "ok", "timestamp": 1556914540492, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "NluLEVL6VbfT", "outputId": "a78967ff-f1e1-44f9-e6ed-bc43ed0dc131" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[2 3]\n", " [4 5]]\n" ] } ], "source": [ "two_dim_array = np.array([[2, 3], [4, 5]])\n", "\n", "print(two_dim_array)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 102 }, "colab_type": "code", "executionInfo": { "elapsed": 632, "status": "ok", "timestamp": 1556914544741, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "6HIBtdA_VizU", "outputId": "320162c2-6bdb-40b7-a51e-7819b454df39" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[[2 3]\n", " [4 5]]\n", "\n", " [[5 6]\n", " [7 8]]]\n" ] } ], "source": [ "three_dim_array = np.array([[[2, 3], [4, 5]], [[5, 6], [7, 8]]])\n", "\n", "print(three_dim_array)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "UAPCq4dmWQRU" }, "source": [ "Напомним, что в numpy, неважно, в одномерном или многомерном массиве, *все* элементы имеют одинаковый тип\n", "\n", "Давайте в этом убедимся:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "colab_type": "code", "executionInfo": { "elapsed": 537, "status": "ok", "timestamp": 1556915221721, "user": { "displayName": "Tatiana Gaintseva", "photoUrl": "https://lh6.googleusercontent.com/-8CX4gk2wqJg/AAAAAAAAAAI/AAAAAAAAAAk/y13ijTBP8WM/s64/photo.jpg", "userId": "12353702982477031617" }, "user_tz": -180 }, "id": "NV7tM_8IXkkS", "outputId": "84190c51-bce6-42f1-e8e8-600a84e20c84" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[2. 3.]\n", " [4. 5.]] float64\n" ] } ], "source": [ "# 2 и 3 приведутся к типу чисел 4. и 5., т.е. float64\n", "a = np.array([[2, 3], [4., 5.]])\n", "print(a, a.dtype)\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "9LH7l4YFWJl-" }, "source": [ "### Информация о массиве" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "84HDTakDVqjm" }, "outputs": [], "source": [ "Теперь научимся получать основную информацию о массиве" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "JrEY8hzdfmM2" }, "source": [ "## Операции над одномерными массивами\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "vbjIN8IrOk3t" }, "source": [ " ### Арифметические операции" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "hJfC6mEUfmM2" }, "outputs": [], "source": [ "a = np.array([2, 5, 6, 7])\n", "b = np.array([9, 7, 8, 9])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "SyhreThiOqhx" }, "source": [ "С двумя массивами одинаковой " ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "EmlV4Cn2fmM3", "outputId": "69d8903b-e6e6-44af-bd46-88e1de05c1aa" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[11 12 14 16]\n" ] } ], "source": [ "print(a + b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "hFgqEFPdfmM4", "outputId": "32f58971-27cc-43e9-f871-077552c59c25" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-7 -2 -2 -2]\n" ] } ], "source": [ "print(a - b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "TdCSYDsUfmM5", "outputId": "5eca99a6-0d7d-44b1-c4d9-5cdb011ddf65" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[18 35 48 63]\n" ] } ], "source": [ "print(a * b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "iM1VgL_AfmM6", "outputId": "b303d686-53d5-47a7-f3f4-1244b449b5cd" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.22222222 0.71428571 0.75 0.77777778]\n" ] } ], "source": [ "print(a / b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "fhYQugrafmM8", "outputId": "5706ddc5-ff29-4d6e-e71f-6c5a805be7b8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 4 25 36 49]\n" ] } ], "source": [ "print(a ** 2)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "u-nODxC_fmM_" }, "source": [ "`numpy` содержит элементарные функции, которые тоже применяются к массивам поэлементно. Они называются универсальными функциями (`ufunc`)." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Q4AVx4JbfmM_", "outputId": "4d45e0c2-9471-4114-bd45-1fb82285fa2c" }, "outputs": [ { "data": { "text/plain": [ "(, numpy.ufunc)" ] }, "execution_count": 34, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "np.sin, type(np.sin)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "UlD1i1ucfmNA", "outputId": "333948f2-cab8-4305-dbff-390547609325" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0.90929743 -0.95892427 -0.2794155 0.6569866 ]\n", "[ 3.76219569 74.20994852 201.71563612 548.31703516]\n" ] } ], "source": [ "print(np.sin(a))\n", "print(np.cosh(a))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "rcOgTOV9fmNB" }, "source": [ "Один из операндов может быть скаляром, а не массивом." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "evAWu0mtfmNB", "outputId": "e912c1b0-ad6c-4d12-8b84-3b2fccb20e51" }, "outputs": [ { "data": { "text/plain": [ "array([2, 5, 6, 7])" ] }, "execution_count": 46, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "VvT9aNIXfmND", "outputId": "b59d3928-0d87-4212-bd66-1efc24c4d555" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3 6 7 8]\n" ] } ], "source": [ "print(a + 1)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "qVBR-7oMfmNF", "outputId": "09468475-8060-4333-c821-2ca7338678cd" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 4 10 12 14]\n" ] } ], "source": [ "print(2 * a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "UjhN4lHGfmNG" }, "source": [ "Сравнения дают булевы массивы." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Pu3FPoK-fmNG", "outputId": "0880061e-9c32-40fe-9ba3-191b1843d1c3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[False False False False]\n" ] } ], "source": [ "print(a > b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "aQ2NQc0DfmNH", "outputId": "b69bcbd2-827f-49d7-ac8f-97a11fbed300" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ True True True True]\n" ] } ], "source": [ "print(a < b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "K6JjG8YXfmNI", "outputId": "8a7c3085-ad3b-480d-ef93-f033acea24c4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[False False False False]\n" ] } ], "source": [ "print(a == b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "fC4mG93EfmNK", "outputId": "c20b5708-9814-4ebb-ca62-013444f3ab0f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[False False True True]\n" ] } ], "source": [ "c = a > 5\n", "print(c)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "1B7KJ7O-fmNL" }, "source": [ "Кванторы \"существует\" и \"для всех\"." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "UXQgvtZcfmNL", "outputId": "5d15b920-66e9-469d-a387-e834f9e39d9c" }, "outputs": [ { "data": { "text/plain": [ "(False, False)" ] }, "execution_count": 41, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "np.any(c), np.all(c)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "SGteTpYBfmNM" }, "source": [ "Модификация на месте." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "lritBIg0fmNN", "outputId": "263c519f-973d-4111-b096-e7a8e372a558" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1. 1.025 1.05 1.075 1.1 ]\n" ] } ], "source": [ "a += 1\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "c3n8Y23hfmNO", "outputId": "a1f46560-71ef-465d-c86d-4782b01ad633" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 4. 8. 12. 16.]\n" ] } ], "source": [ "b *= 2\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "VRJqCFK3fmNP", "outputId": "4a84296c-ba91-4b23-da3d-3dc14e4c1700" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 3.90243902 7.61904762 11.1627907 14.54545455]\n" ] } ], "source": [ "b /= a\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "9pQ60AqPfmNQ" }, "source": [ "При выполнении операций над массивами деление на 0 не возбуждает исключения, а даёт значения `np.nan` или `np.inf`." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "ltwGc-bofmNR", "outputId": "b9ce9bf4-37cc-49b2-ddd4-c8e2086187ac" }, "outputs": [ { "data": { "text/plain": [ "(nan, inf, nan, 0.0)" ] }, "execution_count": 45, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "np.nan + 1, np.inf + 1, np.inf * 0, 1. / np.inf" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ITxex6KQfmNS" }, "source": [ "Сумма и произведение всех элементов массива; максимальный и минимальный элемент; среднее и среднеквадратичное отклонение." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "x7j0UYGnfmNS", "outputId": "32926b56-e460-409e-a085-cc407cb58f09" }, "outputs": [ { "data": { "text/plain": [ "(33, 4536, 9, 7, 8.25, 0.82915619758885)" ] }, "execution_count": 52, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "b.sum(), b.prod(), b.max(), b.min(), b.mean(), b.std()" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "_lHBH_bzfmNT", "outputId": "90a5286a-176c-4389-c23c-092d9a3ee105" }, "outputs": [ { "data": { "text/plain": [ "(-0.06815562196555326, 0.9830193100609568)" ] }, "execution_count": 53, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "x = np.random.normal(size=1000)\n", "x.mean(), x.std()" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "h3KrQIEDfmNU" }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "MiHVT1dUfmNV" }, "source": [ "Имеются встроенные функции" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "O9YkL8oPfmNV", "outputId": "12bc2d11-84c1-44bc-e059-66e6b1188157" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 1.97545919 2.76026224 3.34107628 3.81385036]\n", "[1.00000000e+00 4.95230899e+01 2.03662157e+03 7.04593127e+04\n", " 2.07496438e+06]\n", "[0. 1.58973284 2.15397459 2.49838135 2.74376828]\n", "[ 0. -0.68953468 0.9725297 -0.98605188 0.91780205]\n", "2.718281828459045 3.141592653589793\n" ] } ], "source": [ "print(np.sqrt(b))\n", "print(np.exp(b))\n", "print(np.log(b + 1))\n", "print(np.sin(b))\n", "print(np.e, np.pi)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "bzIBuoHZfmNW" }, "source": [ "Иногда бывает нужно использовать частичные (кумулятивные) суммы. В нашем курсе такое пригодится." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "lPTe5BJ3fmNW", "outputId": "1edacba3-a446-4116-e2c5-49928e6ee421" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[37.22973189 22.68427734 11.52148664 3.90243902 0. ]\n" ] } ], "source": [ "print(b.cumsum()[::-1])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "hjedKncOfmNY" }, "source": [ "Функция `sort` возвращает отсортированную копию, метод `sort` сортирует на месте." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "I6oLUas2fmNY", "outputId": "8296dce3-96af-42b3-9991-6172ada7db6c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 3.90243902 7.61904762 11.1627907 14.54545455]\n", "[ 0. 3.90243902 7.61904762 11.1627907 14.54545455]\n" ] } ], "source": [ "print(np.sort(b))\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "ipq5cBfdfmNZ", "outputId": "c4f692e0-71ed-4cfa-d718-d67095311de8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 3.90243902 7.61904762 11.1627907 14.54545455]\n" ] } ], "source": [ "b.sort()\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "D8PDlwE-fmNc" }, "source": [ "Объединение массивов \"по-горизонтали\" (horizontal stack)." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "9QNmb95wfmNc", "outputId": "2c23f7c8-4d66-4d0f-ae9d-38b013352439" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 1 2 3 100 200 300]\n" ] } ], "source": [ "a = np.array([1, 2, 3])\n", "b = np.array([100, 200, 300])\n", "\n", "print(np.hstack((a, b)))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "0xcN7Aj_fmNe" }, "source": [ "Объединение массивов \"по-вертикали\" (vertical stack)." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Y_jxaXArfmNe", "outputId": "32c58870-a98f-493a-c002-1e91934f2767" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1 2 3]\n", " [100 200 300]]\n" ] } ], "source": [ "print(np.vstack((a, b)))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Ff0G4h_QfmNf" }, "source": [ "Расщепление массива в позициях 3 и 6." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "IUJsUaPdfmNf", "outputId": "526cbd9e-9303-4f68-d8cf-964f34afe641" }, "outputs": [ { "data": { "text/plain": [ "[array([0.64501372, 0.99102171, 0.28545633]),\n", " array([0.6489831 , 0.95678594, 0.80428645]),\n", " array([0.59815893, 0.81674245, 0.44190248, 0.47429843])]" ] }, "execution_count": 54, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a = np.random.random(10)\n", "np.hsplit(a, [3, 6])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "BaRHNopmfmNg" }, "source": [ "Функции `delete`, `insert` и `append` не меняют массив на месте, а возвращают новый массив, в котором удалены, вставлены в середину или добавлены в конец какие-то элементы." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "nKd8vvWwfmNg" }, "outputs": [], "source": [ "a = np.arange(10)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "G3n3pvY8fmNh", "outputId": "3b80612e-e184-41ea-d0a4-66bca100d512" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0 1 2 3 4 6 8 9]\n" ] } ], "source": [ "a = np.delete(a, [5, 7])\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vSh1n-MrfmNi", "outputId": "33615dda-c012-40db-b228-c8dd58311f46" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0 1 0 0 2 3 4 6 8 9]\n" ] } ], "source": [ "a = np.insert(a, 2, [0, 0])\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "nK_tcSNCfmNi", "outputId": "7f96fd06-19ef-4e7c-e860-efec09e5a0b5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0 1 0 0 2 3 4 6 8 9 1 2 3]\n" ] } ], "source": [ "a = np.append(a, [1, 2, 3])\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "gUvXXkjufmNk" }, "source": [ "Есть несколько способов индексации массива. Вот обычный индекс." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "VaxI1LMZfmNk", "outputId": "17672fb9-784a-4bb4-f336-e6b33d7bdf62" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]\n" ] } ], "source": [ "a = np.linspace(0, 1, 11)\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Un8iBzpGfmNm", "outputId": "f2095f87-59b8-4af5-d293-4bcb69c84f84" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.2\n" ] } ], "source": [ "b = a[2]\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "tUEpza04fmNn" }, "source": [ "Диапазон индексов. Создаётся новый заголовок массива, указывающий на те же данные. Изменения, сделанные через такой массив, видны и в исходном массиве." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "_1r9_G69fmNn", "outputId": "857d8668-17b6-4ee8-dc51-78e928b2558e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.2 0.3 0.4 0.5]\n" ] } ], "source": [ "b = a[2:6]\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "C4t-B6ZzfmNo", "outputId": "e61b7161-d3e2-42be-f8be-3814f9d13556" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.2 0.3 0.4 0.5]\n" ] } ], "source": [ "b[0] = -0.2\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "2qbvKB_jfmNp", "outputId": "1ab424cc-8bbe-420c-e4d3-121fdbff74ad" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 0.1 -0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]\n" ] } ], "source": [ "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "TeiXcTTTfmNq" }, "source": [ "Диапазон с шагом 2." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "AJjKLi35fmNq", "outputId": "76837c5f-0e53-4400-c201-205c0dbb3b31" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.1 0.3 0.5 0.7 0.9]\n" ] } ], "source": [ "b = a[1:10:2]\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "jK_Td23_fmNr", "outputId": "9122e4c9-3bc2-4214-e4e9-85147880b863" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0. -0.1 -0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]\n" ] } ], "source": [ "b[0] = -0.1\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "fZpNnjbqfmNs" }, "source": [ "Массив в обратном порядке." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "jATTNvVYfmNs", "outputId": "4dc736a8-697c-4e28-88f3-f62948306640" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 1. 0.9 0.8 0.7 0.6 0.5 0.4 0.3 -0.2 -0.1]\n" ] } ], "source": [ "b = a[len(a):0:-1]\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "JyLgSAwHfmNt" }, "source": [ "Подмассиву можно присвоить значение - массив правильного размера или скаляр." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "7gxJfWqifmNt", "outputId": "40ec931a-6bef-42f7-ffa0-62d140d19e85" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 0. -0.2 0.3 0. 0.5 0.6 0. 0.8 0.9 1. ]\n" ] } ], "source": [ "a[1:10:3] = 0\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "CDT5mLThfmNt" }, "source": [ "Тут опять создаётся только новый заголовок, указывающий на те же данные." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "f_tZbUirfmNu", "outputId": "174fe1c6-7b6a-4c09-88e8-b97d5f31d599" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 0.1 -0.2 0.3 0. 0.5 0.6 0. 0.8 0.9 1. ]\n" ] } ], "source": [ "b = a[:]\n", "b[1] = 0.1\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "CzZSgXktfmNu" }, "source": [ "Чтобы скопировать и данные массива, нужно использовать метод `copy`." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Bo8Cgn_dfmNv", "outputId": "e9acece1-7819-4dcc-e8cf-bb7c9d2d6932" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 0.1 0. 0.3 0. 0.5 0.6 0. 0.8 0.9 1. ]\n", "[ 0. 0.1 -0.2 0.3 0. 0.5 0.6 0. 0.8 0.9 1. ]\n" ] } ], "source": [ "b = a.copy()\n", "b[2] = 0\n", "print(b)\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "vdDCbeHBfmNv" }, "source": [ "Можно задать список индексов." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "DYgQYl9TfmNv", "outputId": "49beab92-b839-47b9-b17c-c213733be9aa" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.2 0.3 0.5]\n" ] } ], "source": [ "print(a[[2, 3, 5]])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "aFWiNZd7fmNw" }, "source": [ "Можно задать булев массив той же величины." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "W4tlGJzXfmNw", "outputId": "5779ad8c-d779-46be-8edb-4e372452ef04" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[False True False True False True True False True True True]\n" ] } ], "source": [ "b = a > 0\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "5B6-HVhgfmNx", "outputId": "3b3a6c0c-fbf2-454c-b652-171257797c96" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.1 0.3 0.5 0.6 0.8 0.9 1. ]\n" ] } ], "source": [ "print(a[b])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "collapsed": true, "id": "mrm41pzufmNy" }, "source": [ "## 2-мерные массивы" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "nUDue8svfmNy", "outputId": "24d3b918-026b-4fb8-ce72-d7e5c9fb67e6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0. 1.]\n", " [-1. 0.]]\n" ] } ], "source": [ "a = np.array([[0.0, 1.0], [-1.0, 0.0]])\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "edMAUCADfmNz", "outputId": "856eddc7-320b-4dae-8a54-1a5c4a45dd6c" }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 55, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a.ndim" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "-ehx8jg5fmN0", "outputId": "1db8c8e7-71ab-49ce-c21e-443977d8de6f" }, "outputs": [ { "data": { "text/plain": [ "(2, 2)" ] }, "execution_count": 56, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a.shape" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "q-xHGc8cfmN0", "outputId": "5045c20a-aef7-464b-df7e-b528adc152d4" }, "outputs": [ { "data": { "text/plain": [ "(2, 4)" ] }, "execution_count": 57, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "len(a), a.size" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "5GruXNexfmN1", "outputId": "8c016f71-c996-4a21-fb6c-09f235220b5c" }, "outputs": [ { "data": { "text/plain": [ "-1.0" ] }, "execution_count": 58, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a[1, 0]" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "hs-7wB5dfmN2" }, "source": [ "Атрибуту `shape` можно присвоить новое значение - кортеж размеров по всем координатам. Получится новый заголовок массива; его данные не изменятся." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "4z49_SEyfmN2", "outputId": "3e31ab49-1f27-4513-d7fd-6280aea198d8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 1. 2. 3.]\n" ] } ], "source": [ "b = np.linspace(0, 3, 4)\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "5JKJ90zJfmN3", "outputId": "31ee3c8f-cb17-43a3-e5f4-978be86557eb" }, "outputs": [ { "data": { "text/plain": [ "(4,)" ] }, "execution_count": 79, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "b.shape" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "rV_Tyzp0fmN4", "outputId": "1704a9f1-1697-4356-96fb-a5df9a616ed7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0. 1.]\n", " [2. 3.]]\n" ] } ], "source": [ "b.shape = 2, 2\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "c6fPpTnYfmN5" }, "source": [ "Можно растянуть в одномерный массив" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "V35k5mhQfmN5", "outputId": "018651e4-01f1-41ad-c476-0c332bbb2c83" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 1. 2. 3.]\n" ] } ], "source": [ "print(b.ravel())" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "79n-zW4RfmN6" }, "source": [ "Арифметические операции поэлементные" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "eDoK5LNLfmN6", "outputId": "830420d0-b0f5-48a0-8404-e7ad4160c9b7" }, "outputs": [ { "data": { "text/plain": [ "array([[ 0., 1.],\n", " [-1., 0.]])" ] }, "execution_count": 60, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "UBAKba1VfmN7", "outputId": "0d20c6cc-f4e0-4883-b6aa-3a03b367b85c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[3 4]\n", " [8 6]]\n" ] } ], "source": [ "b = np.array([[3, 4], \n", " [8, 6 ]])\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Tgm5RIaWfmN8", "outputId": "a34908b8-c124-4dfc-9724-cf2fbb7e07e4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 2.]\n", " [0. 1.]]\n", "[[ 0. 2.]\n", " [-2. 0.]]\n", "[[ 0. 2.]\n", " [-1. 1.]]\n", "[[0. 1.]\n", " [1. 2.]]\n", "[[3. 5.]\n", " [7. 6.]]\n" ] } ], "source": [ "print(a + 1)\n", "print(a * 2)\n", "print(a + [0, 1]) # второе слагаемое дополняется до матрицы копированием строк\n", "print(a + np.array([[0, 2]]).T) # .T - транспонирование\n", "print(a + b)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "UsHKpNqyfmN9" }, "source": [ "Поэлементное и матричное (только в Python 3.5) умножение." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "y2AzM-6wfmN-", "outputId": "93de801e-1bd4-44ae-e449-bb2abc3dc3bc" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0. 1.]\n", " [-1. 0.]]\n" ] } ], "source": [ "print(a)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "B8XRyWUdfmN_", "outputId": "dd8636ac-38b4-48d6-e959-412464f2c9cd" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[3 4]\n", " [8 6]]\n" ] } ], "source": [ "print(b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "WjVtzrN-fmOA", "outputId": "06e7d89a-db82-4ea9-a832-a99b221915f8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 0. 4.]\n", " [-8. 0.]]\n" ] } ], "source": [ "print(a * b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "NQvK75yDfmOA", "outputId": "083f2938-434d-46e2-a7e7-d0a1b92be0a2" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 8. 6.]\n", " [-3. -4.]]\n" ] } ], "source": [ "print(a @ b)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "QmJCt0ApfmOB", "outputId": "b4050307-b67c-4212-f015-97e8892626df" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-4. 3.]\n", " [-6. 8.]]\n" ] } ], "source": [ "print(b @ a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "7uC-wg07fmOC" }, "source": [ "Умножение матрицы на вектор." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "-gsGIk3hfmOC", "outputId": "56467a5b-c21e-43fd-a7c0-4411c7b3610f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-1. 2.]\n" ] } ], "source": [ "v = np.array([1, -1], dtype=np.float64)\n", "print(b @ v)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "gAnLlc_TfmOD", "outputId": "178c17a6-0427-47b9-cabc-ff496d6e6e3a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-5. -2.]\n" ] } ], "source": [ "print(v @ b)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "wigtCX3lfmOF" }, "source": [ "Если у вас Питон более ранней версии, то для работы с матрицами можно использовать класс `np.matrix`, в котором операция умножения реализуется как матричное умножение." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Bd4wMoWkfmOF", "outputId": "83e13d81-d6c5-4895-9e2e-b6b0a8f51001" }, "outputs": [ { "data": { "text/plain": [ "matrix([[ 2., 3.],\n", " [ 0., -1.]])" ] }, "execution_count": 88, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "np.matrix(a) * np.matrix(b)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "YqgeGsYrfmOG" }, "source": [ "Внешнее произведение $a_{ij}=u_i v_j$" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "gwKinevJfmOG", "outputId": "64ae06ce-9883-4ce5-be84-2f03d3e61cdf" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1. 2.]\n", "[2. 3. 4.]\n" ] } ], "source": [ "u = np.linspace(1, 2, 2)\n", "v = np.linspace(2, 4, 3)\n", "print(u)\n", "print(v)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "o9P_82UzfmOH", "outputId": "45677d9b-1a0f-4a1e-8bbb-e2fa5881a3cf" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[2. 3. 4.]\n", " [4. 6. 8.]]\n" ] } ], "source": [ "a = np.outer(u, v)\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Wrb7V9m4fmOI" }, "source": [ "Двумерные массивы, зависящие только от одного индекса: $x_{ij}=u_j$, $y_{ij}=v_i$" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "WHcnUD8GfmOI", "outputId": "58782d4c-6941-4594-e03d-6a70a6126c26" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 2.]\n", " [1. 2.]\n", " [1. 2.]]\n", "[[2. 2.]\n", " [3. 3.]\n", " [4. 4.]]\n" ] } ], "source": [ "x, y = np.meshgrid(u, v)\n", "print(x)\n", "print(y)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "xnJuN0N6fmOJ" }, "source": [ "Единичная матрица." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "6R7djX9kfmOJ", "outputId": "ab4fc66d-c132-4552-8bc0-9fc70bd624b2" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 0. 0. 0.]\n", " [0. 1. 0. 0.]\n", " [0. 0. 1. 0.]\n", " [0. 0. 0. 1.]]\n" ] } ], "source": [ "I = np.eye(4)\n", "print(I)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "u5c-qCxSfmOL" }, "source": [ "Метод `reshape` делает то же самое, что присваивание атрибуту `shape`." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "4d3ToIOAfmOL", "outputId": "4b6f9798-6e9a-44a0-d597-d5886aea874e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1.]\n" ] } ], "source": [ "print(I.reshape(16))" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "pPNkSiwTfmOM", "outputId": "050b53d0-92a6-40dc-c6a2-2005b6a983fe" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 0.]\n", " [0. 0.]\n", " [0. 1.]\n", " [0. 0.]\n", " [0. 0.]\n", " [1. 0.]\n", " [0. 0.]\n", " [0. 1.]]\n" ] } ], "source": [ "print(I.reshape(8, 2))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "k3605lJYfmON" }, "source": [ "Строка." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vBkj1jD5fmOO", "outputId": "5d9cb9d1-bfb8-4fd1-f7f1-c4a3c8497fe8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 0. 1. 0.]\n" ] } ], "source": [ "print(I[2])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "zx6SXOoHfmOP" }, "source": [ "Цикл по строкам." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "I6jGWR64fmOP", "outputId": "1f312481-ba7c-46c5-80c7-b6ad57ab4cce", "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1. 0. 0. 0.]\n", "[0. 1. 0. 0.]\n", "[0. 0. 1. 0.]\n", "[0. 0. 0. 1.]\n" ] } ], "source": [ "for row in I:\n", " print(row)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "tWrIzkQsfmOQ" }, "source": [ "Столбец." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "9Z9mor1XfmOR", "outputId": "bf1fcec0-0ed0-40a3-e7c7-21143a89f3de" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0\n" ] } ], "source": [ "print(I[1, 1])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "FvEaf0c7fmOS" }, "source": [ "Подматрица." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "CaXHoIZgfmOS", "outputId": "17c1d0f8-57af-419a-a5d0-940ca548ab66" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0. 0.]\n", " [1. 0.]]\n" ] } ], "source": [ "print(I[0:2, 1:3])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ZdAv5jXLfmOT" }, "source": [ "Можно построить двумерный массив из функции." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "FPQdAfykfmOU", "outputId": "a9ae737b-f9dc-4d60-e81e-ee36fb89eef9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0 0 0 0]\n", " [1 1 1 1]\n", " [2 2 2 2]\n", " [3 3 3 3]]\n", "[[0 1 2 3]\n", " [0 1 2 3]\n", " [0 1 2 3]\n", " [0 1 2 3]]\n", "[[ 0 1 2 3]\n", " [10 11 12 13]\n", " [20 21 22 23]\n", " [30 31 32 33]]\n" ] } ], "source": [ "def f(i, j):\n", " print(i)\n", " print(j)\n", " return 10 * i + j\n", "\n", "print(np.fromfunction(f, (4, 4), dtype=np.int64))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "kIHvkeIzfmOV" }, "source": [ "Транспонированная матрица." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "XkCvBDRMfmOV", "outputId": "9824a322-60e4-4f08-a4e2-48f9847873c3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0. 2.]\n", " [1. 3.]]\n" ] } ], "source": [ "print(b.T)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "YxT5DwPffmOW" }, "source": [ "Соединение матриц по горизонтали и по вертикали." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "SgUOSUpJfmOW", "outputId": "c733ed36-5bf7-4cba-b4b2-16027fcaf92b" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0 1]\n", " [2 3]]\n", "[[4 5 6]\n", " [7 8 9]]\n", "[[4 5]\n", " [6 7]\n", " [8 9]]\n" ] } ], "source": [ "a = np.array([[0, 1], [2, 3]])\n", "b = np.array([[4, 5, 6], [7, 8, 9]])\n", "c = np.array([[4, 5], [6, 7], [8, 9]])\n", "print(a)\n", "print(b)\n", "print(c)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Q9XfHNcdfmOX", "outputId": "7b91c73a-41de-4a2f-d98b-ea557ae14d29" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0 1 4 5 6]\n", " [2 3 7 8 9]]\n" ] } ], "source": [ "print(np.hstack((a, b)))" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "9KBGlrxzfmOY", "outputId": "7b18e674-23e8-4cdb-d32e-53b99653549e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0 1]\n", " [2 3]\n", " [4 5]\n", " [6 7]\n", " [8 9]]\n" ] } ], "source": [ "print(np.vstack((a, c)))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "B75txmwJfmOZ" }, "source": [ "Сумма всех элементов; суммы столбцов; суммы строк." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Oo00j_hMfmOZ", "outputId": "0e2391c2-6ff0-4ba8-ce90-4318c8f89cff" }, "outputs": [ { "data": { "text/plain": [ "array([[3, 4],\n", " [8, 6]])" ] }, "execution_count": 87, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "6qzmyVMKfmOZ", "outputId": "ba197e8b-2ed7-4e9d-8d34-7fd4134262a2" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "21\n", "[11 10]\n", "[ 7 14]\n" ] } ], "source": [ "print(b.sum())\n", "print(b.sum(axis=0))\n", "print(b.sum(axis=1))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "nmj7UTCmfmOa" }, "source": [ "Аналогично работают `prod`, `max`, `min` и т.д." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "CbJsqMKcfmOb", "outputId": "3cf6b856-4086-4466-93a0-33ed8801fc98" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n", "[7 8 9]\n", "[4 7]\n" ] } ], "source": [ "print(b.max())\n", "print(b.max(axis=0))\n", "print(b.min(axis=1))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "5eeossTYfmOc" }, "source": [ "След - сумма диагональных элементов." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "7mMEE_BzfmOc", "outputId": "2288d8ea-1412-40b9-95ca-b2bf3be1cd44" }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 106, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "np.trace(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "2kJObRBHfmOd" }, "source": [ "## Многомерные массивы\n", "опциональный материал" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "XO2pnEo1fmOe", "outputId": "a952d7e5-1761-40fe-ded3-6c7f16865697" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[[ 0 1 2 3]\n", " [ 4 5 6 7]\n", " [ 8 9 10 11]]\n", "\n", " [[12 13 14 15]\n", " [16 17 18 19]\n", " [20 21 22 23]]]\n" ] } ], "source": [ "X = np.arange(24).reshape(2, 3, 4)\n", "print(X)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "hAFFHpaBfmOf" }, "source": [ "Суммирование (аналогично остальные операции)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "_xcmPEKNfmOf", "outputId": "c3080f1a-55e5-4a87-909e-670214bcbfe3" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[12 14 16 18]\n", " [20 22 24 26]\n", " [28 30 32 34]]\n", "[ 66 210]\n" ] } ], "source": [ "# суммируем только по нулевой оси, то есть для фиксированных j и k суммируем только элементы с индексами (*, j, k)\n", "print(X.sum(axis=0))\n", "# суммируем сразу по двум осям, то есть для фиксированной i суммируем только элементы с индексами (i, *, *)\n", "print(X.sum(axis=(1, 2)))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ylh_09YIfmOg" }, "source": [ "## Линейная алгебра" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "HUXDKhPzfmOg", "outputId": "43c6412d-a3d3-49db-9403-fa534d1a925b" }, "outputs": [ { "data": { "text/plain": [ "-2.0" ] }, "execution_count": 109, "metadata": { "tags": [] }, "output_type": "execute_result" } ], "source": [ "np.linalg.det(a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "GCcZRK16fmOh" }, "source": [ "Обратная матрица." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "UOUFtpvIfmOh", "outputId": "3048abe5-daec-4fed-9443-d317c80d962a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-1.5 0.5]\n", " [ 1. 0. ]]\n" ] } ], "source": [ "a1 = np.linalg.inv(a)\n", "print(a1)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "QBvEGytEfmOi", "outputId": "a1105b92-5eb0-440c-da3d-6d6b6cb6d6d1" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 0.]\n", " [0. 1.]]\n", "[[1. 0.]\n", " [0. 1.]]\n" ] } ], "source": [ "print(a @ a1)\n", "print(a1 @ a)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "PJQAQQLgfmOj" }, "source": [ "Решение линейной системы $au=v$." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "6rqLKKyrfmOj", "outputId": "d01873be-a893-4a0e-9984-a150bf24db0a" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.5 0. ]\n" ] } ], "source": [ "v = np.array([0, 1], dtype=np.float64)\n", "print(a1 @ v)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "nALBpIIPfmOk", "outputId": "64b4ca5c-f035-4923-805c-6a260ae42a30" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.5 0. ]\n" ] } ], "source": [ "u = np.linalg.solve(a, v)\n", "print(u)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "AQNFE30dfmOl" }, "source": [ "Проверим." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "YYWwTAfmfmOl", "outputId": "d9513a41-77f4-4490-86e4-94e7ce1df3ad" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 0.]\n" ] } ], "source": [ "print(a @ u - v)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "-nPqQZ32fmOm" }, "source": [ "Собственные значения и собственные векторы: $a u_i = \\lambda_i u_i$. `l` - одномерный массив собственных значений $\\lambda_i$, столбцы матрицы $u$ - собственные векторы $u_i$." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Aby8Q0UqfmOm", "outputId": "6b596de2-7f39-4c32-d7e3-5a142a8096b6" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.56155281 3.56155281]\n" ] } ], "source": [ "l, u = np.linalg.eig(a)\n", "print(l)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "M9p_mn3WfmOn", "outputId": "6650b190-e1e2-487c-e922-6b93d59542e7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-0.87192821 -0.27032301]\n", " [ 0.48963374 -0.96276969]]\n" ] } ], "source": [ "print(u)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_ri8pDJofmOo" }, "source": [ "Проверим." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "Eu0hgYVifmOo", "outputId": "7b54885c-0981-4cd0-8402-1c23a62e34d0" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.00000000e+00 1.66533454e-16]\n", "[ 0.0000000e+00 -4.4408921e-16]\n" ] } ], "source": [ "for i in range(2):\n", " print(a @ u[:, i] - l[i] * u[:, i])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "FGLpkdP5fmOo" }, "source": [ "Функция `diag` от одномерного массива строит диагональную матрицу; от квадратной матрицы - возвращает одномерный массив её диагональных элементов." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "R_pGiyEMfmOp", "outputId": "8ed7efcb-1ff8-4c71-f5fb-0f3557e151c8" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-0.56155281 0. ]\n", " [ 0. 3.56155281]]\n", "[-0.56155281 3.56155281]\n" ] } ], "source": [ "L = np.diag(l)\n", "print(L)\n", "print(np.diag(L))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "jQeO5yw4fmOq" }, "source": [ "Все уравнения $a u_i = \\lambda_i u_i$ можно собрать в одно матричное уравнение $a u = u \\Lambda$, где $\\Lambda$ - диагональная матрица с собственными значениями $\\lambda_i$ на диагонали." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "c6Q3_hj-fmOq", "outputId": "7555d5ba-5b0d-4e7a-d40f-3735a047646f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0.00000000e+00 0.00000000e+00]\n", " [1.11022302e-16 0.00000000e+00]]\n" ] } ], "source": [ "print(a @ u - u @ L)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "lcnbDsgQfmOr" }, "source": [ "Поэтому $u^{-1} a u = \\Lambda$." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "zJi2SX33fmOr", "outputId": "b2afb7a1-c46b-488a-a95c-557310edc951" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-5.61552813e-01 1.47801400e-17]\n", " [-1.25939966e-16 3.56155281e+00]]\n" ] } ], "source": [ "print(np.linalg.inv(u) @ a @ u)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "LR99sNMzfmOs" }, "source": [ "Найдём теперь левые собственные векторы $v_i a = \\lambda_i v_i$ (собственные значения $\\lambda_i$ те же самые)." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "-VlU9KTvfmOs", "outputId": "b0eac9e0-0c94-4c65-d22b-958675be97a0" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.56155281 3.56155281]\n", "[[-0.96276969 -0.48963374]\n", " [ 0.27032301 -0.87192821]]\n" ] } ], "source": [ "l, v = np.linalg.eig(a.T)\n", "print(l)\n", "print(v)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "lceOEiLDfmOt" }, "source": [ "Собственные векторы нормированы на 1." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "XVWK3_kffmOt", "outputId": "9272190c-bc2c-491c-b4b4-c68a68567612" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 1. -0.23570226]\n", " [-0.23570226 1. ]]\n", "[[1. 0.23570226]\n", " [0.23570226 1. ]]\n" ] } ], "source": [ "print(u.T @ u)\n", "print(v.T @ v)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "OEzELGlOfmOu" }, "source": [ "Левые и правые собственные векторы, соответствующие разным собственным значениям, ортогональны, потому что $v_i a u_j = \\lambda_i v_i u_j = \\lambda_j v_i u_j$." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "JENmli6ufmOu", "outputId": "b29f7d71-f23f-4f28-ba0c-243a51727741" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[ 9.71825316e-01 -7.57355847e-18]\n", " [-4.34446700e-17 9.71825316e-01]]\n" ] } ], "source": [ "print(v.T @ u)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "wLoVDMQnfmOv" }, "source": [ "# Интегрирование" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vzUcnhqqfmOv" }, "outputs": [], "source": [ "from scipy.integrate import quad, odeint\n", "from scipy.special import erf" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "r7kaCmHkfmOw" }, "outputs": [], "source": [ "def f(x):\n", " return np.exp(-x ** 2)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "6bmt_YF3fmOw" }, "source": [ "Адаптивное численное интегрирование (может быть до бесконечности). `err` - оценка ошибки." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "f-XOO2zkfmOw", "outputId": "ad9f532e-d4d9-4242-dc31-107a23921b6b" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.8862269254527579 0.8862269254527579 7.101318390472462e-09\n" ] } ], "source": [ "res, err = quad(f, 0, np.inf)\n", "print(np.sqrt(np.pi) / 2, res, err)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "qx4wdJ8ufmOx", "outputId": "98075546-907c-4579-ccff-1c7145b5e702" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.7468241328124269 0.7468241328124271 8.291413475940725e-15\n" ] } ], "source": [ "res, err = quad(f, 0, 1)\n", "print(np.sqrt(np.pi) / 2 * erf(1), res, err)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "QeBH-jT4fmOy" }, "source": [ "## Сохранение в файл и чтение из файла" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "En20hxbWfmOy" }, "outputs": [], "source": [ "x = np.arange(0, 25, 0.5).reshape((5, 10))\n", "\n", "# Сохраняем в файл example.txt данные x в формате с двумя точками после запятой и разделителем ';'\n", "np.savetxt('example.txt', x, fmt='%.2f', delimiter=';')" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "VIUIkTyLfmOz" }, "source": [ "Получится такой файл" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "VLOPpXdBfmOz", "outputId": "5c74bac8-911e-460c-c719-9e794a762130" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.00;0.50;1.00;1.50;2.00;2.50;3.00;3.50;4.00;4.50\r\n", "5.00;5.50;6.00;6.50;7.00;7.50;8.00;8.50;9.00;9.50\r\n", "10.00;10.50;11.00;11.50;12.00;12.50;13.00;13.50;14.00;14.50\r\n", "15.00;15.50;16.00;16.50;17.00;17.50;18.00;18.50;19.00;19.50\r\n", "20.00;20.50;21.00;21.50;22.00;22.50;23.00;23.50;24.00;24.50\r\n" ] } ], "source": [ "!cat example.txt" ] } ], "metadata": { "colab": { "collapsed_sections": [ "MFKSC2UUA7Ne", "Mth2u7nzAiqw", "JrEY8hzdfmM2", "mrm41pzufmNy", "2kJObRBHfmOd", "ylh_09YIfmOg", "QeBH-jT4fmOy" ], "name": "NumPy.ipynb", "provenance": [], "version": "0.3.2" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" } }, "nbformat": 4, "nbformat_minor": 1 }