Programming

Tensorflow Strides 인수

procodes 2020. 7. 28. 21:52
반응형

Tensorflow Strides 인수


tf.nn.avg_pool, tf.nn.max_pool, tf.nn.conv2d strides 인수 를 이해하려고합니다 .

문서는 반복적으로 말한다

보폭 : 길이가 4보다 큰 정수의 목록. 입력 텐서의 각 치수에 대한 슬라이딩 윈도우의 보폭.

내 질문은 :

  1. 4 개 이상의 정수는 각각 무엇을 나타 냅니까?
  2. 왜 그들은 convnets에 대한 보폭 [0] = strides [3] = 1을 가져야합니까?
  3. 이 예 에서는 을 참조하십시오 tf.reshape(_X,shape=[-1, 28, 28, 1]). 왜 -1입니까?

슬프게도 -1을 사용하여 문서를 재구성하는 문서의 예제는이 시나리오로 너무 잘 번역되지 않습니다.


풀링 및 컨벌루션 연산은 입력 텐서에서 "창"을 밉니다. 하여 tf.nn.conv2d입력 텐서 4 개 크기를 갖는 경우 : 예를 들어 [batch, height, width, channels], 다음에 회선이 2 차원 화면상에서 동작 height, width치수.

strides각 치수에서 윈도우가 얼마나 이동하는지 결정합니다. 일반적인 용도는 첫 번째 (일괄 처리) 및 마지막 (깊이) 보폭을 1로 설정합니다.

32x32 그레이 스케일 입력 이미지에 대해 2 차원 컨벌루션을 실행하는 매우 구체적인 예를 살펴 보겠습니다. 입력 이미지의 깊이가 1이므로 그레이 스케일이라고 말하면 간단하게 유지할 수 있습니다. 그 이미지를 다음과 같이 보자.

00 01 02 03 04 ...
10 11 12 13 14 ...
20 21 22 23 24 ...
30 31 32 33 34 ...
...

단일 예제 (배치 크기 = 1)에 대해 2x2 컨볼 루션 창을 실행 해 봅시다. 컨볼 루션에 출력 채널 깊이 8을 제공합니다.

컨벌루션에 대한 입력은 shape=[1, 32, 32, 1]입니다.

지정한 경우 strides=[1,1,1,1]padding=SAME, 그 필터의 출력이 될 것이다 [1, 32, 32, 8].

필터는 먼저 다음에 대한 출력을 만듭니다.

F(00 01
  10 11)

그런 다음 :

F(01 02
  11 12)

등등. 그런 다음 두 번째 행으로 이동하여 다음을 계산합니다.

F(10, 11
  20, 21)

그때

F(11, 12
  21, 22)

보폭을 [1, 2, 2, 1]로 지정하면 창이 겹치지 않습니다. 다음을 계산합니다.

F(00, 01
  10, 11)

그리고

F(02, 03
  12, 13)

보폭은 풀링 연산자와 유사하게 작동합니다.

질문 2 : 왜 convnet에 대해 [1, x, y, 1]을 보폭합니까?

첫 번째 1은 배치입니다. 일반적으로 배치에서 예제를 건너 뛰거나 처음에 포함하지 않아야합니다. :)

마지막 1은 컨볼 루션의 깊이입니다. 같은 이유로 일반적으로 입력을 건너 뛰고 싶지 않습니다.

conv2d 연산자가 더 일반적이므로 다른 차원을 따라 창을 미끄러지는 컨볼 루션을 만들 있지만 컨 볼넷에서는 일반적으로 사용되지 않습니다. 일반적인 용도는 공간적으로 사용하는 것입니다.

-1 -1로 재구성하는 이유 는 "전체 텐서에 필요한 크기와 일치하도록 필요한만큼 조정하십시오"라는 자리 표시 자입니다. 코드를 입력 배치 크기와 독립적으로 만드는 방법이므로 파이프 라인을 변경하고 코드 어디에서나 배치 크기를 조정할 필요가 없습니다.


입력은 4 차원이며 형식은 다음과 같습니다. [batch_size, image_rows, image_cols, number_of_colors]

일반적으로 보폭은 적용 작업 간의 겹침을 정의합니다. conv2d의 경우 컨벌루션 필터의 연속적인 적용 사이의 거리를 지정합니다. 특정 차원에서 1의 값은 모든 행 / 열에 연산자를 적용하고 2의 값은 1 초마다 등을 의미합니다.

