반응형

안녕하세요.

 

오늘은 딥러닝에서 가장 많이 사용되는 ReLU를 통해 비선형함수와 선형함수의 차이점을 알아보겠습니다.

 

ReLU 함수

머신러닝에서 선형함수를 통해 회귀문제를 해결할 수 있게 되었고, 더 복잡한 문제를 풀기 위해 비선형 함수 Sigmoid, Tanh, ReLU를 나오기 시작합니다. 

 

현재까지 복잡한 문제를 딥러닝 분야에서 ReLU를 사용하는 것은 당연시 되고 있습니다. 

 

바로, 본론으로 들어가겠습니다.

 

TesorFlow, Keras, Pytorch를 통해 ReLU를 사용하는 것은 굉장히 간단합니다. 

 

신호 및 시스템의 개념적 이야기로 가보겠습니다.

 

ReLU는 왜 비선형 함수일까요?

 

 

 

선형 시스템비선형 시스템의 차이

 

선형성을 가지고 있으면 선형 시스템이고, 그 외는 비선형 시스템입니다.

 

선형성을 가지는 조건은 무엇일까요?

 

세 가지의 조건을 충족하면 선형성을 가진다고 이야기할 수 있습니다. 그 외에는 비선형 시스템으로 분류할 수 있습니다.

 

 

 

 

1. 선형적인 그래프

x = 0 에서 꺽이는 구간을 제외하고 전 구간이 선형성을 가지지만, (x =0) 부분 때문에 선형성을 가진다고 할 수 없습니다. 

 

부끄럽지만, 저는 꺾이는 부분을 제외한 전 구간이 부분 선형형태를 띄우니 선형 함수가 맞지 않나라는 생각을 해 공부를 해서 찾아보았습니다.

 

2. 동차성 ( f(ax) = a * f(x) )

 

ReLU를 간단히 설명하면, x가 0보다 작으면 f(x) = 0, x가 0보다 크면 f(x) = x 입니다. 이를 f(x) = max(0, x)라 표현하겠습니다.

 

 

① a = 3으로 가정하면, 

 

f(3x) = 3x

3 * f(x) = 3x

 

f(3x) = 3 * f(x)  = 3x

 

② a = -3 으로 가정하면

 

f(-3x) = -3x

-3 * f(x) = -3x

 

f(-3x) = -3 * f(x)  = -3x

 

ReLU는 동차성이 성립함을 알 수 있습니다.

 

 

 

 

3. 가산성 ( f(x1 + x2) = f(x1) + f(x2) )

 

x1 = -1, x2 = 2 라고 가정하면,

 

f(-1+2) = 1

 

f(-1) = 0,

f(2) =2 

f(-1) + f(2) = 2

 

f(-1+2) != f(-1) + f(2)

 

ReLU는 가산성이 성립하지 않음을 알 수 있습니다.

 

ReLU는 동차성은 성립하지만, 가산성이 성립하지 않아 선형성을 가지지 않으므로 비선형 함수임을 알 수 있었습니다. 

728x90
반응형
반응형

안녕하세요. 오늘은 Xception 리뷰 세번 째 시간입니다.

 

1. The Xception architecture

 

in particular the VGG-16 architecture , which is schematically similar to our proposed architecture 
in a few respects.

특히 VGG-16계층은 몇 가지 측면에서 Xception 계층과 개략적으로 유사합니다.

 

The Inception architecture family of convolutional neural networks, which first demonstrated the 
advantages of factoring convolutions into multiple branches operating successively on channels and then on 
space.

Inception 모듈이 여러가지 방향으로 채널과 공간에서 작동하는 장점을 소개하고 있다는 내용입니다.

 

Depthwise separable convolutions, which our proposed architecture is entirely based upon. ~~

앞 쪽에서 이야기한 Depthwise Separable Convolution의 연산량 감소로 인한 속도 증가의 장점을 소개하고
있습니다.

coding-yoon.tistory.com/77

 

