3-3-2-3. Why Use NumPy?

NumPy is short for Numerical Python and is

a library designed for efficient Scientific Computation.

It’s built on top of the programming language C,

which works at a lower level on our computer.

To understand what this means for the speed of our code,

see the link in the instructor notes.

At the core of NumPy,

is its N-dimensional array object.

This is just a multi-dimensional array that

holds a group of elements that all have the same data type.

In other words, it’s like a grid that can take on

many shapes and enforces every element in that grid to have the same type,

whether that’s string, float,

boolean, or something else.

Making arrays only able to hold one data type at a time

helps NumPy make very quick computations with vector operations.

These arrays, along with many useful functions in NumPy,

can significantly optimize and simplify operations on data.

Here’s a simple example that demonstrates this.

First, let’s import NumPy with the standard alias for this library, NP.

This generates an array of 100 million floats between zero and one.

Let’s compare the time it takes playing Python

versus NumPy to calculate the mean of this array.

Instead of Python, we do this by getting the sum of

X and dividing that by the length of X, pretty straightforward.

Using the time package,

we can check how long this line of code takes to run.

That took about 9.3 seconds.

Makes sense that it took a while with 100 million values.

Now, let’s see how long it takes NumPy.

That was ridiculously faster.

NumPy took only 0.092 seconds,

while plain Python took 9.31.

As you saw, NumPy can make a difference of orders of magnitude in computation time.

Imagine how much this speeds up the process for

more complex situations that require many more calculations.

For example, let’s say we’re engineering a whole new feature or column in a dataset,

which you compute by multiplying the values and two columns

together and dividing that by the values in another for each row.

Unlike NumPy, plain Python would require

a massively long loop through all of

the rows to compute the new value for each individual row.

In many machine learning problems,

you’ll often find yourself using NumPy arrays in many situations.

For instance, you might use a NumPy array to hold

the pixel values of an image that will be fed into a model for image classification.

Later, we’ll also learn about a popular data science package,

Pandas, which is very useful for manipulating datasets.

It’s actually built on top of NumPy,

which is why its computations are so fast.

Now that you’ve learned a bit about the power of NumPy, let’s get started.

NumPy는 Numerical Python의 약자이며

효율적인 과학적 계산을 위해 설계된 라이브러리입니다.

프로그래밍 언어 C를 기반으로 구축되었으며,

우리 컴퓨터의 낮은 수준에서 작동합니다.

이것이 우리 코드의 속도에 무엇을 의미하는지 이해하려면,

강사 노트의 링크를 참조하세요.

Numpy의 핵심에는

N차원 배열 객체입니다.

이것은 다차원 배열일 뿐입니다.

모두 동일한 데이터 유형을 갖는 요소 그룹을 보유합니다.

즉,

많은 모양을 만들고 해당 그리드의 모든 요소가 동일한 유형을 갖도록 강제합니다.

그것이 문자열이든, 부동 소수점이든,

부울 또는 다른 것.

한 번에 하나의 데이터 유형만 저장할 수 있는 배열 만들기

NumPy는 벡터 연산으로 매우 빠른 계산을 할 수 있도록 도와줍니다.

NumPy의 많은 유용한 기능과 함께 이러한 배열은

데이터 작업을 크게 최적화하고 단순화할 수 있습니다.

다음은 이를 보여주는 간단한 예입니다.

먼저 이 라이브러리의 표준 별칭인 NP를 사용하여 NumPy를 가져오겠습니다.

이것은 0과 1 사이에 1억 개의 부동 소수점 배열을 생성합니다.

파이썬을 플레이하는 데 걸리는 시간을 비교해 봅시다.

NumPy와 비교하여 이 배열의 평균을 계산합니다.

Python 대신

X를 X의 길이로 나누는 것은 매우 간단합니다.

타임 패키지를 이용하면,

이 코드 줄이 실행되는 데 걸리는 시간을 확인할 수 있습니다.

약 9.3초가 소요되었습니다.

1억 개의 값으로 시간이 걸렸다는 것은 의미가 있습니다.

이제 Numpy가 얼마나 오래 걸리는지 봅시다.

그것은 터무니없이 빨랐다.

NumPy는 0.092초 밖에 걸리지 않았습니다.

일반 Python은 9.31이 걸렸습니다.

보았듯이 NumPy는 계산 시간에 엄청난 차이를 만들 수 있습니다.

이렇게 하면 프로세스 속도가 얼마나 빨라질지 상상해 보세요.

더 많은 계산이 필요한 더 복잡한 상황.

예를 들어 데이터세트에서 완전히 새로운 기능이나 열을 엔지니어링한다고 가정해 보겠습니다.

값과 두 개의 열을 곱하여 계산합니다.

함께 각 행에 대한 다른 값으로 나눕니다.

NumPy와 달리 일반 Python에는 다음이 필요합니다.

모든 것을 통해 엄청나게 긴 루프

각 개별 행에 대한 새 값을 계산하는 행.

많은 기계 학습 문제에서

많은 상황에서 NumPy 배열을 사용하는 경우가 많습니다.

예를 들어, NumPy 배열을 사용하여

이미지 분류를 위해 모델에 공급될 이미지의 픽셀 값입니다.

나중에 인기 있는 데이터 과학 패키지에 대해서도 배우게 됩니다.

Pandas는 데이터 세트를 조작하는 데 매우 유용합니다.

실제로 NumPy를 기반으로 구축되었습니다.

그래서 계산이 너무 빠릅니다.

NumPy의 힘에 대해 조금 배웠으니 이제 시작하겠습니다.

Why Use NumPy

You may be wondering why people use NumPy – after all, Python can handle lists, as you learned in the Intro to Python lessons. Let’s explore in the video below:

Here is the code demonstrated in the video above:

# Why use NumPy?
import time
import numpy as np
x = np.random.random(100000000)

# Case 1
start = time.time()
sum(x) / len(x)
print(time.time() - start)

# Case 2
start = time.time()
np.mean(x)
print(time.time() - start)

Benefits of using NumPy

Even though Python lists are great on their own, NumPy has a number of key features that give it great advantages over Python lists. Below are a few convincingly strong features:

  1. One such feature is speed. When performing operations on large arrays NumPy can often perform several orders of magnitude faster than Python lists. This speed comes from the nature of NumPy arrays being memory-efficient and from optimized algorithms used by NumPy for doing arithmetic, statistical, and linear algebra operations.
  2. Another great feature of NumPy is that it has multidimensional array data structures that can represent vectors and matrices. You will learn all about vectors and matrices in the Linear Algebra section of this course later on, and as you will soon see, a lot of machine learning algorithms rely on matrix operations. For example, when training a Neural Network, you often have to carry out many matrix multiplications. NumPy is optimized for matrix operations and it allows us to do Linear Algebra operations effectively and efficiently, making it very suitable for solving machine learning problems.
  3. Another great advantage of NumPy over Python lists is that NumPy has a large number of optimized built-in mathematical functions. These functions allow you to do a variety of complex mathematical computations very fast and with very little code (avoiding the use of complicated loops) making your programs more readable and easier to understand.

These are just some of the key features that have made NumPy an essential package for scientific computing in Python. In fact, NumPy has become so popular that a lot of Python packages, such as Pandas, are built on top of NumPy.

Good to Read

You can read how to use NumPy for efficient computation, from the research article titled The NumPy array: a structure for efficient numerical computation by Walt et. al., 2011. The article is available here.

Supporting Official Resource

If you are new to NumPy, we recommend you develop the practice of referring to the official NumPy User Guide, whenever you are looking for any numerical utility function.

Dr. Serendipity에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

Continue reading