기본 콘텐츠로 건너뛰기

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>

Tensorflow를 backend로 사용하는 Keras 설치하기 (윈도우)

참조 : https://tensorflow.blog/ - 윈도우즈에 아나콘다, 텐서플로우 설치하기 Anaconda 파이썬 패키지가 설치된 배포판 중에 하나이다. anaconda로 가상환경을 만들 수 있다. 일반적으로 python 을 다운 받아서 설치하면, 환경변수에 실행파일이 자동으로 추가되어 시스템 내에서 접근이 가능하다. 하지만, python을 사용할때 2.7이나 3.6을 동시에 사용할 때 패키지를 설치할때 겹치거나 우선순위가 2.7로 되어있어 3.6을 사용하기 어려울 수 있다. 이러한 문제를 해결하기 위해 anaconda 내에서 가상환경을 만든다. anaconda를 설치하면 anaconda폴더가 생기고, 폴더 내에 envs 폴더가 생긴다. 만약 내가 "abc"라는 가상환경을 만들고, 그 가상환경에는 tensorflow를 backend로 사용하는 keras를 설치하면, 그 가상환경에서만 keras를 사용할 수 있는 것이다. 시스템에 설치했던 python에서는 import keras를 실행하면 없는 모듈이라고 나오게된다. 이렇듯 필요할 때마다 가상환경을 만들어서 사용할 수 있다. "a" 가상환경에는 python 2.7에 opencv 2.x 버젼을 설치하고, "b" 가상환경에는 python 2.7에 opencv 3.x 버젼을 설치할 수 있게 된다. 그러면 pycharm을 실행해서 처음에 프로젝트를 만들때 interpreter로 내가 생성한 가상환경을 선택하면 되는 것이다. 가상환경을 만드는 방법들은 여러가지이다. mac에서 tensorflow설치하려고했을때는 virtualenv를 설치하라고 추천되어있었다. 하지만, 윈도우 환경에서 지금까지 anaconda를 사용하고 있었고 많은 사람들이 anaconda를 사용하는 걸로 알고 있다. Tensorflow를 backend로 사용하는 Keras 설치하기 (윈도우) 시작. anaconda 다운로드 ...