[딥러닝] Depthwise Separable Covolution with Pytorch( feat. Convolution parameters VS Depthwise Separable Covolution paramet

안녕하세요. Google Coral에서 학습된 모델을 통해 추론을 할 수 있는 Coral Board & USB Accelator 가 있습니다. 저는 Coral Board를 사용하지 않고, 라즈베리파이4에 USB Accelator를 연결하여 사용할 생각입니..

coding-yoon.tistory.com

 

Residual connections, introduced by He et al. in [4], which our proposed architecture uses extensively.

Resnet에서 사용하는 Residual Connections

https://openaccess.thecvf.com/content_cvpr_2016/papers/He_Deep_Residual_Learning_CVPR_2016_paper.pdf

 

Residual Connections : BottleNeck (x)

Residual Connections를 짚고 넘어가자면, Resnet의 배경은 히든레이어가 증가함에 따라 학습이 더 잘되어야 하지만, 오히려 학습을 못하는 현상이 발생합니다. 이 현상이 vanishing/exploding gradients (기울기 손실) 문제입니다. Batch Normalization으로  어느정도 해결할 수 있지만, 근본적인 문제를 해결할 수 없습니다. 그래서 고안된 방법이 Residual Connection(mapping) 입니다. 이전의 값을 더해줌으로 기울기 손실을 방지하는 것입니다. 간단한 방법이지만 효과는 굉장히 좋습니다. 

 

dataset은 FastEval14K를 사용하였습니다. (299x299x3)

 

2. implemention

2-1 depthwise separable convolution

def depthwise_separable_conv(input_dim, output_dim):
   
    depthwise_convolution = nn.Conv2d(input_dim, input_dim, kernel_size=3, padding=1, groups=input_dim, bias=False)
    pointwise_convolution = nn.Conv2d(input_dim, output_dim, kernel_size=1, bias=False)
   
    model = nn.Sequential(
        depthwise_convolution,
        pointwise_convolution
       
    )
       
    return model

2-2 Entry flow

class entry_flow(nn.Module):
    def __init__(self):
        super(entry_flow, self).__init__()
       
        self.conv2d_init_1 = nn.Conv2d(in_channels = 3,
                                       out_channels = 32,
                                       kernel_size = 3,
                                       stride = 2,
                                      )
       
        self.conv2d_init_2 = nn.Conv2d(in_channels = 32,
                                       out_channels = 64,
                                       kernel_size = 3,
                                       stride = 1,
                                      )
       
       
        self.layer_1 = nn.Sequential(
            depthwise_separable_conv(input_dim = 64, output_dim = 128),
            nn.ReLU(),
            depthwise_separable_conv(input_dim = 128, output_dim = 128),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
           
        )
                                                             
        self.conv2d_1 = nn.Conv2d(in_channels = 64,
                                  out_channels = 128,
                                  kernel_size = 1,
                                  stride = 2
                                  )
       
        self.layer_2 = nn.Sequential(
            depthwise_separable_conv(input_dim = 128, output_dim = 256),
            nn.ReLU(),
            depthwise_separable_conv(input_dim = 256, output_dim = 256),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
           
        )
                                                             
        self.conv2d_2 = nn.Conv2d(in_channels = 128,
                                  out_channels = 256,
                                  kernel_size = 1,
                                  stride = 2
                                  )
       
        self.layer_3 = nn.Sequential(
            depthwise_separable_conv(input_dim = 256, output_dim = 728),
            nn.ReLU(),
            depthwise_separable_conv(input_dim = 728, output_dim = 728),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
           
        )
                                                             
        self.conv2d_3 = nn.Conv2d(in_channels = 256,
                                  out_channels = 728,
                                  kernel_size = 1,
                                  stride = 2
                                  )
       
        self.relu = nn.ReLU()
       
    def forward(self, x):
        x = self.conv2d_init_1(x)
        x = self.relu(x)
        x = self.conv2d_init_2(x)
        x = self.relu(x)
       
        output1_1 = self.layer_1(x)
        output1_2 = self.conv2d_1(x)
        output1_3 = output1_1 + output1_2
       
       
        output2_1 = self.layer_2(output1_3)
        output2_2 = self.conv2d_2(output1_3)
        output2_3 = output2_1 + output2_2
       
       
        output3_1 = self.layer_3(output2_3)
        output3_2 = self.conv2d_3(output2_3)
        output3_3 = output3_1 + output3_2
        y = output3_3
       
        return y

2-2 Middle flow

class middle_flow(nn.Module):
    def __init__(self):
        super(middle_flow, self).__init__()
       
        self.module_list = nn.ModuleList()
       
        layers = nn.Sequential(
                nn.ReLU(),
                depthwise_separable_conv(input_dim = 728, output_dim = 728),
                nn.ReLU(),
                depthwise_separable_conv(input_dim = 728, output_dim = 728),
                nn.ReLU(),
                depthwise_separable_conv(input_dim = 728, output_dim = 728)
            )
       
        for i in range(7):
            self.module_list.append(layers)
           
    def forward(self, x):
        for layer in self.module_list:
            x_temp = layer(x)
            x = x + x_temp
       
        return x

2-3 Exit flow

class exit_flow(nn.Module):
    def __init__(self, growth_rate=32):
        super(exit_flow, self).__init__()
       
        self.separable_network = nn.Sequential(
            nn.ReLU(),
            depthwise_separable_conv(input_dim = 728, output_dim = 728),
            nn.ReLU(),
            depthwise_separable_conv(input_dim = 728, output_dim = 1024),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        )
       
        self.conv2d_1 = nn.Conv2d(in_channels = 728,
                                  out_channels = 1024,
                                  kernel_size = 1,
                                  stride = 2
                                  )
       
        self.separable_conv_1 = depthwise_separable_conv(input_dim = 1024, output_dim = 1536)
        self.separable_conv_2 = depthwise_separable_conv(input_dim = 1536, output_dim = 2048)
       
        self.relu = nn.ReLU()
        self.avgpooling = nn.AdaptiveAvgPool2d((1))
       
        self.fc_layer = nn.Linear(2048, 10)
       
    def forward(self, x):
        output1_1 = self.separable_network(x)
        output1_2 = self.conv2d_1(x)
        output1_3 = output1_1 + output1_2
 
        y = self.separable_conv_1(output1_3)
        y = self.relu(y)
        y = self.separable_conv_2(y)
        y = self.relu(y)
        y = self.avgpooling(y)
       
        y = y.view(-1, 2048)
        y= self.fc_layer(y)
       
       
        return y

2-4 Xception

class Xception(nn.Module):
    def __init__(self):
        super(Xception, self).__init__()
        self.entry_flow = entry_flow()
        self.middle_flow = middle_flow()
        self.exit_flow = exit_flow()
       
       
       
    def forward(self, x):
        x = self.entry_flow(x)
        x = self.middle_flow(x)
        x = self.exit_flow(x)
       
        return x

 

3. Experiment result

 

다른 모델에 비해 높은 accuracy
연산량 감소
Residual Connection의 성능

4. Conclusions

Depthwise Separable Convolution이 Inception 모듈과 유사하지만, Standard Convolution 만큼 사용하기 쉽고, 높은 성능과 연산량 감소의 장점 때문에 CNN의 설계의 기초가 될 것으로 기대가 됩니다. Xception 논문 리뷰를 마치도록 하겠습니다. 첫 논문 리뷰인지라 말하고자 하는 내용을 명확하게 설명하지 못하였습니다. 혹시라도 보시다가 잘못된 부분이나 추가해야할 부분이 보이시면 피드백 주시면 감사하겠습니다.

728x90
반응형
반응형

 

 

 

https://openaccess.thecvf.com/content_cvpr_2017/papers/Chollet_Xception_Deep_Learning_CVPR_2017_paper.pdf

 

안녕하세요.

 

Xception 논문 리뷰 2회차입니다. 

 

1회차 논문리뷰로 An Extreme version of Inception module이 Depthwise Separable Convolution까지 소개했습니다.

 

아래 전 편의 글을 읽는 것을 추천드립니다.

 

https://coding-yoon.tistory.com/78?category=825914

 

[딥러닝 논문 리뷰] Xception: Deep Learning with Depthwise Separable Convolutions (feat.Pytorch)(1)

안녕하세요. 저번 Depthwise Separable Convolution 기법에 대해 글을 올렸습니다. 오늘은 이 기법을 사용한 Xception 논문에 대해 리뷰하도록 하겠습니다. https://openaccess.thecvf.com/content_cvpr_2017/html..

coding-yoon.tistory.com

 

An Extreme version of Inception module과 Depthwise Separable Convolution는 굉장히 비슷한 형태를 가지고 있습니다.

 

논문에서 소개하는 두 개의 차이점을 설명하고 있습니다.

 

Two minor differences between and “extreme” version of an Inception module and a depthwise separable 
convolution would be:

“extreme” version of an Inception module과 depthwise separable 
convolution의 두 가지 사소한 차이점은 다음과 같습니다.

 

 

 

1. Order(순서)

• The order of the operations: 
depthwise separable convolutions as usually implemented (e.g. in TensorFlow)perform first channel-wise 
spatial convolution and then perform 1x1 convolution, whereas Inception performs
the 1x1 convolution first.

Depthwise Separable Convolution : Depthwise Convolution(3x3, 5x5 ...), Pointwise Convolution 

An Extreme version of Inception module : Pointwise Convolution , Depthwise Convolution(3x3, 5x5 ...)

 

Convolution의 순서가 다르다고 합니다.

We argue that the first difference is unimportant, in particular because these operations are meant
to be used in a stacked setting.

 

스택 설정에서 사용되기 때문에 순서의 차이점은 중요하지 않다고 합니다.

 

 

 

2. Non-Linearity(비선형성)

• The presence or absence of a non-linearity after the first operation.
In Inception, both operations are followed by a ReLU non-linearity, however depthwise separable 
convolutions are usually implemented without non-linearities.

ReLU(비선형)의 유무.

 

Inception은 Convolution 수행이 후 ReLU가 붙는 반면, 

 

일반적으로 Depthwise Separable Convolution는 ReLU가 없이 구현됩니다. 

 

The second difference might matter, and we investigate it in the experimental section 
(in particular see figure 10).

 

ReLU의 유무는 중요하며, Figure 10에서 실험 결과를 보여줍니다.

 

Depthwise Separable Convolution에서 ReLU를 사용하지 않았을 때 더 높은 Accruacy를 보여줍니다.

 

It may be that the depth of the intermediate feature spaces on which spatial convolutions are applied 
is critical to the usefulness of the non-linearity:

 for deep feature spaces (e.g. those found in Inception modules) the non-linearity is helpful, 
 but for shallow ones (e.g. the 1-channel deep feature spaces of depthwise separable convolutions) it becomes harmful, 
 possibly due to a loss of information.

 

깊은 특징 공간의 경우, ReLU가 도움이 되지만  얕은 공간( 1x1 Convolution )에서는 ReLU에 의해 정보 손실이 생길 수 있기 때문에 사용하지 않는 것이 좋다는 결과입니다.

 

다음 글은 Xception의 Architecture에 대해 설명하고, Pytorch로 구현함으로 글을 Xception 논문 리뷰를 마치도록 하겠습니다. 피드백주시면 감사하겠습니다.

728x90
반응형
반응형

안녕하세요. 저번 Depthwise Separable Convolution 기법에 대해 글을 올렸습니다.

 

오늘은 이 기법을 사용한 Xception 논문에 대해 리뷰하도록 하겠습니다. 

 

https://openaccess.thecvf.com/content_cvpr_2017/html/Chollet_Xception_Deep_Learning_CVPR_2017_paper.html

 

CVPR 2017 Open Access Repository

Francois Chollet; Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017, pp. 1251-1258 We present an interpretation of Inception modules in convolutional neural networks as being an intermediate step in-between regular

openaccess.thecvf.com

 

우선, Xception을 리뷰하기 전 Inception에 대해 간단히 짚고 넘어가겠습니다. 

 

Inception 모듈로 2014년도에 가장 높은 성적을 거둔 GoogleLeNet 을 만들었습니다.

 

 

 

 

 

1. Inception Module

 

 

Inception Module

 

인셉션 모듈은 이전 단계의 활성화 지도에 다양한 필터 크기(Kernel_Size)로 합성곱 연산을 적용하는 방식입니다.

 

쉽게 표현하면, 강아지 사진에서 귀, 코, 눈 등의 특징을 다른 방향으로 보는 것입니다. 

 

다른 방향에서 보기 때문에, 같은 강아지 사진에서 다른 특성들을 추출할 수 있습니다.

 

인셉션은 적은 파라미터로 다양한 특징값을  추출하는데 의미가 있습니다.

 

class InceptionModule(nn.Module):
    def __init__(self, n_channels=10):
        super(InceptionModule, self).__init__()
        # Sequential : 연산을 차례로 수행

        self.conv2d_3k = nn.Conv2d(in_channels=n_channels,
                                   out_channels=n_channels,
                                   kernel_size=3,
                                   padding=1)

        self.conv2d_1k = nn.Conv2d(in_channels=n_channels,
                                   out_channels=n_channels,
                                   kernel_size=1)

        self.avgpool2d = nn.AvgPool2d(kernel_size=1)

    def forward(self, x):
        y1 = self.conv2d_1k(x)

        y2_1 = self.conv2d_1k(x)
        y2_2 = self.conv2d_3k(y2_1)

        y3_1 = self.avgpool2d(x)
        y3_2 = self.conv2d_3k(y3_1)

        y4_1 = self.conv2d_1k(x)
        y4_2 = self.conv2d_3k(y4_1)
        y4_3 = self.conv2d_3k(y4_2)

        out = torch.cat([y1, y2_2, y3_2, y4_3], dim=1)

        return out

 

 

2. 단순한 Inception Module

A Simplified Inception Module

 

저번 글에 나온 Depthwise Separable Convolution의 핵심 개념인 spartial correlation(3x3 convolution)cross channel correlation(1x1 convolution)이 등장합니다. 

 

여기 Standard Convolution과 차별 점은 서로가 매핑(mapping)되지 않고 독립적으로 수행하는 것입니다.

 

Figure1의 복잡함을 최대한 Simple하게 가는데 의미가 있습니다.

 

class SimplyInceptionModule(nn.Module):
    def __init__(self, n_channels=10):
        super(SimplyInceptionModule, self).__init__()
        # Sequential : 연산을 차례로 수행

        self.conv2d_3k = nn.Conv2d(in_channels=n_channels,
                                   out_channels=n_channels,
                                   kernel_size=3,
                                   padding=1)

        self.conv2d_1k = nn.Conv2d(in_channels=n_channels,
                                   out_channels=n_channels,
                                   kernel_size=1)

    def forward(self, x):
        y1_1 = self.conv2d_1k(x)
        y1_2 = self.conv2d_3k(y1_1)

        y2_1 = self.conv2d_1k(x)
        y2_2 = self.conv2d_3k(y2_1)

        y3_1 = self.conv2d_1k(x)
        y3_2 = self.conv2d_3k(y3_1)

        out = torch.cat([y1_2, y2_2, y3_2], dim=1)

        return out

 

 

3. 더 단순한 Inception module

A strictly equivalent reformulation of the simplified Inception module

 

Figure2에서 1x1 Convolution을 Input마다 독립적으로 수행했다면,

 

Figure3에서는 1x1 Convolution을 input 한 번만을 수행합니다. 

 

1x1 Convolution 수행한 output을 (그룹으로) 분리하여 3x3 Convolution을 수행합니다. 

 

Figure2를 변형하여 더 Simple하게!

 

SimplyInceptionModule3 = nn.Sequential(
    nn.Conv2d(in_channels=9,
              out_channels=9,
              kernel_size=1,
              bias=False),
              
    nn.ReLU(),

    nn.Conv2d(in_channels=9,
              out_channels=9,
              kernel_size=3,
              groups=3,
              bias=False),
    
    nn.ReLU()

)

 

 

 

 

이 논문에서 중요한 부분이라고 생각되는 부분입니다. 

 

 This observation naturally raises the question: 
 
 이 관찰은 당연히 문제를 제기합니다.
 
 what is the effect of the number of segments in the partition (and their size)?
 
 파티션의 세그먼트 수 (및 크기)는 어떤 영향을 미칩니까?
 

 

 

 

 

4. Extreme version of Inception module

Figure3에서 Output Channels를 최대로 그룹을 지어 분리하여 수행하면 어떨까?

 

An Extreme version of Inception module

 

위 논문의 질문의 가설로,  파티션의 세그먼트를 최대 단위로 수행한다면 어떻게 되는가?

 

ExtremeInception = nn.Sequential(
    nn.Conv2d(in_channels=9,
              out_channels=9,
              kernel_size=1,
              bias=False),
              
    nn.ReLU(),

    nn.Conv2d(in_channels=9,
              out_channels=9,
              kernel_size=3,
              groups=9,
              bias=False),
    
    nn.ReLU()

)

 

 

We remark that this extreme version of an Inception module is almost identical to a depthwise 
separable convolution, an operation that has been used in neural network design as early as 
2014 and has become more popular since its inclusion in the TensorFlow framework in 2016.


An extreme version of Inception module은 2014 년 초 신경망 설계에 사용되었으며 2016 년 TensorFlow 프레임 워크에 
포함 된 이후 더 널리 사용되는 Depthwise Separable Convolution과 거의 동일합니다.

 

depthwise separable convolution 와 비슷한 형태의 모듈이 생성됩니다.

 

depthwise separable convolution가 궁금하시면

 

https://coding-yoon.tistory.com/77

 

[딥러닝] Depthwise Separable Covolution with Pytorch( feat. Convolution parameters VS Depthwise Separable Covolution paramet

안녕하세요. Google Coral에서 학습된 모델을 통해 추론을 할 수 있는 Coral Board & USB Accelator 가 있습니다. 저는 Coral Board를 사용하지 않고, 라즈베리파이4에 USB Accelator를 연결하여 사용할 생각입니..

coding-yoon.tistory.com

 

Xception을 한 번에 작성할려고 했지만 생각보다 쓸 것이 많아 2편 정도로 연장될 것 같습니다. 

 

첫 논문 리뷰인데 부족한 부분이 많습니다. 피드백 주시면 감사하겠습니다.

 

 

728x90
반응형
반응형
글의 가독성을 위해 아래 링크에 정리해둠.

https://blog.naver.com/younjung1996/223413266165

 

[딥러닝] Depth-wise Separable Convolution

Depth-wise Separable Convolution은 합성곱 신경망(CNN:Convolution Neural Network)의 효율성과...

blog.naver.com

안녕하세요. 

 

Google Coral에서 학습된 모델을 통해 추론을 할 수 있는 Coral Board & USB Accelator 가 있습니다. 

 

저는 Coral Board를 사용하지 않고, 라즈베리파이4에 USB Accelator를 연결하여 사용할 생각입니다. 

 

딥러닝을 위해 나온 제품이라 할지라도 아직 부족한 부분이 많습니다.

 

이런 고성능 환경이 아닌 곳에서도 학습하고, 추론할 수 있는 모바일 넷(Mobile Net)이 개발되었습니다. 

 

그 중 Mobile Net의 Architecture에서 Depthwise Separable Convolution에 대해 이야기하겠습니다. 

 

Depthwise separable Convoltion은 Parameter를 줄임으로, 연산량을 줄이고, 속도를 높이는 기법입니다. 

 

 

 

 

 

https://hichoe95.tistory.com/48

 

Different types of Convolutions (Grouped convolution, depthwise convolution, pointwise convolution, depthwise separable convolut

오늘 정리해 볼 것들은 앞으로 정리할 논문들을 위해 미리 알아두면 좋은 convolution입니다. 각 convolution들에 대한 간단한 특징과 param수, 연산량 등에대해서 알아봅시다 ㅎㅎ 들어가기에 앞서 몇��

hichoe95.tistory.com

 

Depthwise Separable Convolution = Depthwise Convolution + Pointwise Convolution

 

아마 Depthwise Separable Convolution을 공부하실 때 위 그림을 가장 많이 보셨을겁니다.

 

 

 

Depthwise Convolution으로 채널간 Spartial Correlations을 고려하여 ~ 각각 독립적으로 패턴을 파악하고 ~ 

Pointwise Convolution으로 Cross Channel Correlations로 채널을 조절할 수 있는 ~ 블라블라

 

위 블로그 분께서 굉장히 정리를 잘해주셨습니다.

 

그럼 저의 글의 목적은 무엇이냐.

 

Standard Convolution과 Depthwise Separable Covolution를 pytorch로 구현하여 정말로 파라미터 수와 연산량이 줄어드는지 결과값을 눈으로 확인하는 것입니다.

 

 

1. Standard Convolution

Convolution = K * K * C * M

 

k : Kernel ( 3으로 가정)

c : intput_dimension (channel ) (100으로 가정)

m : output_dimension (activation map) (1000으로 가정)

 

standard_convolution = nn.Conv2d(in_channels=100, out_channels=1000, kernel_size=3, bias=False)
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 1000, 15, 15]         900,000
================================================================
Total params: 900,000
Trainable params: 900,000
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.11
Forward/backward pass size (MB): 1.72
Params size (MB): 3.43
Estimated Total Size (MB): 5.26
----------------------------------------------------------------

 

 

2. Depth-wise Convolution

Depthwise Convolutuon = K * K * C

 

k : Kernel ( 3으로 가정)

c : intput_dimension (channel ) (100으로 가정)

m : output_dimension (activation map) (1000으로 가정)

 

depthwise_convolution = nn.Conv2d(in_channels=100, out_channels=1000, kernel_size=3, groups=100,bias=False)
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1          [-1, 100, 15, 15]             900
================================================================
Total params: 900
Trainable params: 900
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.11
Forward/backward pass size (MB): 0.17
Params size (MB): 0.00
Estimated Total Size (MB): 0.29
----------------------------------------------------------------

 

 

3. Point-wise Convolution ( 1 x 1 Convolution )

Pointwise Convolutuon = C * M

 

k : Kernel ( 3으로 가정)

c : intput_dimension (channel ) (100으로 가정)

m : output_dimension (activation map) (1000으로 가정)

 

pointwise_convolution = nn.Conv2d(in_channels=100, out_channels=1000, kernel_size=1, bias=False)
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 1000, 17, 17]         100,000
================================================================
Total params: 100,000
Trainable params: 100,000
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.11
Forward/backward pass size (MB): 2.20
Params size (MB): 0.38
Estimated Total Size (MB): 2.70
----------------------------------------------------------------

 

 

4. Depthwise Separable Convolution 

Depthwise Separable Convolution = K * K * C + C * M = C( K * K + M )

 

k : Kernel ( 3으로 가정)

c : intput_dimension (channel ) (100으로 가정)

m : output_dimension (activation map) (1000으로 가정)

 

depthwise_separable_convolution = nn.Sequential(
    nn.Conv2d(in_channels=100,
              out_channels=100,
              kernel_size=3,
              groups=100,
              bias=False),

    nn.Conv2d(in_channels=100,
              out_channels=1000,
              kernel_size=1,
              bias=False)
)
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1          [-1, 100, 15, 15]             900
            Conv2d-2         [-1, 1000, 15, 15]         100,000
================================================================
Total params: 100,900
Trainable params: 100,900
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.11
Forward/backward pass size (MB): 1.89
Params size (MB): 0.38
Estimated Total Size (MB): 2.38
----------------------------------------------------------------

Depthwise Separable Convolution = Depthwise Convolution + Pointwise Convolution ( 100900 = 100000 + 900 ) 

 

Standard Convolution Parameters = 900,000

Depthwise Separable Convolution Parameters = 100,900

 

=> 약 K(Kernel Size) 제곱의 차이

 

5. Kernel Size가 값이 굉장히 크다면... ( kerenl size == 7 )

 

Standard Convolution 

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 1000, 11, 11]       4,900,000
================================================================
Total params: 4,900,000
Trainable params: 4,900,000
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.11
Forward/backward pass size (MB): 0.92
Params size (MB): 18.69
Estimated Total Size (MB): 19.73
----------------------------------------------------------------

 

Depthwise separable Convolution 

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1          [-1, 100, 11, 11]           4,900
            Conv2d-2         [-1, 1000, 11, 11]         100,000
================================================================
Total params: 104,900
Trainable params: 104,900
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.11
Forward/backward pass size (MB): 1.02
Params size (MB): 0.40
Estimated Total Size (MB): 1.53
----------------------------------------------------------------

 

Kernel의 사이즈가 커질수록, 엄청난 파라미터 수의 감소를 보여주며, 곱셈을 덧셈으로 대체하기 때문에 연산이 굉장히 빨라집니다.

 

이러한 특징덕에 의해, Depthwise separable Convolution를 통한 Inception, Xception, mobile net 등 여러 논문에서 많이 등장합니다. 

 

728x90
반응형

+ Recent posts