상세 컨텐츠

본문 제목

[딥러닝초급]The Sliding Window

카테고리 없음

by happynaraepapa 2025. 3. 6. 11:39

본문

sources:
https://www.kaggle.com/code/ryanholbrook/the-sliding-window

The Sliding Window

Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources

www.kaggle.com


Introduction
In the previous two lessons, we learned about the three operations that carry out feature extraction from an image:
filter with a convolution layer
detect with ReLU activation
condense with a maximum pooling layer
앞 강의에서 피쳐 추출과 관련된 3가지 작업을 배웠다.
1. 합성곱레이어를 이용한 필터
2. ReLU 활성화 함수를 이용한 인지
3. Max. Pooling 레이어를 이용한 컨덴스

The convolution and pooling operations share a common feature: they are both performed over a sliding window. With convolution, this "window" is given by the dimensions of the kernel, the parameter kernel_size. With pooling, it is the pooling window, given by pool_size.
컨벌루션 과 풀링 레이어는 둘다 슬라이딩 윈도우라는 기법을 사용하고 있다. 이 윈도우는 커널의 크기에서 가져오고, 풀링에서는 비슷하게 풀링 윈도우 pool_size로 주어진다.


A 2D sliding window.
2 차원 슬라이딩 윈도우
There are two additional parameters affecting both convolution and pooling layers -- these are the strides of the window and whether to use padding at the image edges. The strides parameter says how far the window should move at each step, and the padding parameter describes how we handle the pixels at the edges of the input.
컨볼루션 레이어와 풀링 레이어에 영향을 주는 추가 요소가 두가지 있고, 스트라이드와 패딩이다.

두개의 파라미터를 넣어서 레이어는 다음과 같다.
"파이썬 코드"

from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Conv2D(filters=64,
                  kernel_size=3,
                  strides=1,
                  padding='same',
                  activation='relu'),
    layers.MaxPool2D(pool_size=2,
                     strides=1,
                     padding='same')
    # More layers follow
])


Stride
스트라이드
The distance the window moves at each step is called the stride. We need to specify the stride in both dimensions of the image: one for moving left to right and one for moving top to bottom. This animation shows strides=(2, 2), a movement of 2 pixels each step.
스트라이드는 각 스텝에서 윈도우가 움직인 거리를 의미한다. 아래 그리에서 stride =2,2,) ,각 스텝마다. strides =(2,2)로 움직인다.


What effect does the stride have? Whenever the stride in either direction is greater than 1, the sliding window will skip over some of the pixels in the input at each step.
스트라이드가 가지는 효과는 무엇일까? 스트라이드가 각 방향으로 1보다 크다면 슬라이딩 윈도우는 각 스텝마다 입력 픽셀의 일부를 건너뛰게 된다.

Because we want high-quality features to use for classification, convolutional layers will most often have strides=(1, 1). Increasing the stride means that we miss out on potentially valuble information in our summary. Maximum pooling layers, however, will almost always have stride values greater than 1, like (2, 2) or (3, 3), but not larger than the window itself.

분류(classification)를 위한 정도 높은 피쳐를 추출하고자 하면 컨볼루션 레이어에 스트라이드를 (1,1)로 줄수도 있다 (즉 빼먹는 픽셀 없도록). 스트라이드 값이 커진다는 것은 잠재적으로 유용한 정보를 스킵할 수도 있는 가능성도 커짐을 의미한다. 그러나 Maximum Pooling Layer는 항상 1보다 큰 스트라이드 값을 사용한다. (단 윈도우 자체보다 클 수는 없다.)

Finally, note that when the value of the strides is the same number in both directions, you only need to set that number; for instance, instead of strides=(2, 2), you could use strides=2 for the parameter setting
그리고 스트라이드가 각 차원마다 동일한 값이면 (2차원에서 횡축 종축이 동일한 값이면) 하나의 숫자로 파라미터를 지정할 수 있다. 즉 strides = (2,2) 대신 strides = 2로 지정할 수 있다.


Padding
패딩
When performing the sliding window computation, there is a question as to what to do at the boundaries of the input. Staying entirely inside the input image means the window will never sit squarely over these boundary pixels like it does for every other pixel in the input. Since we aren't treating all the pixels exactly the same, could there be a problem? What the convolution does with these boundary values is determined by its padding parameter. In TensorFlow, you have two choices: either padding='same' or padding='valid'. There are trade-offs with each.
슬라이딩 윈도우를 이용하는 동안 인풋이미지의 가장자리 픽셀에 대한 처리방법을 의미한다.
윈도우가 이미지 안쪽에 완전히 들어와 있다는 것은 윈도우가 가장자리에 걸쳐있지 않다는 것을 의미한다.
---(무슨소리를 하려는 건지 당췌모르겠다.)
컨볼루션 레이어는 이 경계값으로 어떤 일을 하고 있을까? 텐서 플로우에서는 패딩값으로 두가지를 넣을 수 있다.
'same' 또는 'valid'다. 두 값은 서로 상반된 특성을 가진다.


