Установка библиотеки numpy python windows

Установка и первое знакомство

Язык Python стал популярен благодаря своей богатой библиотеке. Я его воспринимаю как некоего начальника, который через свои команды раздает задачи подчиненным. Они выполняются и на выходе получается некий результат работы программы:

Из всех известных мне языков высокого уровня, этот, наверное, самый высокий, а потому, один из самых удобных в реализации алгоритмов. Но чтобы им успешно пользоваться нужно уметь раздавать приказы подчиненным. И в этой серии занятий мы познакомимся с еще одним исполнителем языка Python – пакетом NumPy.

Вообще, NumPy предназначен для выполнения научных вычислений и активно используется не только в качестве самостоятельной библиотеки учеными и преподавателями по всему миру, но и входит в состав многих других популярных пакетов. С одним из них – Keras, мы с вами недавно познакомились, когда изучали основы работы НС. И вы могли заметить, что вначале программ фигурировала строчка:

Это, как раз, выполнение импорта того самого пакета NumPy.

Но почему он стал так популярен? Причин несколько. Самое главное, критичные по скорости вычисления фрагменты реализованы на языках Си и Фортран. Также он имеет довольно простой и продуманный синтаксис, а, значит, им легко пользоваться. Ну и, наконец, богатство возможностей этой библиотеки, начиная с базовых математических функций и заканчивая работой с полиномами, линейной алгеброй и многомерными матрицами (тензорами). Все это очень часто используется в инженерных задачах, отсюда и высокая популярность пакета.

Установка NumPy

Я думаю, вы прониклись уважением к этому пакету, и пришла пора прикоснуться к «святому граалю». В начале, как всегда, его нужно установить. Сделать это чрезвычайно просто, достаточно выполнить в терминале команду:

pip install numpy

Не удивляйтесь, если этот пакет у вас уже установлен, так как он входит в состав многих других библиотек. Проверить установку можно командой:

Если такая программа выполняется без ошибок, то этот «святой грааль» уже присутствует на вашем устройстве и готов к истязаниям.

У вас здесь уже может возникнуть вопрос: почему импорт записан в таком виде? А не просто: import numpy? Можно и так, но тогда в программе все время придется использовать префикс numpy. Гораздо удобнее писать две буквы «np». Поэтому общепринятой практикой стало импортирование этого пакета именно в таком виде. Я буду следовать сложившейся традиции и делать также.

Фундаментальный элемент NumPy – массив (array)

Отлично, сложнейший этап установки и импорта пакета позади. Пришло время сделать первые шаги и вначале познакомиться с его фундаментальным элементом – однородным многомерным массивом. В NumPy элементы массива имеют единый тип данных. Их индексы описываются кортежем целых неотрицательных чисел. Размерность кортежа – это ранг массива (то есть, размерность массива), а каждое число в кортеже представляет свою отдельную ось:

Как создать массив в NumPy? Существует много способов, но базовый реализуется через функцию:

Здесь в качестве первого параметра object может выступать список или кортеж, а также функция или объект, возвращающий список или кортеж. Второй параметр dtype – это тип элементов массива. Если указано значение None, то тип будет определяться автоматически на основе переданных данных. Подробнее об этой функции можно, как всегда, почитать на странице официальной документации:

Итак, в самом простом варианте можно создать одномерный массив так:

В результате получим объект типа array с элементами 1, 2, 3, 4:

Какой будет тип у этих элементов? Мы можем его посмотреть с помощью атрибута dtype, выполнив в консоли строчку:

Читайте также:  Как удалить файлы подкачки windows

То есть, автоматически был применен целочисленный тип размерностью 32 бит. Ну, хорошо, а что если попробовать создать массив с разными типами его элементов, например, так:

В результате увидим, следующее содержимое:

Например, для нашего одномерного случая, мы можем взять первый элемент из массива a, следующим образом:

Увидим значение ‘1’. Обратите внимание, первый элемент имеет индекс 0, а не 1. Единица – это уже второй элемент:

Для изменения значения элемента, достаточно присвоить ему новое значение, например:

в результате получим массив:

А что будет, если мы попробуем присвоить значение другого типа данных, например, число:

Ошибки не будет, а значение автоматически будет преобразовано в строку:

Разработчики пакета NumPy постарались сделать его максимально дружественным, чтобы инженер сосредотачивался именно на решении задачи, а не на нюансах программирования. Поэтому везде, там где это допустимо, пакет NumPy берет на себя разрешение подобных нюансов. И, как показала практика, это очень удобно и заметно облегчает жизнь нам, простым смертным.

