what we will learn ...

  1. what is CNN
  2. Convolution Operation
  3. Relu layer
  4. Pooling?
  5. Flattening
  6. Full Connection

1. What is CNN

----------------------------------------------------------------------------------

----------------------------------------------------------------------------------

필요성 :::: ::::: Image classification problem --------------------------------

----------------------------------------------------------------------------------

----------------------------------------------------------------------------------

2. Convolution Op

convolution : filter 를 여러번 input_image 에 적용시켜 여러개의 feature_map 을 구하는 과정

convolution op만으로도 여러 포토샵의 효과를 만들수 있음

여러개의 feature map == convolutional layer

3. Relu

여러개의 feature map 으로 이루어진 convolutional layer 를 relu 에 적용시킨다.

(각각의 픽셀값들이 0 이하이면 사라질 것이다.)

4. Max Pooling

max pooling : 하나의 feature map 을 max pool filter 통해서 pooled feature map 으로 바꾼다.

장점 : reducing size / calculation / parameters(-> prevent overfitting)

이러한 장점때문에

결과적으로 cnn 에선 이런식으로

5. Flattening

RESULT

6. Full Connection ( ANN at the tail )

**Loss Function 을 다양하게 사용하는 이유

이렇게 생긴 모델이 있다고 합시다.

강아지와 고양이 두가지의 classification 을 수행할 수 있는 모델입니다.

서로 구성을 조금 다르게 해서 성능이 약간 다른 두 모델의 loss 를 비교하고 싶습니다.

각각의 모델들은 이런 결과값을 내놓았습니다.

만약

1. 단순히 몇개 맞추었는지 비교한다면 ?

-> 결과 동일

2. label 과 softmax로 구한 ^ 을 제곱해서 평균 구하면 ( Mean Square )

-> 차이 조금 명확

3. Cross Entropy 라는 함수에 label 과 ^ 넣어서 구하면

-> 차이 매우 명확

<<< CODE >>>

------------------------Part 1 - Building the CNN-------------------------------

Importing the Keras libraries and packages


In [1]:
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense


Using TensorFlow backend.

Initialising the CNN


In [2]:
classifier = Sequential()

Step 1 - Convolution


In [3]:
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

Step 2 - Pooling


In [4]:
classifier.add(MaxPooling2D(pool_size = (2, 2)))

Adding a second convolutional layer


In [5]:
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))

classifier.add(MaxPooling2D(pool_size = (2, 2)))

Step 3 - Flattening


In [6]:
classifier.add(Flatten())

Step 4 - Full connection


In [7]:
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

Compiling the CNN


In [8]:
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy',  metrics = ['accuracy'] )

----------------------Part 2 - Fitting the CNN to the images-------------------------


In [ ]:
from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')

test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')
print(type(test_set))






classifier.fit_generator(training_set,
                         steps_per_epoch = 8000,
                         epochs = 25,
                         validation_data = test_set,
                         validation_steps = 2000)


Found 8000 images belonging to 2 classes.
Found 2000 images belonging to 2 classes.
<class 'keras.preprocessing.image.DirectoryIterator'>
Epoch 1/25
6554/8000 [=======================>......] - ETA: 576s - loss: 0.3930 - acc: 0.8152

---------------------------Part 3 - Making new predictions---------------------------


In [10]:
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
    prediction = 'dog'
else:
    prediction = 'cat'