본문 바로가기

개발/AI (ML, DL, DS, etc..)

Numpy Tutorials 01 [Notion : 1/4]

Numpy Tutorials

# Importing Module
import numpy as np

Arrays

Numpy array is a grid of values. all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array. The shape of an array is a tuple of integers giving the size of the array along each dimension.

Numpy Terminology

  • Tensor : arraymatrix와 매우 유사한 특수한 자료구조
    • 특수한 가공처리를 위해 개발된 data type이다.
    • matrix와 2dim 이상의 array와 동일시해도 무방하다.
  • axis : 각 차원의 축
    • axis = 0 : Matrix에서 row를 가리키는 축
    • axis = 1 : Matrix에서 column을 가리키는 축
  • dim : Tensor가 존재하는 축의 개수 (= 보통 col의 개수를 의미한다.)
    • 단, dim 용어의 경우 차원 2개 표현을 공용하여 사용하기도 한다. 이는 vector나 matrix의 차원과는 다른 의미이니 헷갈리지 말자!
  • rank : tensor가 몇 차원인지 나타내는 값
  • shape : 각 축(차원)에 존재하는 원소의 수
    • div ≥ 3 일 경우 가장 바깥쪽 차원부터 작성한다.
    • 이를 표헌하기에 (배치사이즈 x 행의 개수 x 열의 개수)로 말한다.
    • 4x3 2 dim matrix 2개를 만든다면 shape(2,4,3)
    • 4x3x2 3 dim matrix 3개를 만든다면 shape(3, 2, 4, 3)
  • size : 총 element의 개수

Create Arrays

  • np.array(list type)
    • np.array([1,2,3])
  • np.array(list type, dtype = data type)
    • np.array([(1,2), (3,4), dtype = float]
a = np.array([1,2,3])       # Create a rank 1 array
print(f"type : {type(a)}")  # Prints "<class 'numpy.ndarray'>"
print(f"shape : {a.shape}") # Prints "(3, )"
print(a[0], a[1], a[2])     # Prints "1 2 3"

a[0] = 5                    # Change an element of the array
print(a)                    # Prints "[5,2,3]"
print()

b = np.array([[1,2,3], [4,5,6]])    # Create a rank 2 array
print(f"shape : {b.shape}")         # Prints "(2, 3)"
print(b[0, 0], b[0,1], b[1,0])      # Prints "1 2 4"
a = np.array([(1.5,2,3), (4,5,6)], dtype=float)
a

# array([[1.5, 2. , 3. ],
#        [4. , 5. , 6. ]])

👉 Inspecting Your Array

  • numpy.array.shape
  • numpy.array.ndim
  • numpy.array.size
  • numpy.array.dtype
  • numpy.array.dtype.name
  • numpy.array.astype(_ another data type _)
t = np.array([(1,2,3), (4,5,6)])
print(f"t.shape : {t.shape}") # t.shape : (2, 3)
print(f"t.ndim : {t.ndim}") # t.ndim : 2
print(f"t.size : {t.size}") # t.size : 6
print(f"t.dtype : {t.dtype}") # t.dtype : int32
print(f"t.dtype.name : {t.dtype.name}") # t.dtype.name : int32
print(f"t.astype(str) : {t.astype(str)}")
# t.astype(str) : [['1' '2' '3']
#  ['4' '5' '6']]

👉 Initial Placeholder

  • np.zeros() : 0으로 채워진 배열을 만들기 위해 사용, 메모리를 할당받아 0으로 초기화한 뒤 반환
  • np.ones() : 1로 채워진 배열을 만들기 위해 사용
  • np.arange() : 반열린구간에서 step의 크기만큼 일정하게 떨어져 있는 숫자들을 array형태로 반환
    • numpy.arange([start, ], stop, [step, ], dtype=None)
  • np.linspace : start부터 stop까지 num개만큼 array형태로 반환
    • numpy.linspace(start, stop, num)
  • np.full() : shape에 맞게 value값을 채워 array형태로 반환
    • numpy.full(shape, value)
  • np.eye() : 특정 rank의 단위 행렬을 만든다. 정사각행렬에 주대선의 원소들이 1인 행렬
  • np.random.rand() : 주어진 형태의 난수 array를 생성
  • np.empty() : 빈 배열을 만들기 위해 사용, 메모리를 할당만 받고 초기화 없이 반환
    • numpy.empty(shape, dtype)
# np.zeros()
a = np.zeros(5)
b = np.zeros((3,4))

print(f"np.zeros(5) ▼ \\n {a}\\n")
print(f"np.zeros((3,4)) ▼ \\n {b}")

# np.zeros(5) ▼ 
#  [0. 0. 0. 0. 0.]

# np.zeros((3,4)) ▼ 
#  [[0. 0. 0. 0.]
#  [0. 0. 0. 0.]
#  [0. 0. 0. 0.]]
# np.ones()
a = np.ones(5)
b = np.ones((3,4))

print(f"np.ones(5) ▼ \\n {a}\\n")
print(f"np.ones((3,4)) ▼ \\n {b}")

# np.ones(5) ▼ 
#  [1. 1. 1. 1. 1.]

# np.ones((3,4)) ▼ 
#  [[1. 1. 1. 1.]
#  [1. 1. 1. 1.]
#  [1. 1. 1. 1.]]
# np.arange()
a = np.arange(10)
b = np.arange(1, 15, 2)
c = np.arange(9, -2, -1.5)

print(f"np.arrange(10) ▼ \\n {a}\\n")
print(f"np.arrange(1, 15, 2) ▼ \\n {b}\\n")
print(f"np.arrange(9, -2, -1.5) ▼ \\n {c}\\n")

# np.arrange(10) ▼ 
#  [0 1 2 3 4 5 6 7 8 9]

# np.arrange(1, 15, 2) ▼ 
#  [ 1  3  5  7  9 11 13]

# np.arrange(9, -2, -1.5) ▼ 
#  [ 9.   7.5  6.   4.5  3.   1.5  0.  -1.5]
# np.linspace()

import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y, color='r')
plt.show

# np.full()
f = np.full((4,3), 5)
print(f)

# [[5 5 5]
#  [5 5 5]
#  [5 5 5]
#  [5 5 5]]
# np.eye()
e = np.eye(2)
E = np.eye(8)
print(e)
print(E)

# [[1. 0.]
#  [0. 1.]]
# [[1. 0. 0. 0. 0. 0. 0. 0.]
#  [0. 1. 0. 0. 0. 0. 0. 0.]
#  [0. 0. 1. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 1. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 1. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 1. 0. 0.]
#  [0. 0. 0. 0. 0. 0. 1. 0.]
#  [0. 0. 0. 0. 0. 0. 0. 1.]]
# np.random.rand()
r = np.random.rand(5)
print(r)

# [0.6460569  0.60605689 0.67550698 0.7657232  0.09467338]
# np.empty()
em = np.empty(shape = (10, ), dtype=np.int8)
print(em)

# [  0 -20 -34  76  58   1   0   0   0   0]