Минутка восхищения или что такого в массивах NumPy

Но, все-таки, что такого в массивах NumPy, что они повсеместно используются в разных библиотеках? Давайте я приведу несколько примеров, и вы сами все увидите.

Предположим, мы определили одномерный массив с числами от 1 до 9:

Мы уже знаем как взять один отдельный элемент, но что будет, если прописать индексы для всех 9 элементов:

На выходе увидим одномерный массив из двоек:

array([2, 2, 2, 2, 2, 2, 2, 2, 2])

тогда получим аналогичный массив, но размерностью 5 элементов:

Как видите, индексирование здесь более гибкое, чем у обычных списков Python. Или, вот еще один характерный пример:

Результат будет следующим:

То есть, остаются элементы со значениями True и отбрасываются со значениями False. Обо всем этом мы еще будем подробно говорить.

Еще один пример. Предположим, нам понадобилось представить одномерный массив a в виде матрицы 3х3. Нет ничего проще, меняем его размерность:

и получаем заветный результат:

Далее, можем обращаться к элементам матрицы b так:

В обоих случаях будет взят один и тот же элемент со значением 6.

Все это лишь мимолетный взгляд на возможности пакета NumPy. Я здесь лишь хотел показать, насколько сильно отличаются массивы array от списков языка Python, и если вы хотите овладеть этим инструментом, то эта серия занятий для вас.

Видео по теме

#1. Пакет numpy — установка и первое знакомство | NumPy уроки

#2. Основные типы данных. Создание массивов функцией array() | NumPy уроки

#3. Функции автозаполнения, создания матриц и числовых диапазонов | NumPy уроки

#4. Свойства и представления массивов, создание их копий | NumPy уроки

#5. Изменение формы массивов, добавление и удаление осей | NumPy уроки

#6. Объединение и разделение массивов | NumPy уроки

#7. Индексация, срезы, итерирование массивов | NumPy уроки

#8. Базовые математические операции над массивами | NumPy уроки

#9. Булевы операции и функции, значения inf и nan | NumPy уроки

#10. Базовые математические функции | NumPy уроки

#11. Произведение матриц и векторов, элементы линейной алгебры | NumPy уроки

#12. Множества (unique) и операции над ними | NumPy уроки

#13. Транслирование массивов | NumPy уроки

© 2021 Частичное или полное копирование информации с данного сайта для распространения на других ресурсах, в том числе и бумажных, строго запрещено. Все тексты и изображения являются собственностью сайта

Installing NumPy

The only prerequisite for installing NumPy is Python itself. If you don’t have Python yet and want the simplest way to get started, we recommend you use the Anaconda Distribution — it includes Python, NumPy, and many other commonly used packages for scientific computing and data science.

NumPy can be installed with conda , with pip , with a package manager on macOS and Linux, or from source. For more detailed instructions, consult our Python and NumPy installation guide below.

Читайте также:  Linux fedora ubuntu opensuse mint

CONDA

If you use conda , you can install NumPy from the defaults or conda-forge channels:

PIP

If you use pip , you can install NumPy with:

Also when using pip, it’s good practice to use a virtual environment — see Reproducible Installs below for why, and this guide for details on using virtual environments.

Python and NumPy installation guide

Installing and managing packages in Python is complicated, there are a number of alternative solutions for most tasks. This guide tries to give the reader a sense of the best (or most popular) solutions, and give clear recommendations. It focuses on users of Python, NumPy, and the PyData (or numerical computing) stack on common operating systems and hardware.

Recommendations

We’ll start with recommendations based on the user’s experience level and operating system of interest. If you’re in between “beginning” and “advanced”, please go with “beginning” if you want to keep things simple, and with “advanced” if you want to work according to best practices that go a longer way in the future.

Beginning users

On all of Windows, macOS, and Linux:

  • Install Anaconda (it installs all packages you need and all other tools mentioned below).
  • For writing and executing code, use notebooks in JupyterLab for exploratory and interactive computing, and Spyder or Visual Studio Code for writing scripts and packages.
  • Use Anaconda Navigator to manage your packages and start JupyterLab, Spyder, or Visual Studio Code.

Advanced users

Windows or macOS

  • Install Miniconda.
  • Keep the base conda environment minimal, and use one or more conda environments to install the package you need for the task or project you’re working on.
  • Unless you’re fine with only the packages in the defaults channel, make conda-forge your default channel via setting the channel priority.

