728x90
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]:
In [4]:
#첫번째 이미지 할당
image = train_x[0]
In [5]:
#첫번째 이미지의 shape 확인 필수 - 사이즈, 채널 개수 등
image.shape
Out[5]:
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]:
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층을 따로 만들 수 있음
- parameters
In [8]:
tf.keras.layers.Conv2D(filters=3, kernel_size=(3,3), strides=(1,1), padding='SAME', activation='relu')
Out[8]:
In [9]:
tf.keras.layers.Conv2D(3,3,1,'SAME') #위와 동일한 코드다. 튜플로 안줘도 상관없음
Out[9]:
image data -> convolution -> output 시각화¶
In [10]:
image = tf.cast(image, dtype=tf.float32) #dtype가 int8일 경우 오류발생하므로 반드시 변경해준다.
image.dtype
Out[10]:
In [11]:
layer = tf.keras.layers.Conv2D(5,3,1,padding='SAME')
layer
Out[11]:
In [12]:
output = layer(image)
output #filter 개수 만큼 채널수가 변경 되었다, padding이 same 이라 size 변화가 없다.
Out[12]:
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]:
In [15]:
np.min(output), np.max(output)
Out[15]:
weight 불러와서 시각화¶
- layer.get_weights()
In [16]:
#weight는 리스트로 받게된다.
weight = layer.get_weights()
len(weight) #앞은 weight, 뒤는 bias
Out[16]:
In [17]:
weight[0].shape, weight[1].shape #0:weight, 1:bias
Out[17]:
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]:
activation function¶
- relu fuction 적용시, 0 미만은 0, 1 이상은 자기 값 으로 할당해줌
In [20]:
tf.keras.layers.ReLU() #parameter 설정할 것은 없다.
Out[20]:
In [21]:
act_layer = tf.keras.layers.ReLU()
act_output = act_layer(output)
act_output
Out[21]:
In [22]:
np.min(act_output), np.max(act_output)
Out[22]:
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]:
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()
반응형
'공부 > 프로그래밍' 카테고리의 다른 글
딥러닝 Tensorflow | Keras training model.fit() 오류 (0) | 2021.02.04 |
---|---|
딥러닝 Tensorflow | Optimization, Training with Keras (0) | 2021.02.04 |
딥러닝 Tensorflow | fully-connected (0) | 2021.02.03 |
딥러닝 Tensorflow | 방학 중 진행상황 (0) | 2021.01.24 |
딥러닝 Tensorflow | (FastCampus) TensFlow를 활용한 딥러닝 기초 (0) | 2020.11.17 |