donut

Python Tensorflow CNN_basic

Tensorflow/CNN

 

 

 

CNN 기본 원리 실습

파이썬 텐서플로우 CNN 코드 실습.
CNN : 합성곱 신경망(Convolutional Neural Network)
이미지의 특징을 찾아 분류하는데 용이하게 쓰임

모듈 세팅

In [20]:
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
 

실습에 사용할 이미지 준비

In [21]:
#4차원의 텐서 준비
image= tf.constant([[[[1],[2],[3]],
                    [[4],[5],[6]],
                    [[7],[8],[9]]]],dtype = np.float32)
#배치size : 사진의 갯수
#채널 수 : 색상구분 (회색만으로 구분하기 때문에 1)
print("배치size, 세로, 가로, 채널 수",image.shape)
#
plt.imshow(image.numpy().reshape(3,3), cmap='Greys')
plt.show()
 
배치size, 세로, 가로, 채널 수 (1, 3, 3, 1)
 
 

필터, con레이어 설정 패딩 사용x

In [22]:
print("image.shape, 배치size, 세로, 가로, 채널", image.shape)

#필터로 사용할 weight
#2*2로 이루어져 있고, 각 값이 1로 된 필터임
#세로, 가로, 채널, 갯수
weight = np.array([[[[1.]],[[1.]]],
                   [[[1.]],[[1.]]]])
print("weight.shape, 세로, 가로, 채널, 갯수", weight.shape)
#init설정
weight_init = tf.constant_initializer(weight)

#con레이어 설정
#필터 1개, 커널사이즈(필터사이즈) 2*2 ->2, 패딩 x(valid), stribe =1(디폴트)

conv2d = keras.layers.Conv2D(filters=1, kernel_size=2, padding='VALID', 
                             kernel_initializer=weight_init)(image)
#배치size, 세로, 가로, 채널 
print("conv2d.shape , 배치size, 세로, 가로, 채널 ", conv2d.shape)
print(conv2d.numpy().reshape(2,2))
plt.imshow(conv2d.numpy().reshape(2,2), cmap='gray')
plt.show

#패딩을 사용하지 않았기 때문에, conv2연산후 가로세로가 줄었다.
 
image.shape, 배치size, 세로, 가로, 채널 (1, 3, 3, 1)
weight.shape, 세로, 가로, 채널, 갯수 (2, 2, 1, 1)
conv2d.shape , 배치size, 세로, 가로, 채널  (1, 2, 2, 1)
[[12. 16.]
 [24. 28.]]
Out[22]:
<function matplotlib.pyplot.show(close=None, block=None)>
 
 

패딩 사용

In [23]:
print("image.shape, 배치size, 세로, 가로, 채널", image.shape)

#필터로 사용할 weight
#2*2로 이루어져 있고, 각 값이 1로 된 필터임
#세로, 가로, 채널, 갯수
weight = np.array([[[[1.]],[[1.]]],
                   [[[1.]],[[1.]]]])
print("weight.shape, 세로, 가로, 채널, 갯수", weight.shape)
#init설정
weight_init = tf.constant_initializer(weight)

#con레이어 설정
#필터 1개, 커널사이즈(필터사이즈) 2*2 ->2, 패딩 O(same), stribe =1(디폴트)

conv2d = keras.layers.Conv2D(filters=1, kernel_size=2, padding='SAME', 
                             kernel_initializer=weight_init)(image)
#배치size, 세로, 가로, 채널 
print("conv2d.shape , 배치size, 세로, 가로, 채널 ", conv2d.shape)
print(conv2d.numpy().reshape(3,3))
plt.imshow(conv2d.numpy().reshape(3,3), cmap='gray')
plt.show

#패딩을 사용하지 않았기 때문에, conv2연산후 가로세로가 줄었다.
 
image.shape, 배치size, 세로, 가로, 채널 (1, 3, 3, 1)
weight.shape, 세로, 가로, 채널, 갯수 (2, 2, 1, 1)
conv2d.shape , 배치size, 세로, 가로, 채널  (1, 3, 3, 1)
[[12. 16.  9.]
 [24. 28. 15.]
 [15. 17.  9.]]
Out[23]:
<function matplotlib.pyplot.show(close=None, block=None)>
 
 

필터를 여러개 사용하기

In [25]:
print("image.shape, 배치size, 세로, 가로, 채널", image.shape)


#필터는 모두 2*2로 이우러져있음
#필터1은 1로만 채워짐
#필터2는 10으로만 채워짐
#필터3은 -1로만 채워짐


weight = np.array([[[[1.,10.,-1.]],[[1.,10.,-1.]]],
                   [[[1.,10.,-1.]],[[1.,10.,-1.]]]])
print("weight.shape, 세로, 가로, 채널, 갯수", weight.shape)

weight_init = tf.constant_initializer(weight)
conv2d = keras.layers.Conv2D(filters=3, kernel_size=2, padding='SAME',
                             kernel_initializer=weight_init)(image)
print("conv2d.shape , 배치size, 세로, 가로, 채널 ", conv2d.shape)
feature_maps = np.swapaxes(conv2d, 0, 3)
for i, feature_map in enumerate(feature_maps):
    print(feature_map.reshape(3,3))
    plt.subplot(1,3,i+1), plt.imshow(feature_map.reshape(3,3), cmap='gray')

plt.show()
 
image.shape, 배치size, 세로, 가로, 채널 (1, 3, 3, 1)
weight.shape, 세로, 가로, 채널, 갯수 (2, 2, 1, 3)
conv2d.shape , 배치size, 세로, 가로, 채널  (1, 3, 3, 3)
[[12. 16.  9.]
 [24. 28. 15.]
 [15. 17.  9.]]
[[120. 160.  90.]
 [240. 280. 150.]
 [150. 170.  90.]]
[[-12. -16.  -9.]
 [-24. -28. -15.]
 [-15. -17.  -9.]]
 
 

해당 포스팅은 모두를 위한 딥러닝, 부스트코스를 참고하여 작성하였습니다.

In [ ]:
 

'Tensorflow > CNN' 카테고리의 다른 글

Python Tensorflow CNN_pooling  (0) 2020.08.26