[AIVLE] 딥러닝 3일차(CIFAR) + Functional API
AIVLE
2023. 3. 2. 17:10
CIFAR
이번엔 CIFAR - 10 데이터 써보자
flatten()
평탄화 - 말 그대로 쫙 펴주는거다. 어제 reshape로 했던 것을 그냥 코드 내부에서 flatten()으로 자동으로 처리해줄 수 있다.
model.add(keras.layers.Flatten())
그냥 얘만 추가해주면 나머지는 똑같다.
데이터 불러오기
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random as rd
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow import keras
라이브러리 불러오고,
(train_x, train_y), (test_x, test_y) = keras.datasets.cifar10.load_data()
이렇게 keras로 불러와주는데, 시간이 좀 걸린다. 기다려주면 알아서 다운로드 된다.
labels = { 0 : 'Airplane',
1 : 'Automobile',
2 : 'Bird',
3 : 'Cat',
4 : 'Deer',
5 : 'Dog',
6 : 'Frog',
7 : 'Horse',
8 : 'Ship',
9 : 'Truck' }
레이블 정보는 이와 같다.
Min-Max Scailing도 수행해주자.
max_x = train_x.max()
min_x = train_x.min()
x_train = (train_x - min_x) / (max_x - min_x)
x_test = (test_x - min_x) / (max_x - min_x)
y를 categorical(one-hot encoding)하게 변경해주자.
from tensorflow.keras.utils import to_categorical
len_y = len(labels)
y_train = to_categorical(train_y, len_y)
y_test = to_categorical(test_y, len_y)
이제 모델 설계
keras.backend.clear_session()
model = keras.models.Sequential()
model.add(keras.layers.Input(shape = (32, 32, 3)))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(512, activation = 'relu'))
model.add(keras.layers.Dense(512, activation = 'relu'))
model.add(keras.layers.Dense(256, activation = 'relu'))
model.add(keras.layers.Dense(128, activation = 'relu'))
model.add(keras.layers.Dense(10, activation = 'softmax'))
model.compile(loss = 'categorical_crossentropy', metrics = ['accuracy'], optimizer = 'adam')
model.summary()
나머지 fit이랑 es는 원래 하던대로 하면 된다. flatten이 추가된 것 빼고는 똑같다.
Functional API
Sequential로 모델을 설계해봤으면 functional로도 해보자
import tensorflow as tf
from tensorflow import keras
import numpy as np
x = np.array(range(40)) # [ 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]
y = np.array([0]*20 + [1]*20) # [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
데이터를 대충 넘파이로 만들어준다.
그리고 모델을 설계해보자.
keras.backend.clear_session()
input_layer = keras.layers.Input(shape=(1,))
output_layer = keras.layers.Dense(1, activation='sigmoid')(input_layer)
model = keras.models.Model(inputs=input_layer, outputs=output_layer)
model.compile(loss='binary_crossentropy', metrics=['accuracy'], optimizer='adam')
원래는 model.add(keras.layers.Input) 이런 식으로 쭉 더해왔다면,
functional은 레이어 하나하나를 직접 선언하고 쌓아올리는 구조인듯 하다.
model.fit(x, y, epochs=10, verbose=1)
학습시키는 과정은 똑같다.
미프때 데이터 뭘 줄지 좀 설렌다.
'AIVLE' 카테고리의 다른 글
[AIVLE] 딥러닝 4일차 - multi input (0) | 2023.03.03 |
---|---|
[AIVLE] 딥러닝 2일차 (0) | 2023.02.28 |
[AIVLE] 딥러닝 - keras 기초 (0) | 2023.02.27 |
[AIVLE] 머신러닝 (0) | 2023.02.24 |
[KT AIVLE 3기] 이변량분석 (0) | 2023.02.10 |