When we set padding='valid', the convolution window will stay entirely inside the input. The drawback is that the output shrinks (loses pixels), and shrinks more for larger kernels. This will limit the number of layers the network can contain, especially when inputs are small in size.
'valid'로 지정하면 컨볼루션 윈도우는 인풋이미지 내부에 완전히 머물게 된다. 이미지의 일부 픽셀을 잃게 된다.
특히 커널이 크면 클 수록 픽셀 손실이 크다. 이것은 특히 입력 데이터 양이 제한적인 경우 신경망의 레이어 숫자도 제한하게 된다.

The alternative is to use padding='same'. The trick here is to pad the input with 0's around its borders, using just enough 0's to make the size of the output the same as the size of the input. This can have the effect however of diluting the influence of pixels at the borders. The animation below shows a sliding window with 'same' padding.
'same'을 사용하면 입력값의 경계값을 0으로 변경하고 인풋값의 픽셀 숫자와 아웃풋의 픽셀숫자가 같아지도록 한다. 이렇게하면 이미지 경계가 흐릿해지는 (해당 픽셀의 영향이 희석되는) 효과가 있다.





The VGG model we've been looking at uses same padding for all of its convolutional layers. Most modern convnets will use some combination of the two. (Another parameter to tune!)
VGG 모델은 모든 컨볼루션 레이어에 같은 패딩을 적용한다. 하지만 최신의 컨브이넷에서는 두가지 패딩 방식을 조합하기도 한다. (튜닝방식의 차이)

To better understand the effect of the sliding window parameters, it can help to observe a feature extraction on a low-resolution image so that we can see the individual pixels. Let's just look at a simple circle.

파라미터 효과를 살펴보기 위해 저화질의 이미지로 부터 피쳐 추출을 해보자. 이렇게 해서 각각의 픽셀에 미치는 영향을 살펴볼 수 있게 될 것이다. 우선 간단한 원 이미지를 사용해보자.
#파이썬코드
# create an image and kernel
import tensorflow as tf
import matplotlib.pyplot as plt

plt.rc('figure', autolayout=True)
plt.rc('axes', labelweight='bold', labelsize='large',
       titleweight='bold', titlesize=18, titlepad=10)
plt.rc('image', cmap='magma')

image = circle([64, 64], val=1.0, r_shrink=3)
image = tf.reshape(image, [*image.shape, 1])
# Bottom sobel
kernel = tf.constant(
    [[-1, -2, -1],
     [0, 0, 0],
     [1, 2, 1]],
)
show_kernel(kernel)

#출력된 커널

The VGG architecture is fairly simple. It uses convolution with strides of 1 and maximum pooling with 2×2 windows and strides of 2.
VGG 구조는 간단하다. 컨볼루션 레이어로 스트라이드 1, 그리고 맥시멈풀링으로 2x2 윈도우와 스트라이드 2를 사용한다.

We've included a function in the visiontools utility script that will show us all the steps.
우리는 visiontools utility 스크립트를 추가했고, 각 스텝에 대해서 우리에게 보여줄 것.
#파이썬코드
show_extraction(
    image, kernel,

    # Window parameters
    conv_stride=1,
    pool_size=2,
    pool_stride=2,

    subplot_shape=(1, 4),
    figsize=(14, 6),
)



And that works pretty well! The kernel was designed to detect horizontal lines, and we can see that in the resulting feature map the more horizontal parts of the input end up with the greatest activation.
그리고 잘 작동하는 걸로 보인다. 커널은 horizontal 라인을 인지하도록 짜였고 결과적으로 인풋의 수평선에 가까운 부분들이 잘 활성화되었다는 것을 알 수 있다.

What would happen if we changed the strides of the convolution to 3?
만약 컨볼루션 레이어의 스트라이드를 3으로 바꾸면 어떻게 될까?
#파이썬코드
show_extraction(
    image, kernel,

    # Window parameters
    conv_stride=3,
    pool_size=2,
    pool_stride=2,

    subplot_shape=(1, 4),
    figsize=(14, 6),    
)

This seems to reduce the quality of the feature extracted. Our input circle is rather "finely detailed," being only 1 pixel wide. A convolution with strides of 3 is too coarse to produce a good feature map from it.
결과를 보면 피쳐 추출의 품질이 저하된 것 같다. 아웃풋에서 원형이 잘 유지되지 않고 있다. 따라서 컨볼루션 스트라이드를 3으로 지정한 것은 좋은 피쳐 맵을 얻기에는 너무 큰 값이었다.

Sometimes, a model will use a convolution with a larger stride in it's initial layer. This will usually be coupled with a larger kernel as well.
가끔씩 첫 레이어에 큰 컨볼루션 스트라이드를 쓰는 모델이 있다.이것은 큰 커널과 동반된다.

The ResNet50 model, for instance, uses 7×7 kernels with strides of 2 in its first layer. This seems to accelerate the production of large-scale features without the sacrifice of too much information from the input.
예를 들어 ResNet50 모델은 7x7 커널과 스트라이드 2를 첫 레이어에 쓴다. 이것은 아마도 인풋에서 손실을 줄이면서도 큰 스케일의 피쳐 추출을 빨리 하기 위해서 사용하는 것으로 보인다.