경기도 인공지능 개발 과정/Python

[Python] 텐서플로_컨볼루전(Conv2D)_실습

agingcurve 2022. 7. 12. 14:48
반응형

컨볼루전(Conv2D)

  • 컨볼루전은 이미지 처리 신호 분야에서 매우 유용한 도구임
  • 이미치 처리에서 특정 패턴의 특징이 어느 부분에 등장하는지 파악하는데 사용함
  • 특징 맵(feature map) : 대상 이미지로부터 필터를 통해 특징을 잡아냄
  • 컨볼루전 필터 하나는 대상 이미지를 보고 특징 맵 이미지 하나를 만들게 된다. 필터 하나가 이미지 하나를 만듬
  • 필터는 가중치로 이루어져 있고 컴퓨터는 특징맵을 만들어내는 컨볼루션 필터를 학습한다. 히든 레이어르 추가하는 것은 지정한 노드 개수 만큼 컴퓨터에 분류를 위한 가장 좋은 특징을 찾아 다랄고 요청하는 것임

Conv2D 실습

In [3]:
# 라이브러리 사용
import tensorflow as tf
import pandas as pd
In [4]:
# 데이터 준비
(독립, 종속), _ = tf.keras.datasets.mnist.load_data()
print(독립.shape, 종속.shape)

독립 = 독립.reshape(60000, 28, 28, 1)
종속 = pd.get_dummies(종속)
print(독립.shape, 종속.shape)
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
11501568/11490434 [==============================] - 0s 0us/step
(60000, 28, 28) (60000,)
(60000, 28, 28, 1) (60000, 10)
In [5]:
# 모델을 만들고
X = tf.keras.layers.Input(shape=[28, 28, 1])
H = tf.keras.layers.Conv2D(3, kernel_size=5, activation="swish")(X)
H = tf.keras.layers.Conv2D(6, kernel_size=5, activation="swish")(H)
H = tf.keras.layers.Flatten()(H)
H = tf.keras.layers.Dense(84, activation="swish")(H)
Y = tf.keras.layers.Dense(10, activation="softmax")(H)

model = tf.keras.models.Model(X, Y)
model.compile(loss="categorical_crossentropy", metrics="accuracy")
In [6]:
# 모델을 학습하고
model.fit(독립, 종속, epochs=10)
Epoch 1/10
1875/1875 [==============================] - 18s 4ms/step - loss: 0.4174 - accuracy: 0.9306
Epoch 2/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0822 - accuracy: 0.9778
Epoch 3/10
1875/1875 [==============================] - 7s 3ms/step - loss: 0.0534 - accuracy: 0.9846
Epoch 4/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0363 - accuracy: 0.9895
Epoch 5/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0274 - accuracy: 0.9923
Epoch 6/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0227 - accuracy: 0.9939
Epoch 7/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0210 - accuracy: 0.9944
Epoch 8/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0199 - accuracy: 0.9945
Epoch 9/10
1875/1875 [==============================] - 7s 4ms/step - loss: 0.0176 - accuracy: 0.9958
Epoch 10/10
1875/1875 [==============================] - 7s 3ms/step - loss: 0.0173 - accuracy: 0.9959
Out[6]:
<keras.callbacks.History at 0x7fda00173f90>
In [7]:
# 모델을 이용한다
pred = model.predict(독립[0:5])
pd.DataFrame(pred).round(2)
Out[7]:
012345678901234
0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0
1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0
0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0
In [8]:
# 정답 확인
종속[0:5]
Out[8]:
012345678901234
0 0 0 0 0 1 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
In [9]:
# 모델 확인
model.summary()
Model: "model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_1 (InputLayer)        [(None, 28, 28, 1)]       0         
                                                                 
 conv2d (Conv2D)             (None, 24, 24, 3)         78        
                                                                 
 conv2d_1 (Conv2D)           (None, 20, 20, 6)         456       
                                                                 
 flatten (Flatten)           (None, 2400)              0         
                                                                 
 dense (Dense)               (None, 84)                201684    
                                                                 
 dense_1 (Dense)             (None, 10)                850       
                                                                 
=================================================================
Total params: 203,068
Trainable params: 203,068
Non-trainable params: 0
_________________________________________________________________