오늘은 유명한 데이터 세트인 CIFAR10으로 CNN을 실습해보겠습니다.
import numpy as np
import pandas as pd
import os
from tensorflow.keras.datasets import cifar10
(train_images,train_labels),(test_images,test_labels) = cifar10.load_data()
tensorflow.keras.datasets
에서 cofar10
을 불러옵니다.import matplotlib.pyplot as plt
import cv2
%matplotlib inline
def show_images(images,labels,ncols=8):
figure,axs = plt.subplots(figsize=(22,6),nrows=1,ncols=ncols)
for i in range(ncols):
axs[i].imshow(images[i])
label = labels[i].squeeze()
axs[i].set_title(NAMES[int(label)])
show_images(train_images[:8],train_labels[:8],ncols=8)
axs
하나 당 한 열에 해당합니다. (즉, 8개를 불러오니 8장의 이미지가 한 행에 나열됩니다.)from tensorflow.keras.layers import Conv2D,Flatten,Dense,MaxPooling2D,Activation,Dropout, Input,GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.callbacks import ReduceLRPlateau,EarlyStopping, ModelCheckpoint, LearningRateScheduler
IMAGE_SIZE = 32
input_tensor = Input(shape=(IMAGE_SIZE,IMAGE_SIZE,3))
x = Conv2D(filters=32,kernel_size=(5,5),strides=1,padding='valid',activaiton='relu')(input_tensor)
x = Conv2D(filters=32,kernel_size=(3,3),strides=1,padding='valid',activation='relu',kernel_initializer='he_normal')(x)
x = Conv2D(filters=32,kernel_size=(3,3),strides=1,activation='relu',padding='same')(x)
x = MaxPooling2D(pool_size=(2,2))(x)
x = Conv2D(filters=64,kernel_size=(3,3),padding='same',activation='relu',kernel_initializer='he_normal')(x)
x = Conv2D(filters=64,kernel_size=(3,3),padding='same',kernel_initializer='he_normal')(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=2)(x)
x = Conv2D(filters=128,kernel_size=(3,3),padding='same',activation='relu',kernel_initializer='he_normal')(x)
x = Conv2D(filters=128,kernel_size=(3,3),padding='same',activation='relu',kernel_initializer='he_normal')(x)
x = MaxPooling2D(pool_size=2)(x)
x = Flatten(name='flatten')(x)
x = Dropout(rate=0.5)(x)
x = Dense(300,activation='relu',name='fc1')(x)
x = Dropout(rate=0.3)(x)
output = Dense(10, activation='softmax',name='output')(x)
model = Model(inputs=input_tensor,outputs=output)
model.summary()
model.compile(optimizer=Adam(),loss='categorical_crossentropy',metrics=['accuracy'])
history = model.fit(x=tr_images,y=tr_oh_labels,batch_size=64,epochs=30,validation_split=0.15)
이런 방식으로 진행시켜줍니다.
Conv2D에 대한 실습을 해보았습니다.