728x90
반응형
import numpy as np
### Create array using List ###
# Scala
a0 = np.array(1)
print(a0) # 1
print(type(a0)) # <class 'numpy.ndarray'> // n dimensional array
print(a0.shape) # ()
# Vector
a1 = np.array([1, 2, 3, 4, 5])
print(a1) # [1 2 3 4 5]
print(type(a1)) # <class 'numpy.ndarray'>
print(a1.shape) # (5,)
print(a1[0], a1[1], a1[2], a1[3], a1[4]) # 1, 2, 3, 4, 5 Access each element.
a1[0] = 4 # Access each element and modifies.
a1[1] = 5
a1[2] = 6
print(a1) # [4 5 6 4 5] Modified each element.
# Matrix
a2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # List in the list. [[]]
print(a2) # [[1 2 3]
# [4 5 6]
# [7 8 9]]
print(type(a2)) # <class 'numpy.ndarray'>
print(a2.shape) # (3, 3) - 3 by 3
print(a2[0, 0], a2[1, 1], a2[2, 2]) # 1 5 9 Access each element [r, c]
# Tensor
a3 = np.array([[[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]]])
print(a3) #[[[ 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]]]
print(a3.shape) # (3, 3, 3) - 3 by 3 by 3
### Create and initialize arrays with Numpy method ###
# Vector
x1 = np.zeros(10)
print(x1) # [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] Initialize 10 elements to zero.
y1 = np.ones(10)
print(y1) # [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] Initialize 10 elements to one.
# Matrix
x2 = np.zeros((3, 3))
print(x2) #[[0. 0. 0.] Initialize 9 element to zero.
# [0. 0. 0.] - 3 by 3
# [0. 0. 0.]]
y2 = np.ones((3, 2))
print(y2) #[[1. 1.] Initialize 9 element to one.
# [1. 1.] - 3 by 2
# [1. 1.]]
z2 = np.full((3, 3), 1.23)
print(z2) #[[1.23 1.23 1.23] Initialize 9 element to custom.
# [1.23 1.23 1.23] - 3 by 3
# [1.23 1.23 1.23]]
i2 = np.eye(3)
print(i2) #[[1. 0. 0.] Create Identity matrix
# [0. 1. 0.] A square matrix
# [0. 0. 1.]]
t2 = np.tri(3)
print(t2) #[[1. 0. 0.] A Triangular matrix
# [1. 1. 0.]
# [1. 1. 1.]]
e2 = np.empty(10) # Create an uninitialized array
print(e2) # [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] ← Beware of garbage value.
print(y1) # [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
l2 = np.zeros_like(y1) # Create a matrix with the same shape as the specified array.
print(l2) # [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
np.zeros.like()
np.ones_like()
np.full_like()
np.empty_like()
### Create Array with Generated Values ###
a = np.arange(0, 30, 2) # Generate an array with integer range (from 0 to 30, 2 step)
print(a) # [ 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28]
b = np.linspace(0, 1, 5)# Create an array of evenly spaced intervals within the range
print(b) # [0. 0.25 0.5 0.75 1. ]
c = np.logspace(0.1, 1, 10) # Create an array of log scales with even intervals within the range
print(c) # [ 1.25892541 1.58489319 1.99526231 2.51188643 3.16227766 3.98107171
# 5.01187234 6.30957344 7.94328235 10. ]
### Create an array with random values ###
r1 = np.random.random((3, 3)) # Create a random number of arrays(return float)
print(r1) #[[0.53211545 0.40315282 0.3655071 ] - 3 by 3
# [0.08398926 0.35323255 0.99272187]
# [0.97705483 0.10857701 0.56858021]]
r2 = np.random.randint(0, 10, (3, 3))# Generating an array of random integers in a constant interval
print(r2) #[[6 7 6]
# [4 1 5]
# [8 8 3]]
r3 = np.random.normal(0, 1, (3, 3)) # Normal distribution/ Avg = 0, Std deviation = 1, 3 x 3
print(r3) #[[ 0.10852207 1.32039278 0.17203194]
# [-0.78297992 0.09678898 -0.1776252 ]
# [ 0.90409379 1.18575751 -0.35939382]]
r4 = np.random.rand(3, 3) # Uniform distribution
print(r4) #[[0.08537755 0.96704872 0.8643199 ]
# [0.4065074 0.99676198 0.32118854]
# [0.20685903 0.47882192 0.51110865]]
r5 = np.random.randn(3, 3) # Standard normal distribution
print(r5) #[[-1.69176794 -0.53270296 -0.34607617]
# [ 0.19504317 -0.52377593 -1.72434365]
# [ 0.14757745 -1.84736909 -0.46290985]]
"""Random"""
np.random.seed(0) # 하위 생성되는 난수 값 고정 (첫 생성 난수가 default)
np.random.randint(6) # 0 or 1 or ~ or 5 0부터 5까지 랜덤한 숫자 1개
np.random.randint(1, 20) # 1부터 19까지 랜덤숫자 1개
np.random.rand(6) # 0 ~ 1의 균일분포
np.random.rand(3, 2) # 표준 정규분포 난수를 Matrix array(m, n) 생성 (rows, column)
np.random.randn(6) # 평균 0, 표준편차 1의 가우시안
np.random.randn(3, 2) # 표준정규분포 난수를 matrix array(m, n) 생성 (rows, column)
np.random.shuffle(x) # 기존의(x) 데이터의 순서 바꾸기
np.random.choice(x) # 기존의 데이터에서 값 한개를 샘플링
np.unique # 데이터에서 중복된 값을 제거하고 중복되지 않는 값의 리스트를 출력
np.bincount # 발생하지 않은 사건에 대해서도 카운트를 해줌
"""Matrix Operation"""
np.dot() # 선형대수 내적연산, 결과값이 스칼라 (m,p) dot (p,k) = (m,k)
# 1차원 배열 2개를 매개변수로 받으면 두 벡터의 내적을 반환
# 2차원 배열 2개를 매개변수로 받으면 두 행렬의 행렬곱을 반환
# 둘 중 하나가 0차원 배열(스칼라)이면 스칼라곱을 반환
# 두 번째 매개변수가 1차원 배열이면 열 벡터로 계산
A * B # 별연산은 스칼라 곱 / 브로드 캐스팅 가능 / 같은 shape 이어야함.
A @ B # 행렬 곱 / 2차원에서는 내적과 행렬곱 어떤것을 써도 무방
### Data types ###
bool_ 바이트로 저장된 불리언(Boolean)으로 True 또는 False 값을 가짐
int_ 기본 정수(integer) 타입
intc C언어에서 사용되는 int 와 동일 (일반적으로 int32 또는 int64)
intp 인덱싱에 사용되는 정수 (C언어에서 ssize_t와 동일, 일반적으로 int32 또는 int64)
int8 바이트(Byte) (-128 ~ 127)
int16 정수 (-32768 ~ 32767)
int32 정수 (-2147483648 ~ 2147483647)
int64 정수 (--)
uint8 부호 없는 정수 (0 ~ 255)
uint16 부호 없는 정수 (0 ~ 65535)
unint32 부호 없는 정수 (--)
unint64 부호 없는 정수 (--)
float16 반정밀 부동 소수점
float32 단정밀 부동 소수점
float64 배정밀 부동 소수점
float_ float64를 줄여서 표현
complex64 복소수
complex_ complex128을 줄여서 표현
d1 = np.zeros(20, dtype=int)
print(d1) # [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
d2 = np.ones((3, 3), dtype = bool)
print(d2) #[[ True True True]
# [ True True True]
# [ True True True]]
d3 = np.full((3, 3), 1.0, dtype=float)
print(d3) #[[1. 1. 1.]
# [1. 1. 1.]
# [1. 1. 1.]]
### Create Date/Time Array ###
date = np.array('2020-01-01', dtype=np.datetime64)
print(date) # 2020-01-01
adddate = date + np.arange(12)
print(adddate) #['2020-01-01' '2020-01-02' '2020-01-03' '2020-01-04' '2020-01-05'
# '2020-01-06' '2020-01-07' '2020-01-08' '2020-01-09' '2020-01-10'
# '2020-01-11' '2020-01-12']
datetime = np.datetime64('2020-06-01 12:00')
print(datetime) # 2020-06-01T12:00
datetime = np.datetime64('2020-06-01 12:00:12.34', 'ns')
print(datetime) # 2020-06-01T12:00:12.340000000
### An array inquiry ###
# Array Properties Information
a = np.arange(0, 10)
def array_info(array):
print(array)
print("ndim: ", array.ndim)
print("shape: ", array.shape)
print("dtype: ", array.dtype)
print("size: ", array.size)
print("itemsize : ", array.itemsize)
print("nbytes: ", array.nbytes)
print("strides: ", array.strides)
array_info(a)
"""
[0 1 2 3 4 5 6 7 8 9]
ndim: 1
shape: (10,)
dtype: int32
size: 10
itemsize : 4
nbytes: 40
strides: (4,) Move to next step element 4byte
"""
### Indexing ###
# Same as PYTHON
### Slicing ###
# Same as PYTHON
### Boolean Indexing ###
### Fancy Indexing ###
###
### Insert/Modify/Delete/Copy Array Values ###
a1 = np.arange(1, 10) # [1 2 3 4 5 6 7 8 9]
b1 = np.insert(a1, 0, 10) # [10 1 2 3 4 5 6 7 8 9]
c1 = np.insert(a1, 2, 10) # [ 1 2 10 3 4 5 6 7 8 9]
a2 = np.random.randint(0, 10, (3, 3))
b2 = np.insert(a2, 1, 10, axis=0) # axis = 0 : ROWS // axis = 1 : COLUMN
# Modify -> INDEXING
# Delete -> delete() Delete values at specific locations in an array // Axis must be specified
# Copy -> copy() Explicitly copy values within an array or subarray
### Array conversion ###
# Change array transposition and axis
a1 = np.array([1, 2, 3, 4, 5])
a2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
a3 = np.array([[[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]]])
print(a2)
"""
[[1 2 3]
[4 5 6]
[7 8 9]]
"""
print(a2.T)
"""
[[1 4 7]
[2 5 8]
[3 6 9]]
"""
print(a2.swapaxes(1, 0)) # swapaxes same.
"""
[[1 4 7]
[2 5 8]
[3 6 9]]
"""
print(a3)
"""
[[[ 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]]]
"""
print(a3.T)
"""
[[[ 1 10 19]
[ 4 13 22]
[ 7 16 25]]
[[ 2 11 20]
[ 5 14 23]
[ 8 17 26]]
[[ 3 12 21]
[ 6 15 24]
[ 9 18 27]]]
"""
### Change Array Size ###
### Add Array ###
# append() : Add value to end of array
a2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
c2 = np.append(a2, b2)
print(c2) # [1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9]
d2= np.append(a2, b2, axis = 0)
print(d2) # same shape
"""
[[1 2 3]
[4 5 6]
[7 8 9]
[1 2 3]
[4 5 6]
[7 8 9]]
"""
### Array connection ###
# concatenate() : Tuple or list of array connect to array as argument
# vstack() : vertical stack / vector
# hstack() : horizontal stack / matrix
# dstack() : depth stack / tensor
# stack() : Connet new dimension
### Array Segmentation ###
# split()
# vsplit() : verical Seg
# hsplit()
# dsplit()
### Array operation ###
"""
Numpy의 배열 연산은 벡터화(Vectorized)연산을 사용
일반적으로 Numpy의 범용 함수(Universal functions)를 통해 구현
배열 요소에 대한 반복적인 계산을 효율적으로 수행
"""
# Broadcasting
# Arithmetic Operators
# Absolute Function
# absolute(), abs() : 내장된 절대값 함수
# square, sqrt : 제곱, 제곱근 함수
# Exponential and Log Function
# Trigonometrical Function
# Aggregate Functions 집계 함수
# sum() : 합 계산
# cunsum() : 누적합 계산
# diff() : 차분 계산
# prod() : 곱 계산
# cumprod() : 누적곱 계산
# dot() / matmul() : 점곱 / 행렬곱 계산
# tensordot() : 텐서 곱 계산
# cross() : 벡터곱
# inner() / outer() : 내적 / 외적
# mean() : 평균 계산
# std() : 표준 편차 계산
# var(): 분산 계산
# min(): 최소값
# max() : 최대값
# argmin() : 최소값 인덱스
# argmax() : 최대값 인덱스
# median() : 중앙값
# percentile() : 백분위 수
# Comparison Operators
# Boolean Operators
# 부분 정렬 partition() : 배열에서 k개의 작은 값을 반환
728x90
반응형
'Deep Learning' 카테고리의 다른 글
Implementing a Simple Neural Network Structure Using TensorFlow (0) | 2022.09.13 |
---|---|
TensorFlow (0) | 2022.09.12 |
How To Build An Artificial Neural Network With Python (0) | 2022.09.12 |
How to Create Single Layer Neural Network with Python? (0) | 2022.09.12 |
How to create A single Layer Perceptron? (0) | 2022.09.12 |