- Install NumPy, SciPy and Matplotlib on Mac OS X
- Step 0 — Getting Started
- Step 1 — Install Libraries
- Numpy
- gfortran
- Scikit
- Matplotlib
- Pandas
- OpenCV
- Tensorflow
- Keras
- Installing NumPy
- Python and NumPy installation guide
- Recommendations
- Beginning users
- Advanced users
- Windows or macOS
- Linux
- Alternative if you prefer pip/PyPI
- Python package management
- Pip & conda
- Reproducible installs
- NumPy packages & accelerated linear algebra libraries
- Troubleshooting
- Как установить NumPy для python 3.3.5 на Mac OSX 10.9
- 3 ответов
- Вариант 1: Домашнее Пиво
- Вариант 2: Анаконда
Install NumPy, SciPy and Matplotlib on Mac OS X
Tools for machine learning. How to install NumPy, SciPy and Matplotlib using Homebrew.
Step 0 — Getting Started
Homebrew is a package manager for Mac OS X. Here’s how to install it beforehand.
Step 1 — Install Libraries
Pip is a package manager for Python.
Numpy
NumPy supports scientific computing and linear algebra support.
gfortran
We need gfortran to compile SciPy, but it does not come pre-installed with Xcode. Therefore, Homebrew can help us out again:
Scikit
Scikit-learn’s purpose is to support machine learning, and therefore it’s used for many of the tasks performed routinely in machine learning. A few key features are:
- It works well with the libraries stated above.
- It helps integrate the algorithms we will use for predictive models.
- It contains methods that will help us pre-process data, measure the performance of our models, and splitting data into test sets.
- Methods for creating trained models, tuning models, and identifying which features within the models are essential.
Matplotlib
To install matplotlib, we need to install pkg-config
Mat plotlib is a 2D publication library that produces high-quality graphics.
Pandas
Pandas is a data manipulation tool that uses data frames to access and analyze information.
OpenCV
Library often used for Computer Vision.
Tensorflow
TensorFlow is a free and open-source software library for dataflow and differentiable programming across a range of tasks.
Keras
Keras is a high-level neural networks API, written in Python, and capable of running on top of TensorFlow.
Источник
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.
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.
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:
- use a different environment per project you’re working on,
- 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.
Источник
Как установить NumPy для python 3.3.5 на Mac OSX 10.9
поэтому в настоящее время я пытаюсь использовать python, чтобы он получал электронное письмо и открывал вложение, и одним из импорта, который я нашел, был matplotlib.pyplot как plt. Это, в свою очередь, требовало Numpy и matplotlib, из которых matplotlib было легко импортировать, но я не могу на всю жизнь заставить NumPy работать. Я попытался пройти через репозиторий, распаковывая файл, используя Xcode, terminal и homebrew, и ни один из них не работает. В настоящее время я продолжаю пытаться с terminal, но всякий раз, когда я пытаюсь установить NumPy не удается. Подруга порекомендовала вводить в «судо питона setup.py строить» с последующим «судо питона setup.py установите», однако произошла ошибка что нет такого файла или каталога как setup.py. Любом случае кто-нибудь может объяснить метод установки numpy, который будет работать для Python 3.3 (большинство я вижу за 2,7 которых у меня нет), что не свести меня с ума? (В случае, если вопрос, который я задаю, кажется смехотворно легким для некоторых, я всего лишь ученик средней школы, который никогда ничего не делал как и раньше, поэтому я отчаянно нуждаюсь в помощи)
3 ответов
Добро пожаловать в Python и Stack Overflow!
ваш вопрос совсем не редкость. Я видел, как выпускники PhD боролись с теми же проблемами! Хотя Python-красивый язык программирования с очень дружелюбным сообществом, начало работы с научным стеком Python может быть довольно хлопотно.
есть два хороших варианта для Python на Mac, в зависимости от того, сколько времени вы хотите инвестировать в изучение определенного набора инструментов. Оба набора инструменты превосходны и хорошо стоят вашего времени, но имеют несколько компромиссов. Они похожи, хотя, в том, что они оба потребуют от вас провести некоторое время в терминале; я бы рекомендовал установить iTerm2 как ваш первый шаг, если вы еще этого не сделали.
Вариант 1: Домашнее Пиво
этот вариант может быть немного сложнее и может потребовать больше времени, вложенного заранее, но в конце концов может сэкономить ваше время и головные боли, потому что у вас больше контроля и свободу с тем, как вы хотите установить Python и другие инструменты командной строки.
первый шаг-установить доморощенного. В настоящее время это делается с помощью одной команды терминала, которая проведет вас через процесс установки.
в рамках этого вам придется установить XCode (бесплатно из App Store) и связанные с ним инструменты командной строки. Это то, что делает этот вариант трудоемким.
после установки Homebrew, у вас есть доступ к новой команде в терминале, brew . Эту команду можно использовать для установки Python 3, NumPy и Matplotlib.
тогда вы хорошо идти! Эта опция дает вам доступ к мощным инструментам, как pip и brew . Это означает, что в будущем, когда вы хотите установить новый пакет Python, вы должны иметь возможность pip install
для получения дополнительной информации, см. Домашняя страница и страница Вики Python.
Вариант 2: Анаконда
Anaconda-это решение «все-в-одном», которое сразу настроит Python и все научные инструменты Python. Все, что вам нужно сделать, это загрузите и установите его!
после установки вы сможете запускать код Python, который использует Numpy и Matplotlib. Если вам нужен новый пакет Python, вы должен иметь возможность открыть терминал и сделать pip install
на краткое руководство является хорошим ресурсом для наиболее распространенных проблем с Anaconda.
самый простой способ-использовать pip (http://en.wikipedia.org/wiki/Pip_ (package_manager)), который является менеджером пакетов для пакетов python, таких как apt на Ubuntu или Homebrew на mac (который я бы также рекомендовал вам получить, но не совсем уместен в этой ситуации). Pip предоставит вам список пакетов python, которые вы можете искать и устанавливать, и pip будет обрабатывать конфигурацию и обновление этих пакетов. Pip по умолчанию поставляется с Python, но не установлен, но установка pip очень проста, см. Как установить pip на macOS или OS X?, все, что вам нужно сделать, это запустить sudo easy_install pip который установит pip (это предполагает, что у вас уже установлен python в вашей системе, если вы не установите его перед запуском этой команды). Затем вы можете использовать pip для установки numpy с помощью sudo pip install numpy , который установит пакет numpy. Вы также можете использовать pip для поиска пакетов с помощью pip search
что позволяет выполнять поиск по списку пакетов python.
Примечание.: У меня недостаточно репутации, чтобы прокомментировать ответ выше меня, но поскольку я использовал Anaconda, я хотел бы указать, что Anaconda-это полная IDE, и что установка Anaconda также устанавливает другую версию Python в вашей системе, которая может вызвать проблемы при использовании оболочки или запуске ваших программ python, которые требуют пакетов, предоставляемых Anaconda за пределами IDE.
установка numpy используя pip не работает для меня Mac OSX 10.12.6. Его не обнаружили. Вместо этого я установил с помощью квас, и это сработало!
чтобы проверить, правильно ли он установлен,
если ошибка не отображается, значит, она была установлена правильно.
Источник