일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 키워드
- hardware
- memory
- kernel
- USENIX
- 시스템 소프트웨어
- Machine Learning
- 시스템 프로그래밍
- FTL
- github
- Samsung
- Flash Memory
- 포트 번호 변경
- linux
- Cache
- storage system
- performance
- Operating System
- software
- Intel
- overflow
- framework
- ssd
- 커널 프로그래밍
- Git
- core dumped
- rocksdb
- deep learning
- Today
- Total
Happy to visit my research note ^^
Example of Neural Network using Keras 본문

이번 챕터에서는 Neural Network를 공부하면서 해당 연습 문제를 학습한 과정을 보여드립니다.
Create Neural Network Model using Keras
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
위 코드는 keras를 사용해서 Neural Network model을 구성하는 코드이다.
우선, 'keras' modul을 import 해야한다. 그리고 'Sequential' model을 생성한다. 'Sequential' model은 layer를 sequential하게 차례대로 쌓아서 만드는 가장 간단한 neural network model이다.
다음으로, 'Dense' layer를 import 한다. 'Dense' layer는 fully connected layer를 의미하고, adjacent layer of whole neurons are connected each other.
마지막으로, 'Activation' layer를 import 한다. 'Activation' layer는 각 neuron의 출력값을 변환시켜주는 함수를 적용하는 layer이다. 예를 들어, 'sigmoid', 'relu', 'softmax' , etc. function 이 있다.
model = Sequential([
Dense(32, input_shape = (784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])
model.summary()
위 코드는 Keras를 사용해서 neural network model을 생성하는 code이다.
먼저 input layer로 784 dimension의 data를 받고 32개의 neuron으로 구성된 hidden layer를 추가했다. 이후에는 'relu' activation function을 적용하였다.
그리고, output layer 로는 10개의 neuron을 가지는 dense layer를 추가했고, 'softmax' activation function을 적용해서 multiple class classification problem을 해결하기 위한 output을 계산한다.
마지막으로, 'model.summary()' function을 호출하면, model의 architecture와 the number of parameter, etc.를 출력해서 information of model configuration을 확인할 수 있다.
model = Sequential()
model.add(Dense(32, input_dim = 784))
model.add(Activation('relu'))
model.add(Dense(10, activaiton = 'softmax'))
model.summary()
먼저, sequential() function으로 model 생성, add() function으로 첫 번째 Dense layer를 추가(input data size = 784, output neuron 개수 = 32인 fully connected layer) 한다. 다음 ReLU(Rectified Linear Unit activation) function을 적용하고, add() function을 사용해서 두 분째 Dense layer를 추가한다.(output neuron의 수가 10개이고, softmax activation function을 적용한다.)
마지막으로, summary() function을 통해 요약 정보를 출력하게 되는데 결과로는 아래와 같이 확인할 수 있다.
Optimizer
지금부터는 위에서 만든 Neural Network Model을 training하는 것을 보여준다. compile() function을 통해서 model의 training process를 설정하고 어떤 parameter를 받게 되는 지 코드와 함께 설명하겠다.
# for a multi-class classification problem
model.compile(optimizer = 'rmsprop',
loss = 'categorical_crossentropy',
metrics = ['accuracy'])
# for a binary classification problem
model.compile(optimizer = 'rmsprop',
loss = 'binary_crossentropy',
metrics = ['accuracy'])
# for a mean squared error regression problem
model.compile(optimizer = 'rmsprop',
loss = 'mse')
위 코드는 Keras model의 compiling process를 보여준다. compile() function은 다음과 같은 parameter를 받는다.
1. optimizer: training process를 설정하는데 사용되는 optimization algorithm을 선택한다. 예를 들어, 'adam', 'sgd', etc.가 있다.
2. loss: loss function을 선택한다. loss function은 model이 예측한 값과 실제 값 사이의 오차를 측정한다. classification problem의 경우, categorical_crossentropy / binary_crossentropy를 사용하고, regression의 경우 mean_squared_error를 사용하는 경우가 많다.
3. metrics: model의 평가 지표를 선택한다. classification의 경우 'accuracy'를, regression의 경우 'mse'를 주로 사용한다.
위 코드에서는 classification problem을 다루는 모델로, 'rmsprop' optimizer를 사용하였다. RMSprop optimizer는 주로 neural network learning based on gradient descent 에서 사용되는 optimization algorithm 중 하나이다. RMSprop은 이전 gradient의 제곱 평균 값을 이요해서 adaptive learning rate를 계산하는 방식으로 동작한다. 이를 통해, learning rate를 자동으로 조절해서, 더 빠르고 안정적인 training이 가능해진다. RMSprop은 대체로 Adam optimizer보다 안정적으로 수렴하는 것으로 알려져있긴 하다. 경우에 따라 다르겠지만?? ㅎㅎ,ㅎㅎ
Examples
1. binary classification
# Generate dummy data
import numpy as np
data = np.random.random((1000,100))
labels = np.random.randint(2, size = (1000, 1))
model = Sequential()
model.add(Dense( (1), activation = 'relu', input_dim = (2)))
model.add(Dense( (3), activation = (4)))
model.compile(optimizer = 'rmsprop',
loss = (5),
metrics = ['accuracy'])
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, labels, epochs = 10, batch_size = 32)
먼저, np.random.random function은 지정한 shape과 같은 배열을 생성하고, 해당 배열을 0과 1 사이의 uniform distribution에서 추출된 random value로 채운다. 여기서 np.random.random((1000,100)) 을 실행하면, row : 1000, column: 100의 2차원 배열이 생성되고, 0과 1사이의 random value로 채우게 된다.
(1) 빈칸은 32가 된다.
-> 첫 번째 dense layer의 output node의 수는 model의 complexity와 연관이 있는데 underfitting과 overfitting을 유의해서 본인은 trial and error을 통해서 32로 지정하게 되었다.
(2) 빈칸은 100이 된다.
-> 위의 dummy data에서 example = 1000, feature = 100으로 설정하였기 때문에, feature에 맞춰서 input_dimension은 100이 된다.
(3) 빈칸은 1이 된다.
-> label data의 dimension이 1이기 때문이다. labels variable은 (1000, 1) 크기의 2차원 배열로 생성되었기 때문에, output layer의 neuron 수는 1로 설정해줘야한다. label data의 의미는 supervised learning에서 사용되는 개념으로, input data와 함께 주어지는 true data이다. like classify binary options, if one is true, the other is false.
(4) 빈칸은 sigmoid를 선택하였다.
-> 이유는 sigmoid function은 S자 형태를 띄는 함수로 입력값이 커질수록 출력값이 1에 수렴하고, 입력값이 작을수록 출력값이 0에 수렴한다. -> 그리고 sigmoid activation function이 이진 분류ㅇ서 자주 사용하기 때문이다.
ReLU function은 입력값이 0보다 작으면 출력값이 0이되고, 0보다 크면 입력값을 그대로 출력한다. 이 함수는 Sigmoid 함수와 달리 기울기 손실 문제를 완화시켜주고 더 빠른 수렴 속도와 높은 성능을 보여주는 경우가 많다. -> 얘는 주로 regression, multi-class classification, image classification, etc. 에서 주로 쓰인다.
(5) 빈칸은 binary_crossentropy가 들어간다.
2. multi-class classification
# Generate dummy data
import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(10, size=(1000, 1))
model = Sequential()
model.add(Dense( 32 , activation='relu', input_dim= 100 ))
model.add(Dense( 10 , activation= 'relu' ))
model.compile(optimizer='rmsprop',
loss= 'categorical_crossentropy',
metrics=['accuracy'])
# Convert labels to categorical one-hot encoding
one_hot_labels = keras.utils.to_categorical(labels, num_classes=10)
# Train the model, iterating on the data in batches of 32 samples
model.fit(data, one_hot_labels, epochs=10, batch_size=32)
근본적인 것은 위에 binary classification과 비슷하다.
이번 코드는 example 1000개, 100개의 feature를 가진 dummy data를 생성하고, 이에 해당되는 10개의 class에 대한 random label을 지정한다.
그리고 2개의 Dense layer를 사용해서 model을 구성한다. 첫 번째 Dense layer는 32개의 output node와 ReLU activation function을 사용한다. 이는 100개의 input node를 받는다.
두 번째 Dense layer는 10개의 output node와 ReLU activation function을 사용한다. 이는 첫 번째 layer의 32개의 output 을 input으로 받는다.
compile 과정에서는 rmsprop optimizer를 사용하고, loss function으로 categorical_crossentropy를, validation metrics 로는 accuracy를 사용한다.
마지막으로, model을 10번의 epoch 동안 training하고, batch_size는 32로 지정한다. 데이터와 one-hot encoding된 label이 주어지면 model은 이를 학습하고 각 class에 대한 예측을 수행할 수 있다.
simple Neural Network model로 MNIST dataset을 이용한 숫자 이미지 분류
# Keras on mnist
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
# just a little function for pretty printing a matrix
def matprint(mat, fmt="g"):
for x in mat:
for y in x:
print('%3s'%y, end=' ')
print()
# Load the data and split it between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
print("x_train shape:", x_train.shape)
print("x_train[0] shape:", x_train[0].shape)
# matprint(x_train[0])
# plt.imshow(x_train[0], cmap='gray')
# Model / data parameters
num_classes = 10
input_shape = x_train[0].shape
# convert class vectors to binary class matrices
print('before y shape:', y_train.shape)
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
print('after y shape:', y_train.shape)
model = keras.Sequential(
[
keras.Input(shape=input_shape),
layers.Flatten(),
layers.Dense(num_classes, activation="softmax"),
]
)
model.summary()
batch_size = 128
epochs = 5
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)
score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])
위 코드는 MNIST dataset을 사용해서 숫자 이미지를 분류하는 간단한 neural network model을 구현하는 code이다.
먼저, keras.datasets.mnist.load_data() function을 사용해서 MNIST dataset을 load한다. load된 data는 60,000개의 train image와 10,000개의 test image로 구성된다.
model의 input layer에 해당하는 keras.Input function을 이용해서 input의 형태를 지정한다. 이후 layers.Flatten() function을 사용해서 input data를 1차원으로 flat화 시킨다. 그리고 마지막 output later로 layers.Dense(num_classes, activation= "softmax")를 추가해서 입력된 image를 10개의 class(0-9) 중 하나로 분류한다.
이어서 model을 compile해서, loss function으로 categorical_crossentropy를 사용하고, Optimizer로 adam을 선택한다. metrics parameter를 통해 accuracy를 평가 지표로 사용한다.
마지막으로, model.fit function을 호출해서 model을 training 시킨다. 그리고 batch_size와 epoch를 설정하고 validation_split을 사용해서 training dataset안에서 validation data를 0.1 만큼 땐다.
after training, model.evaluate 함수로 test data에 대한 loss와 accuracy를 계산한다.
'AI & Machine Learning' 카테고리의 다른 글
[2] Machine Learning (ML basics) (0) | 2023.04.20 |
---|---|
[1] AI & principle of machine learning (2) | 2023.03.17 |