2024.02.07
CNN
convolution Neural Network
- Image 연산, CNN의 역할
- 특징 추출: 가로 특성, 세로 특성, edge추출 등
- 이미지 변환 : 뿌옇게 하는 현상,
⇒ 전통적인 이미지에 filter를 적용하는 방식이다.
- 이미지 데이터의 입력 데이터 shape
- 이미지 데이터는 2D가 아니라 3D다.
CNN 실습
* 구글 코랩에서 진행할 때는 GPU를 적용해서 해야한다.
import tensorflow as tf
# Fashion-MNIST 데이터 적용
# CNN
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_X, train_y), (test_X, test_y) = fashion_mnist.load_data()
# train_X.shape : 60000, 28, 28
# train_y.shape : 60000,
# test_X.shape : 10000, 28, 28
# test_y.shape : 10000,
# 전처리: 이미지 데이터, 1개 픽셀이 8비트 -> 정규화 255
train_X = train_X / 255.0
test_X = test_X / 255.0
train_X[0].shape # 2D
=> (28, 28)
train_X = train_X.reshape(-1,28,28,1) # 3d -> 4d
test_X = test_X.reshape(-1,28,28,1)
# 컬러 적용시 : (-1, 28, 28, 3)
# 적용 결과
print(train_X.shape)
print(test_X.shape)
=> 60000, 28, 28, 1
=> 10000, 28, 28, 1
시도 1
# CNN 모델을 작성
model = tf.keras.Sequential([
# 입력: 1장 데이터를 기준 -> 28 28 1
# 1번 conv 레이어 + input_shape
tf.keras.layers.Conv2D(input_shape=(28,28,1), kernel_size=(3,3), filters=16),
# 2번 conv 레이어
tf.keras.layers.Conv2D(kernel_size=(3,3), filters = 32),
# 3번 conv 레이어
tf.keras.layers.Conv2D(kernel_size=(3,3), filters = 64)
### step2) 분류를 위한 FNN
tf.kears.layers.Flatten(),
tf.keras.layers.Dense(units= 128, activation="relu"),
### step3) 출력용
tf.keras.layers.Dense(units= 10, activation = 'softmax')
])
model.summary()
# 학습 방향 설정
model.compile(
loss = "sparse_categorical_crossentropy",
optimizer = tf.keras.optimizers.Adam(),
metrics = ["accuracy"]
)
history = model.fit(train_X, train_y, epochs=20,
validation_split= 0.25, batch_size= 128)
#-------------------------------------------------------------#
# 수행 결과 그래프 확인
import matplotlib.pyplot as plt
plt.subplot(1,2,1) # loss
plt.plot(history.history["loss"], "b-", label="train_loss")
plt.plot(history.history["val_loss"], "r-", label="val_loss")
plt.xlabel("Epoch")
plt.legend()
plt.subplot(1,2,2) # metrics : accuracy
plt.plot(history.history["accuracy"], "b-", label="train_accuracy")
plt.plot(history.history["val_accuracy"], "r-", label="val_accuracy")
plt.xlabel("Epoch")
plt.legend()
'ASAC 빅데이터전문가과정 > DL' 카테고리의 다른 글
ASAC 52일차_딥러닝 7일차 (0) | 2024.09.02 |
---|---|
ASAC 51일차_딥러닝 6일차 (0) | 2024.09.02 |
ASAC 50일차_딥러닝 5일차 (0) | 2024.09.02 |
ASAC 47일차_딥러닝 3일차 (0) | 2024.09.02 |
ASAC 45일차_딥러닝 1일차 (0) | 2024.09.01 |