본문 바로가기

공부/프로그래밍

딥러닝 Tensorflow | layer, feature extraction - convolution

728x90
2021-02-03

Layer 개념 / 시각화 / Layer 적층법

In [1]:
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
In [2]:
#mnist 데이터 이미지 로드
from tensorflow.keras import datasets
(train_x, train_y), (test_x, test_y) = datasets.mnist.load_data()
In [3]:
#데이터 로드 후에는 shape 확인 필수
train_x.shape
Out[3]:
(60000, 28, 28)
In [4]:
#첫번째 이미지 할당
image = train_x[0]
In [5]:
#첫번째 이미지의 shape 확인 필수 - 사이즈, 채널 개수 등
image.shape
Out[5]:
(28, 28)
In [6]:
#이미지 시각화
plt.imshow(image,'gray')
plt.show()

.[batch_size, height, width, channel]. -> 6만개, 28x28, 1 or 3 channel

In [7]:
#규격에 맞게 만들어주기
image = image[tf.newaxis, ... , tf.newaxis]
image.shape
Out[7]:
(1, 28, 28, 1)

Feature extraction -> classification

Feature extraction

  • convolution -> subsampling -> convolution -> subsampling

    • convolution
  • weight, bias 설정을 keras에서는 쉽게 할 수 있다
    • parameters
      • filters : layer에서 나갈때 몇개의 filter를 만들 것인지 (a.k.a weight, filters, channels)
      • kernel_size : filter의 사이즈
      • strides : 몇 개의 pixel을 skip 하면서 훑어 지나갈 것인지 (사이즈에 영향 줌)
      • padding : zero padding을 만들지. (VALID; no padding, SAME; padding) (사이즈에 영향 줌)
      • activation : activation function을 만들 것인지. 당장 설정안해도 layer층을 따로 만들 수 있음
In [8]:
tf.keras.layers.Conv2D(filters=3, kernel_size=(3,3), strides=(1,1), padding='SAME', activation='relu')
Out[8]:
<tensorflow.python.keras.layers.convolutional.Conv2D at 0x1a7ef461988>
In [9]:
tf.keras.layers.Conv2D(3,3,1,'SAME') #위와 동일한 코드다. 튜플로 안줘도 상관없음
Out[9]:
<tensorflow.python.keras.layers.convolutional.Conv2D at 0x1a7f2a427c8>

image data -> convolution -> output 시각화

In [10]:
image = tf.cast(image, dtype=tf.float32) #dtype가 int8일 경우 오류발생하므로 반드시 변경해준다.
image.dtype
Out[10]:
tf.float32
In [11]:
layer = tf.keras.layers.Conv2D(5,3,1,padding='SAME')
layer
Out[11]:
<tensorflow.python.keras.layers.convolutional.Conv2D at 0x1a7f2a45108>
In [12]:
output = layer(image)
output #filter 개수 만큼 채널수가 변경 되었다, padding이 same 이라 size 변화가 없다.
Out[12]:
<tf.Tensor: shape=(1, 28, 28, 5), dtype=float32, numpy=
array([[[[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.],
         [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.],
         [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.],
         ...,
         [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.],
         [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.],
         [0., 0., 0., 0., 0.]]]], dtype=float32)>
In [13]:
plt.subplot(1,2,1)
plt.imshow(image[0,:,:,0], 'gray')

plt.subplot(1,2,2)
plt.imshow(output[0,:,:,0], 'gray')

plt.show()
In [14]:
import numpy as np
np.min(image), np.max(image)
Out[14]:
(0.0, 255.0)
In [15]:
np.min(output), np.max(output)
Out[15]:
(-234.82193, 385.1782)

weight 불러와서 시각화

  • layer.get_weights()
In [16]:
#weight는 리스트로 받게된다.
weight = layer.get_weights()
len(weight) #앞은 weight, 뒤는 bias
Out[16]:
2
In [17]:
weight[0].shape, weight[1].shape #0:weight, 1:bias
Out[17]:
((3, 3, 1, 5), (5,))
In [18]:
plt.figure(figsize=(15, 5))

plt.subplot(131)
plt.hist(output.numpy().ravel(), range=[-2,2])
plt.ylim(0,100)

plt.subplot(132)
plt.title(weight[0].shape)
plt.imshow(weight[0][:,:,0,0],'gray')#3x3확인

plt.subplot(133)
plt.title(output.shape)
plt.imshow(output[0,:,:,0],'gray')
plt.colorbar()

plt.show()
In [19]:
np.min(output), np.max(output)
Out[19]:
(-234.82193, 385.1782)

activation function

  • relu fuction 적용시, 0 미만은 0, 1 이상은 자기 값 으로 할당해줌
In [20]:
tf.keras.layers.ReLU() #parameter 설정할 것은 없다.
Out[20]:
<tensorflow.python.keras.layers.advanced_activations.ReLU at 0x1a7f3d15e48>
In [21]:
act_layer = tf.keras.layers.ReLU()
act_output = act_layer(output)
act_output
Out[21]:
<tf.Tensor: shape=(1, 28, 28, 5), dtype=float32, numpy=
array([[[[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.],
         [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.],
         [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.],
         ...,
         [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.],
         [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.],
         [0., 0., 0., 0., 0.]]]], dtype=float32)>
In [22]:
np.min(act_output), np.max(act_output)
Out[22]:
(0.0, 385.1782)
In [23]:
plt.figure(figsize=(15, 5))

plt.subplot(121)
plt.hist(act_output.numpy().ravel(), range=[-2,2])
plt.ylim(0,100)

plt.subplot(122)
plt.title(act_output.shape)
plt.imshow(act_output[0,:,:,0],'gray')

plt.show()
#0 이상만 살아남고 나머지는 다 없앤것.

pooling

  • 쉽게말해서 간소화 시켜줌. 지금은 maxpooling 사용할 것. (가장 큰 수 선택)
  • tf.keras.layers.MaxPool2D
In [24]:
pool_layer = tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=(2,2), padding='SAME')
pool_output = pool_layer(act_output)
In [25]:
act_output.shape, pool_output.shape
Out[25]:
(TensorShape([1, 28, 28, 5]), TensorShape([1, 14, 14, 5]))
In [26]:
plt.figure(figsize=(15, 5))

plt.subplot(121)
plt.hist(pool_output.numpy().ravel(), range=[-2,2])
plt.ylim(0,100)

plt.subplot(122)
plt.title(pool_output.shape)
plt.imshow(pool_output[0,:,:,0],'gray')
plt.colorbar()

plt.show()
반응형