프로그래밍/텐서플로우(tensorflow)

텐서플로우 convolutional layer 가중치 세팅

텐서플로우의 conv 레이어가 어떻게 동작하는지 실행해보려 하니, conv 레이어에 가중치를 세팅하는 문제가 발생하였다.
가중치를 세팅해주지 않는 경우, conv 레이어의 초기 가중치를 랜덤하게 생성한다.
랜덤하게 생성한 가중치는 결과값을 보기에도 불편하고 어떻게 동작하는지 확인하기 힘들어, 가중치를 세팅하는 방법에 대해 찾아보게 되었다.

import tensorflow as tf
import numpy as np
import os

os.environ["CUDA_VISIBLE_DEVICES"]='1'

image = [1,2,3,4,5,6,7,8,9]
image = np.array(image)
image = np.reshape(image, (3,3))
image = image.astype(np.float)

print("======== input =========")
print(image.shape)
print(image)

======== input =========
(3, 3)
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]

filters = np.array([2,0,0,1,1,1,0,0])
filters = np.reshape(np.array(filters), (2,2,1,2))
filters = filters.astype(np.float)

print("======== filter =========")
filter_1 = np.reshape(filters[:,:,:,0], (2,2))
print(filter_1)
filter_2 = np.reshape(filters[:,:,:,1], (2,2))
print(filter_2)

======== filter =========
[[2. 0.]
[1. 0.]]
[[0. 1.]
[1. 0.]]

# Input Layer
input_layer = tf.reshape(image, [1, 3, 3, 1])
conv1 = tf.nn.conv2d(
    input=input_layer,
    filter=filters,
    strides=[1,1,1, 1],
    padding="VALID"
    )

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    conv1_result = sess.run(conv1)
    print("======== conv1_result =========")
    conv1_result_1 = np.reshape(conv1_result[:,:,:,0], (2,2))
    print(conv1_result_1)
    conv1_result_2 = np.reshape(conv1_result[:,:,:,1], (2,2))
    print(conv1_result_1)
    print("")

======== conv1_result =========
[[ 6. 9.]
[15. 18.]]
[[ 6. 9.]
[15. 18.]]

요약

tf.nn.conv2d 레이어의 filter라는 인자로 세팅할 가중치(필터) 값을 넣어주면 된다.
이때 넣어주는 필터 데이터의 모양을 [필터x축, 필터y축, 인풋 채널, 아웃풋 채널]로 맞춰줘야 한다.
위 예제에선 인풋 데이터의 채널이 1이고, 2x2 필터를 2개 사용하였으므로 (2, 2, 1, 2) 모양으로 변경하였다.