기본 콘텐츠로 건너뛰기

keras를 이용하여 cifar10 실행해보기 (Functional API step by step)

Keras 라이브러리를 이용하여 cifar 10 데이터를 기본적인 CNN 구조를 이용하여 수행

사용하는 레이어들을 추가한다.

from keras.layers import Input, Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D


모델도 추가한다.


from keras.models import Model

구조는 기본적으로 아래와 같다.
이는 keras에서 제공하는 cifar10 예제를 참고하였다.

conv2D -> conv2D -> maxpooling -> dropout

-> conv2D -> conv2D -> maxpooling -> dropout

-> flatten -> Dense -> dropout ->Dense(마지막은 분류하고자 하는 개수, 여기서는 10)


블럭을 생성하기 전에 Input layer에 형태를 넣어줘야한다.

#Input
inputs =Input((32,32,3))

# block1
x = Conv2D(32, (3,3), activation='relu', padding='same', name='block1_conv1')(inputs) 
x = Conv2D(32, (3,3), activation='relu', padding='valid', name='block1_conv2')(x) 
x = MaxPooling2D((2, 2), name='block1_pool')(x) x = Dropout(0.25)(x) 

# block2
x = Conv2D(64, (3,3), activation='relu', padding='same', name='block2_conv1')(inputs) 
x = Conv2D(64, (3,3), activation='relu', padding='valid', name='block2_conv2')(x) 
x = MaxPooling2D((2, 2), name='block2_pool')(x) x = Dropout(0.25)(x) x = Flatten()(x) 
x = Dense(512, activation='relu', name='dense1')(x) x = Dropout(0.5)(x) 
prediction = Dense(num_classes, activation='softmax', name='dense2')(x)

#model 형성
model = Model(inputs = inputs, outputs= prediction)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, 
            validation_data=(x_test, y_test),
            shuffle=True)

#전체코드
from keras.layers import Conv2D, MaxPooling2D
from keras.models import Model

import os

batch_size = 32num_classes = 10epochs = 10data_augmentation = Truenum_predictions = 20save_dir = os.path.join(os.getcwd(), '/models', 'saved_models')
model_name = 'keras_cifar10_trained_model.h5'
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print('x_train shape: ', x_train.shape)
print(x_train.shape[0] , 'train samples')
print(x_test.shape[0], 'test samples')

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

inputs = Input((32,32,3))

# block1x = Conv2D(32, (3,3), activation='relu', padding='same', name='block1_conv1')(inputs)
x = Conv2D(32, (3,3), activation='relu', padding='valid', name='block1_conv2')(x)
x = MaxPooling2D((2, 2),  name='block1_pool')(x)
x = Dropout(0.25)(x)

# block2x = Conv2D(64, (3,3), activation='relu', padding='same', name='block2_conv1')(inputs)
x = Conv2D(64, (3,3), activation='relu', padding='valid', name='block2_conv2')(x)
x = MaxPooling2D((2, 2),  name='block2_pool')(x)
x = Dropout(0.25)(x)

x = Flatten()(x)
x = Dense(512, activation='relu', name='dense1')(x)
x = Dropout(0.5)(x)
prediction = Dense(num_classes, activation='softmax', name='dense2')(x)

opt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)

model = Model(inputs = inputs, outputs= prediction)
model.compile(loss='categorical_crossentropy',
              optimizer=opt,
              metrics=['accuracy'])

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255x_test /= 255
model.fit(x_train, y_train,
              batch_size=batch_size,
              epochs=epochs,
              validation_data=(x_test, y_test),
              shuffle=True)
























댓글

이 블로그의 인기 게시물

데이터 열로 추가하여 쌓기

import numpy as np x = [] a = np.array([1,2,3]) Out[5]: array([1, 2, 3]) a.shape Out[6]: (3,) np.concatenate((x,a)) Out[7]: array([ 1.,  2.,  3.]) x = np.concatenate((x,a)) x = np.concatenate((x,a)) Out[10]: array([ 1.,  2.,  3.,  1.,  2.,  3.]) x = [] x = np.concatenate((x,a), axis=1) => 오류발생  -. x가 차원이 안맞아서 안됨.  np.expand_dims(a,axis=1) Out[14]:  array([[1],        [2],        [3]]) b = np.expand_dims(a,axis=1) b.shape Out[16]: (3, 1) => (3,1)짜리 차원으로 확장한 후 열 방향으로 쌓을 수 있다. => 아래는 empty함수나 zeros를 사용하여 공간을 만드는 작업 x = [] x = np.empty((3,0)) x Out[19]: array([], shape=(3, 0), dtype=float64) x = np.zeros((3,0)) x Out[21]: array([], shape=(3, 0), dtype=float64) x = np.zeros((3,0)) a Out[23]: array([1, 2, 3]) b Out[24]: array([[1],        [2],        [3]]) np.concatenate((x,b), axis=1) Out[26]: array([[ 1.], ...

HTML 테스트

Lab 시리즈 화장품 구매(파란색, 가장크게) <span style="color: blue; font-size: x-large;">Lab 시리즈 화장품 구매(파란색, 가장크게)</span><br /> Lab 시리즈 화장품 구매(검은색, 보통) <span style="color: blue; font-size: x-large;"><br /></span> Lab 시리즈 화장품 구매(검은색, 보통)<br /> Lab 시리즈 화장품 구매(검은색, 보통, Airal) <span style="font-family: Arial, Helvetica, sans-serif;">Lab 시리즈 화장품 구매(검은색, 보통, Airal)</span><br /> Lab 시리즈 화장품 구매(검은색, 보통, Airal, Bold) <span style="font-family: Arial, Helvetica, sans-serif;"><b>Lab 시리즈 화장품 구매(검은색, 보통, Airal, Bold)</b></span> 하나의 문단을 의미하는 <p>태그 문장의 일부를 의미하는 <span>태그 강제줄바꿈을 의미하는 <br>태그 비교적 넓은 지역을 묶어 지정 </div>