Re 1) 컨볼 루션에 중요한 값은 2와 3이며 행과 열을 따라 컨볼 루션 필터를 적용 할 때 겹치는 부분을 나타냅니다. [1, 2, 2, 1]의 값은 매 두 번째 행과 열에 필터를 적용하고 싶다고 말합니다.

Re 2) I don't know the technical limitations (might be CuDNN requirement) but typically people use strides along the rows or columns dimensions. It doesn't necessarily make sense to do it over batch size. Not sure of the last dimension.

Re 3) Setting -1 for one of the dimension means, "set the value for the first dimension so that the total number of elements in the tensor is unchanged". In our case, the -1 will be equal to the batch_size.


Let's start with what stride does in 1-dim case.

Let's assume your input = [1, 0, 2, 3, 0, 1, 1] and kernel = [2, 1, 3] the result of the convolution is [8, 11, 7, 9, 4], which is calculated by sliding your kernel over the input, performing element-wise multiplication and summing everything. Like this:

  • 8 = 1 * 2 + 0 * 1 + 2 * 3
  • 11 = 0 * 2 + 2 * 1 + 3 * 3
  • 7 = 2 * 2 + 3 * 1 + 0 * 3
  • 9 = 3 * 2 + 0 * 1 + 1 * 3
  • 4 = 0 * 2 + 1 * 1 + 1 * 3

Here we slide by one element, but nothing stops you by using any other number. This number is your stride. You can think about it as downsampling the result of the 1-strided convolution by just taking every s-th result.

Knowing the input size i, kernel size k, stride s and padding p you can easily calculate the output size of the convolution as:

enter image description here

Here || operator means ceiling operation. For a pooling layer s = 1.


N-dim case.

Knowing the math for a 1-dim case, n-dim case is easy once you see that each dim is independent. So you just slide each dimension separately. Here is an example for 2-d. Notice that you do not need to have the same stride at all the dimensions. So for an N-dim input/kernel you should provide N strides.


So now it is easy to answer all your questions:

  1. What do each of the 4+ integers represent?. conv2d, pool tells you that this list represents the strides among each dimension. Notice that the length of strides list is the same as the rank of kernel tensor.
  2. Why must they have strides[0] = strides3 = 1 for convnets?. The first dimension is batch size, the last is channels. There is no point of skipping neither batch nor channel. So you make them 1. For width/height you can skip something and that's why they might be not 1.
  3. tf.reshape(_X,shape=[-1, 28, 28, 1]). Why -1? tf.reshape has it covered for you:

    If one component of shape is the special value -1, the size of that dimension is computed so that the total size remains constant. In particular, a shape of [-1] flattens into 1-D. At most one component of shape can be -1.


@dga has done a wonderful job explaining and I can't be thankful enough how helpful it has been. In the like manner, I will like to share my findings on how stride works in 3D convolution.

According to the TensorFlow documentation on conv3d, the shape of the input must be in this order:

[batch, in_depth, in_height, in_width, in_channels]

Let's explain the variables from the extreme right to the left using an example. Assuming the input shape is input_shape = [1000,16,112,112,3]

input_shape[4] is the number of colour channels (RGB or whichever format it is extracted in)
input_shape[3] is the width of the image
input_shape[2] is the height of the image
input_shape[1] is the number of frames that have been lumped into 1 complete data
input_shape[0] is the number of lumped frames of images we have.

Below is a summary documentation for how stride is used.

strides: A list of ints that has length >= 5. 1-D tensor of length 5. The stride of the sliding window for each dimension of input. Must have strides[0] = strides[4] = 1

As indicated in many works, strides simply mean how many steps away a window or kernel jumps away from the closest element, be it a data frame or pixel (this is paraphrased by the way).

From the above documentation, a stride in 3D will look like this strides = (1,X,Y,Z,1).

The documentation emphasizes that strides[0] = strides[4] = 1.

strides[0]=1 means that we do not want to skip any data in the batch 
strides[4]=1 means that we do not want to skip in the channel 

strides[X] means how many skips we should make in the lumped frames. So for example, if we have 16 frames, X=1 means use every frame. X=2 means use every second frame and it goes and on

strides[y] and strides[z] follow the explanation by @dga so I will not redo that part.

In keras however, you only need to specify a tuple/list of 3 integers, specifying the strides of the convolution along each spatial dimension, where spatial dimension is stride[x], strides[y] and strides[z]. strides[0] and strides[4] is already defaulted to 1.

I hope someone finds this helpful!

참고URL : https://stackoverflow.com/questions/34642595/tensorflow-strides-argument

반응형