NumPy

EDA with Python - NumPy Broadcasting

강의 홍보

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

I. 개요

  • NumPy는 C언어로 구성되었으며, 고성능의 수치계산을 위해 나온 패키지이며, Numerical Python의 약자이다.
  • Python을 활용한 데이터 분석을 수행할 때, 그리고 데이터 시각화나 전처리를 수행할 때, NumPy는 매우 자주 사용되기 때문에 한번쯤은 꼭 다듬고 가는 것이 중요하다.
  • 이전 포스트에서는 Python - NumPy 소개 및 다양한 객체 생성에 대해 다루었으니, 본 포스트 읽기에 앞서서 기본적인 개념에 대해 확인하기를 바란다.

II. 모듈 Import

import numpy as np
print(np.__version__)
1.18.4

III. NumPy 기본 활용법

  • NumPy 객체 생성을 한 뒤에, 파일 저장, 서로 다른 배열끼리의 사칙연산 등을 수행할 수 있다.

(1) NumPy 객체 파일 저장 및 불러오기

  • savetxt, loadtxt, 그리고 genfromtxt 함수를 활용하여 객체를 불러오는 예제를 실습한다.
# 객체 생성 후 저장하기
x = np.arange(0.0, 50.0, 1.0)
print(x)
np.savetxt('data.out', x, delimiter=',')
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15. 16. 17.
 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35.
 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49.]
!ls
data.out  sample_data
  • 현재 폴더에 data.out 파일이 생성된 것을 확인할 수 있다.
# `data.out` 불러오기
z = np.loadtxt('data.out', unpack=True)
print(z)
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15. 16. 17.
 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35.
 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49.]
  • 정상적으로 data.out을 불러와서 z객체에 저장된 것을 확인할 수 있다.
# genfromtxt 활용
my_array2 = np.genfromtxt('data.out', 
                          skip_header=1, 
                          filling_values=-999)
print(my_array2)
[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18.
 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36.
 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49.]
  • z객체와 마찬가지로 my_array2도 객체가 정상적으로 생성된 것을 확인할 수 있다.

EDA with Python - NumPy basic

강의 홍보

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

I. 개요

  • 파이썬 처음 입문하는 사람들을 위해서 작성하였다. 탐색작 자료분석(EDA: Exploratory Data Analysis)을 위해 가장 기초적인 뼈대가 되는 NumPy에 대해서 학습하도록 합니다.

II. Array 만들기

  • 1차원, 2차원, 3차원의 Array를 만들고 학습니다.
  • 먼저 numpy 라이브러리를 불러옵니다.
# import numpy
import numpy as np
print(np.__version__)
1.18.4
  • 현재 구글 코랩에서 제공하는 numpy 버전은 1.18.4로 확인되고 있습니다.

(1) 1차원 Array 만들기

  • 1차원 Array를 만들어 봅시다.
my_1D_array = np.array([1,3,5,7])
print(my_1D_array)
type(my_1D_array)
[1 3 5 7]





numpy.ndarray

(2) 2차원 Array 만들기

  • 이번에는 2차원 Array를 만듭니다.
my_2D_array = np.array([[1, 2, 3, 4], [2, 4, 9, 16], [4, 8, 18, 32]])
print(my_2D_array)
type(my_2D_array)
[[ 1  2  3  4]
 [ 2  4  9 16]
 [ 4  8 18 32]]





numpy.ndarray

(3) 3차원 Array 만들기

  • 이번에는 3차원 Array를 만듭니다.
my_3D_array = np.array([[[ 1, 2 , 3 , 4],[ 5 , 6 , 7 ,8]], [[ 1, 2, 3, 4],[ 9, 10, 11, 12]]])
print(my_3D_array)
type(my_3D_array)
[[[ 1  2  3  4]
  [ 5  6  7  8]]

 [[ 1  2  3  4]
  [ 9 10 11 12]]]





numpy.ndarray

III. Array Information

  • 실무에서는 데이터를 어떤 형태로 수집되는지 바로 판단하기가 어렵습니다.
  • 따라서, 수집받은 데이터를 다양한 방식으로 출력하여 정보를 알아가는 것이 좋습니다.
  • 대표적으로, ndim, shape, dtype을 통해서 확인합니다.
    • ndim은 배열의 차원수를 의미합니다.
    • shape는 tuple의 index개수와 각 index가 보유하는 elements의 개수를 반환합니다.
    • dtype는 각 게체의 데이터 타입을 표시합니다.

(1) 함수 작성

  • 저장된 1차원, 2차원, 3차원의 Array를 활용합니다.
  • 먼저, 빠르게 확인하기 위해 함수를 작성합니다.
def check_array_info(arr_obj): 
  if isinstance(arr_obj, (np.ndarray)):
    print("The current dimension is :", arr_obj.ndim)
    print("The current shape is :", arr_obj.shape)
    print("The current dtype is :", arr_obj.dtype)
    print("The current value is :\n", arr_obj)