Linux

If you’re fine with slightly outdated packages and prefer stability over being able to use the latest versions of libraries:

  • Use your OS package manager for as much as possible (Python itself, NumPy, and other libraries).
  • Install packages not provided by your package manager with pip install somepackage —user .

If you use a GPU:

  • Install Miniconda.
  • Keep the base conda environment minimal, and use one or more conda environments to install the package you need for the task or project you’re working on.
  • Use the defaults conda channel ( conda-forge doesn’t have good support for GPU packages yet).
  • Install Miniforge.
  • Keep the base conda environment minimal, and use one or more conda environments to install the package you need for the task or project you’re working on.

Alternative if you prefer pip/PyPI

For users who know, from personal preference or reading about the main differences between conda and pip below, they prefer a pip/PyPI-based solution, we recommend:

  • Install Python from python.org, Homebrew, or your Linux package manager.
  • Use Poetry as the most well-maintained tool that provides a dependency resolver and environment management capabilities in a similar fashion as conda does.

Python package management

Managing packages is a challenging problem, and, as a result, there are lots of tools. For web and general purpose Python development there’s a whole host of tools complementary with pip. For high-performance computing (HPC), Spack is worth considering. For most NumPy users though, conda and pip are the two most popular tools.

Pip & conda

The two main tools that install Python packages are pip and conda . Their functionality partially overlaps (e.g. both can install numpy ), however, they can also work together. We’ll discuss the major differences between pip and conda here — this is important to understand if you want to manage packages effectively.

Читайте также:  Ubuntu based linux distros

The first difference is that conda is cross-language and it can install Python, while pip is installed for a particular Python on your system and installs other packages to that same Python install only. This also means conda can install non-Python libraries and tools you may need (e.g. compilers, CUDA, HDF5), while pip can’t.

The second difference is that pip installs from the Python Packaging Index (PyPI), while conda installs from its own channels (typically “defaults” or “conda-forge”). PyPI is the largest collection of packages by far, however, all popular packages are available for conda as well.

The third difference is that conda is an integrated solution for managing packages, dependencies and environments, while with pip you may need another tool (there are many!) for dealing with environments or complex dependencies.

Reproducible installs

As libraries get updated, results from running your code can change, or your code can break completely. It’s important to be able to reconstruct the set of packages and versions you’re using. Best practice is to:

  1. use a different environment per project you’re working on,
  2. record package names and versions using your package installer; each has its own metadata format for this:
    • Conda: conda environments and environment.yml
    • Pip: virtual environments and requirements.txt
    • Poetry: virtual environments and pyproject.toml

NumPy packages & accelerated linear algebra libraries

NumPy doesn’t depend on any other Python packages, however, it does depend on an accelerated linear algebra library — typically Intel MKL or OpenBLAS. Users don’t have to worry about installing those (they’re automatically included in all NumPy install methods). Power users may still want to know the details, because the used BLAS can affect performance, behavior and size on disk:

The NumPy wheels on PyPI, which is what pip installs, are built with OpenBLAS. The OpenBLAS libraries are included in the wheel. This makes the wheel larger, and if a user installs (for example) SciPy as well, they will now have two copies of OpenBLAS on disk.

In the conda defaults channel, NumPy is built against Intel MKL. MKL is a separate package that will be installed in the users’ environment when they install NumPy.

In the conda-forge channel, NumPy is built against a dummy “BLAS” package. When a user installs NumPy from conda-forge, that BLAS package then gets installed together with the actual library — this defaults to OpenBLAS, but it can also be MKL (from the defaults channel), or even BLIS or reference BLAS.

The MKL package is a lot larger than OpenBLAS, it’s about 700 MB on disk while OpenBLAS is about 30 MB.

MKL is typically a little faster and more robust than OpenBLAS.

Besides install sizes, performance and robustness, there are two more things to consider:

  • Intel MKL is not open source. For normal use this is not a problem, but if a user needs to redistribute an application built with NumPy, this could be an issue.
  • Both MKL and OpenBLAS will use multi-threading for function calls like np.dot , with the number of threads being determined by both a build-time option and an environment variable. Often all CPU cores will be used. This is sometimes unexpected for users; NumPy itself doesn’t auto-parallelize any function calls. It typically yields better performance, but can also be harmful — for example when using another level of parallelization with Dask, scikit-learn or multiprocessing.

Troubleshooting

If your installation fails with the message below, see Troubleshooting ImportError.

Оцените статью