(1) 1차원 Array의 정보 확인

  • 이제 정보를 확인합니다.
check_array_info(my_1D_array)
The current dimension is : 1
The current shape is : (4,)
The current dtype is : int64
The current value is :
 [1 3 5 7]
  • 1차원 shape의 경우에는 (4,)만 표시가 되었는데, 이는 요소의 개수만 출력됨을 의미합니다.

(2) 2차원 Array의 정보 확인

  • 2차원 배열의 정보를 확인합니다.
check_array_info(my_2D_array)
The current dimension is : 2
The current shape is : (3, 4)
The current dtype is : int64
The current value is :
 [[ 1  2  3  4]
 [ 2  4  9 16]
 [ 4  8 18 32]]

(3) 3차원 Array의 정보 확인

  • 3차원 배열의 정보를 확인합니다.
check_array_info(my_3D_array)
The current dimension is : 3
The current shape is : (2, 2, 4)
The current dtype is : int64
The current value is :
 [[[ 1  2  3  4]
  [ 5  6  7  8]]

 [[ 1  2  3  4]
  [ 9 10 11 12]]]

IV. Creating An Array

  • 이제 다양한 방식으로 NumPy를 작성해보자.
# Array of ones
ones = np.ones((3,4))
check_array_info(ones)
The current dimension is : 2
The current shape is : (3, 4)
The current dtype is : float64
The current value is :
 [[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
# Array of zeros
zeros = np.zeros((1,2,3), dtype=np.int16)
check_array_info(zeros)
The current dimension is : 3
The current shape is : (1, 2, 3)
The current dtype is : int16
The current value is :
 [[[0 0 0]
  [0 0 0]]]
# Array with random values
np_random = np.random.random((2,2))
check_array_info(np_random)
The current dimension is : 2
The current shape is : (2, 2)
The current dtype is : float64
The current value is :
 [[0.47775118 0.60277821]
 [0.01818544 0.23499141]]
# Empty Array
empty_array = np.empty((3,2))
check_array_info(empty_array)
The current dimension is : 2
The current shape is : (3, 2)
The current dtype is : float64
The current value is :
 [[2.31101775e-316 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000]]
# Full Array
full_array = np.full((2,2), 7)
check_array_info(full_array)
The current dimension is : 2
The current shape is : (2, 2)
The current dtype is : int64
The current value is :
 [[7 7]
 [7 7]]
# Array of evenly_spaced values
even_spaced_array = np.arange(10, 25, 5)
check_array_info(even_spaced_array)
The current dimension is : 1
The current shape is : (3,)
The current dtype is : int64
The current value is :
 [10 15 20]
even_spaced_array2 = np.linspace(0, 2, 9)
check_array_info(even_spaced_array2)
The current dimension is : 1
The current shape is : (9,)
The current dtype is : float64
The current value is :
 [0.   0.25 0.5  0.75 1.   1.25 1.5  1.75 2.  ]

V. Array의 메모리 체크

  • 머신러닝과 딥러닝을 수행하려면 반드시 메모리 체크가 필수다.
  • 이 부분과 관련된 함수를 작성하여 기존에 저장된 1차원, 2차원, 3차원 배열의 객체를 출력하여 본다.

(1) 함수 작성

  • check_memory_info라는 함수를 만들어보자.
def check_memory_info(arr_obj): 
  if isinstance(arr_obj, (np.ndarray)): 
    print("The current size is :", arr_obj.size)
    print("The current flags is :", arr_obj.flags)
    print("The current itemzise is :", arr_obj.itemsize)
    print("The current total consumed bytes is :", arr_obj.nbytes)
  • sizeelement의 전체 개수를 의미한다.
  • flagsmemory layout의 정보를 출력한다.
  • itemsize는 bytes 당 한 배열의 길이를 출력한다.
  • nbytes는 객체가 소비하는 전체 bytes를 출력한다.

(1) 1차원 Array의 메모리 정보 확인

check_memory_info(my_1D_array)
The current size is : 4
The current flags is :   C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

The current itemzise is : 8
The current total consumed bytes is : 32

(1) 2차원 Array의 메모리 정보 확인

check_memory_info(my_2D_array)
The current size is : 12
The current flags is :   C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

The current itemzise is : 8
The current total consumed bytes is : 96

(3) 1차원 Array의 메모리 정보 확인

check_memory_info(my_3D_array)
The current size is : 16
The current flags is :   C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

The current itemzise is : 8
The current total consumed bytes is : 128

VI. 결론

  • NumPy는 파이썬에서 다루는 데이터과학에서 다루는 매우 중요한 토대가 되는 라이브러이이다.
  • 간단하게 NumPy를 활용한 배열에 대해 학습하였다.
  • 또한, Array를 다양하게 만들어보고, Array가 가지고 있는 다양한 정보를 확인할 수 있는 여러 함수에 대해 익히는 시간을 가졌다.
  • 그러나, 여기까지는 사실상 기초이고, 이제 배열의 연산에 대해 익히는 시간을 가져야 한다.
  • 다음 시간에 Broadcasting이라는 기법을 학습할 것이다.

Reference

Mukhiya, Suresh Kumar, and Usman Ahmed. “Hands-On Exploratory Data Analysis with Python.” Packt Publishing, Mar. 2020, www.packtpub.com/data/hands-on-exploratory-data-analysis-with-python.

Python - NumPy 소개 및 다양한 객체 생성

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

I. 개요

  • NumPy는 C언어로 구성되었으며, 고성능의 수치계산을 위해 나온 패키지이며, Numerical Python의 약자이다.
  • Python을 활용한 데이터 분석을 수행할 때, 그리고 데이터 시각화나 전처리를 수행할 때, NumPy는 매우 자주 사용되기 때문에 한번쯤은 꼭 다듬고 가는 것이 중요하다.
  • 독자의 가독성을 위해 두번에 걸쳐 나눠서 연재하려고 한다.

II. 모듈 Import

import numpy as np
print(np.__version__)
1.18.4

III. 배열 생성

  • NumPy를 활용하여 Array(배열)을 만들어 본다.
  • 먼저 1차원 배열을 생성한다.
# Defining 1D array
array_1D = np.array([1,8,27,64])
print(array_1D)
[ 1  8 27 64]
  • 이번에는 2차원 배열을 생성한다.
array_2D = np.array([[1,2,3,4], [2,4,9,16], [4,8,18,32]])
print(array_2D)
[[ 1  2  3  4]
 [ 2  4  9 16]
 [ 4  8 18 32]]
  • 이번에는 3차원 배열을 생성한다.
array_3D = np.array([[[1,2,3,4],[5,6,7,8]],[[1,2,3,4],[9,10,11,12]]])
print(array_3D)
[[[ 1  2  3  4]
  [ 5  6  7  8]]

 [[ 1  2  3  4]
  [ 9 10 11 12]]]

IV. 배열에 대한 정보 확인

  • 배열의 정보를 확인하는 다양한 함수가 존재한다.
  • 현재 저장된 배열에 대해 RAM의 주소를 확인할 수 있다.
print(array_2D.data)
<memory at 0x7f1348684ea0>
  • 배열의 구조를 확인할 수 있다.
print(array_2D.shape)
(3, 4)
  • 배열의 데이터 타입을 확인할 수 있다.
print(array_2D.dtype)
int64
  • 배열의 간격 및 각 요소간의 간격에 대해서도 확인이 가능하다.

V. NumPy를 활용한 다양한 객체 생성

  • NumPy 패키지내의 함수를 활용하여 다양한 방식으로 패키지를 작성해보자.
# Array of 1
import numpy as np
ones = np.ones((3,4)) # 행, 열
print(ones)
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
# Array of 0
zeros = np.zeros((2,3,5), dtype=np.int16) # 3차원의 개수, 2차원의 개수, 1차원의 개수
print(zeros)
[[[0 0 0 0 0]
  [0 0 0 0 0]
  [0 0 0 0 0]]

 [[0 0 0 0 0]
  [0 0 0 0 0]
  [0 0 0 0 0]]]
# Array with 랜덤값
np.random.random((2,2)) # 2차원의 개수, 1차원의 개수
array([[0.25327514, 0.82196535],
       [0.77309235, 0.84250901]])
# Empty 배열
emptyArray = np.empty((3,2))
print(emptyArray)
[[0. 0.]
 [0. 0.]
 [0. 0.]]
# Full Array
fullArray = np.full((2,2), 7)
print(fullArray)
[[7 7]
 [7 7]]
# Array of Evenly-Spaced Values (1차원 배열)
evenSpacedArray = np.arange(10,50,5)
print(evenSpacedArray)
[10 15 20 25 30 35 40 45]
  • arange 특정한 규칙에 따라 증가하는 수열을 생성한다.
  • 위 예제에서는 5만큼 증가하는 수열을 만들었다.
evenSpacedArray2 = np.linspace(0,2,9)
print(evenSpacedArray2)
[0.   0.25 0.5  0.75 1.   1.25 1.5  1.75 2.  ]
evenSpacedArray3 = np.logspace(0,2,9)
print(evenSpacedArray3)
[  1.           1.77827941   3.16227766   5.62341325  10.
  17.7827941   31.6227766   56.23413252 100.        ]
  • linspace & logspace 명령은 선형 구간 혹은 로그 구간을 지정한 구간의 수만큼 분할한다.

VI. What’s Next

지금까지는 NumPy를 활용한 객체 생성에 대해 짧게 익혔다. 그러나, NumPy의 가장 중요한 것은 각각의 배열간의 연산이며, 이러한 연산기법에 대한 이해가 있어야 향후에 배우게 될 머신러닝 & 딥러닝에 대한 이해를 하는데 도움이 될 수 있기 때문에, 꼭 다음 포스트를 읽어두는 것을 추천한다.