SlideShare a Scribd company logo
CNN Visualization Technique
KAIST 전산학부 정태영
Implementation Detail
CNN Visualization technique
Implementation Detail
• 가장 결과가 좋은 Grad-CAM과, 그와 같이 쓸 수 있는 Guided
Backpropagation을 pytorch(0.4.0)로 구현하는 법에 대해 알아보자!
• pytorch의 hook 함수와 opencv의 여러가지 유틸 함수를 사용하면 쉽게
구현할 수 있다. pytorch에 익숙치 않은 사람에게 적절한 난이도
Overall
• 위의 이미지에서 시각화에 준 condition(Cat / Dog)에 따라 그에
대응되는 부분만 표시해주는 것을 볼 수 있음
• 이미지에서 heatmap을 계산하는 것이므로 앞에서 나온 Guided
Backpropagation과 결합해 Guided-Grad-CAM으로도 사용 가능
Overall
Overall
• 목표는 앞의 내용과 같이 임의의 주어진 pytorch CNN model에 대해 쉽
게 Grad-CAM을 적용하게 코딩하는 것
• 모델을 학습하는 것이 주된 내용이 아니므로 모델은 torchvision에서 제공
하는 ResNet101 pretrained model을 사용!
Utils
• 제일 중요한 2가지 util 함수
1. 이미지 전처리 함수
2. heatmap 구성 함수
• 이미지 전처리의 경우 주어진 모델의 test image preprocessing을
따르도록 하는 것이 좋음
• heatmap의 경우 opencv의 컬러맵을 활용
Utils
• torchvision의 transform 기능을 이용해서 이미지 전처리
• normaliz의 mean과 std 값은 torchvision에서 제공되는 모델이 사용했
던 hyperparameter 들. 원래는 이미지 픽셀의 평균값을 그때그때 계산해
서 사용하지만 torchvision에서 미리 계산해서 상수 값으로 사용함
Utils
• opencv의 resize와 color map을 사용해서 heatmap 구성
• Windows의 경우 COLORMAP_JET의 색 구성이 우분투와 반대로 되어
있는 경우가 있음. 해당하는 경우에만 52번 라인 사용해서 뒤집어줌
Grad-CAM
• 해야 하는 것
1. 주어진 레이블에 대한 target layer weight의 gradient 계산
2. target layer output과 위의 gradient를 weighted sum
• 1)은 pytorch의 backward_hook을 사용해서 저장 가능
• 2)는 pytorch의 forward_hook을 사용해서 저장 가능
Grad-CAM
• 1)은 pytorch의 backward_hook을 사용해서 저장 가능 => #21
• 2)는 pytorch의 forward_hook을 사용해서 저장 가능 => #22
Grad-CAM
• forward hook의 파라미터는 module, input, output
• module은 해당 layer의 object, input은 해당 레이어에 들어온 입력
텐서, output은 해당 layer가 forward pass한 결과 텐서
Grad-CAM
• backward hook의 파라미터는 module, grad_input, grad_output
• module은 forward hook과 동일, grad_input은 해당 레이어에 들어온
입력의 gradient, grad_output은 forward pass의 결과로 나온 텐서의
gradient. 즉 grad_outpu로 grad_input을 새로 계산함(역전파)
Grad-CAM
• 주의할 점은 backward_hook에선 주어진 args를 변경하면 안 됨.
대신 backward_hook에서 텐서를 반환하면 해당 텐서를 grad_input 대
신 역전파 시켜 줌
Grad-CAM
• 이제 forward pass를 한 뒤 계산된
feature map과 gradient로
weighted sum 한 것을 반환해
heatmap을 만들 수 있음
• 주의할 점은 model의 forward pass를
호출할 때 model을 evaluation mode
로 설정해 줘야 함. 그렇지 않을 경우
batch norm 등에서 문제가 발생함
Guided Backpropagation
• 해야 하는 것
Backpropagation이 진행될 때 ReLU의 경우 해당 위치가 forward pass
의 output에서도 positive고 backward pass의 input에서도 positive
인 경우만 backpropagation을 진행
• 다행히 ReLU이기 때문에 원래 backpropagation일 때도 forward pass
의 outpu이 positive인 경우만 역전파가 진행됨.
• 따라서 backpropagation에선 뒤쪽 layer으로부터 역전파된 gradient
의 값만 참조해서 수정하면 됨
Guided Backpropagation
• 새로운 grad_input을 constraint에 맞게 새로 계산해주는 hook을 등록
Guided Backpropagation
보통 고정된 입력인 이미지에 대해선
gradient 계산을 하지 않지만,
guided backpropagation의 목적
은 이미지에 대한 gradient를 계산하
는 것이므로
image 텐서에 requires_grad 함수
를 호출해 플래그를 켜줘야 함
Result
Result
• 주어진 target class에 맞게 다른 heatmap이 나오는 것을 확인할 수 있음
Result
• 주어진 target class에 맞게 다른 heatmap이 나오는 것을 확인할 수 있음

More Related Content

What's hot

Active contour segmentation
Active contour segmentationActive contour segmentation
Active contour segmentation
Nishant Jain
 
Review Paper on Image Processing Techniques
Review Paper on Image Processing TechniquesReview Paper on Image Processing Techniques
Review Paper on Image Processing Techniques
IJSRD
 
Hyperloop - The future of Transportation
Hyperloop - The future of TransportationHyperloop - The future of Transportation
Hyperloop - The future of Transportation
Shubham Agarwal
 
Transformer based approaches for visual representation learning
Transformer based approaches for visual representation learningTransformer based approaches for visual representation learning
Transformer based approaches for visual representation learning
Ryohei Suzuki
 
Object tracking
Object trackingObject tracking
Object tracking
ahmadamin636
 
Lung Cancer Detection on CT Images by using Image Processing
Lung Cancer Detection on CT Images by using Image ProcessingLung Cancer Detection on CT Images by using Image Processing
Lung Cancer Detection on CT Images by using Image Processing
ijtsrd
 
Solid modeling-Sweep Representation and B-representation
Solid modeling-Sweep Representation and B-representationSolid modeling-Sweep Representation and B-representation
Solid modeling-Sweep Representation and B-representation
Destro Destro
 
Electromagnetisms transportation (hyperloop)
Electromagnetisms transportation (hyperloop)Electromagnetisms transportation (hyperloop)
Electromagnetisms transportation (hyperloop)
Izzah Aqilah
 
Image recognition
Image recognitionImage recognition
Image recognition
Joel Jose
 
십분딥러닝_17_DIM(Deep InfoMax)
십분딥러닝_17_DIM(Deep InfoMax)십분딥러닝_17_DIM(Deep InfoMax)
십분딥러닝_17_DIM(Deep InfoMax)
HyunKyu Jeon
 
Image processing
Image processingImage processing
Image processing
pradnya patil
 
Image proceesing with matlab
Image proceesing with matlabImage proceesing with matlab
Image proceesing with matlabAshutosh Shahi
 
2D Transformation
2D Transformation2D Transformation
2D Transformation
A. S. M. Shafi
 
Lines and curves algorithms
Lines and curves algorithmsLines and curves algorithms
Lines and curves algorithmsMohammad Sadiq
 
Image segmentation
Image segmentationImage segmentation
Image segmentation
Rania H
 
Object Detection Classification, tracking and Counting
Object Detection Classification, tracking and CountingObject Detection Classification, tracking and Counting
Object Detection Classification, tracking and CountingShounak Mitra
 
Image Forgery Detection
Image Forgery DetectionImage Forgery Detection
Image Forgery Detection
nitishkumar883951
 
딥러닝을 이용한 얼굴 인식
딥러닝을 이용한 얼굴 인식딥러닝을 이용한 얼굴 인식
딥러닝을 이용한 얼굴 인식
if kakao
 
Polygons - Computer Graphics - Notes
Polygons - Computer Graphics - NotesPolygons - Computer Graphics - Notes
Polygons - Computer Graphics - Notes
Omprakash Chauhan
 

What's hot (20)

Active contour segmentation
Active contour segmentationActive contour segmentation
Active contour segmentation
 
Review Paper on Image Processing Techniques
Review Paper on Image Processing TechniquesReview Paper on Image Processing Techniques
Review Paper on Image Processing Techniques
 
Hyperloop - The future of Transportation
Hyperloop - The future of TransportationHyperloop - The future of Transportation
Hyperloop - The future of Transportation
 
Transformer based approaches for visual representation learning
Transformer based approaches for visual representation learningTransformer based approaches for visual representation learning
Transformer based approaches for visual representation learning
 
Object tracking
Object trackingObject tracking
Object tracking
 
Lung Cancer Detection on CT Images by using Image Processing
Lung Cancer Detection on CT Images by using Image ProcessingLung Cancer Detection on CT Images by using Image Processing
Lung Cancer Detection on CT Images by using Image Processing
 
Solid modeling-Sweep Representation and B-representation
Solid modeling-Sweep Representation and B-representationSolid modeling-Sweep Representation and B-representation
Solid modeling-Sweep Representation and B-representation
 
Electromagnetisms transportation (hyperloop)
Electromagnetisms transportation (hyperloop)Electromagnetisms transportation (hyperloop)
Electromagnetisms transportation (hyperloop)
 
Curve clipping
Curve clippingCurve clipping
Curve clipping
 
Image recognition
Image recognitionImage recognition
Image recognition
 
십분딥러닝_17_DIM(Deep InfoMax)
십분딥러닝_17_DIM(Deep InfoMax)십분딥러닝_17_DIM(Deep InfoMax)
십분딥러닝_17_DIM(Deep InfoMax)
 
Image processing
Image processingImage processing
Image processing
 
Image proceesing with matlab
Image proceesing with matlabImage proceesing with matlab
Image proceesing with matlab
 
2D Transformation
2D Transformation2D Transformation
2D Transformation
 
Lines and curves algorithms
Lines and curves algorithmsLines and curves algorithms
Lines and curves algorithms
 
Image segmentation
Image segmentationImage segmentation
Image segmentation
 
Object Detection Classification, tracking and Counting
Object Detection Classification, tracking and CountingObject Detection Classification, tracking and Counting
Object Detection Classification, tracking and Counting
 
Image Forgery Detection
Image Forgery DetectionImage Forgery Detection
Image Forgery Detection
 
딥러닝을 이용한 얼굴 인식
딥러닝을 이용한 얼굴 인식딥러닝을 이용한 얼굴 인식
딥러닝을 이용한 얼굴 인식
 
Polygons - Computer Graphics - Notes
Polygons - Computer Graphics - NotesPolygons - Computer Graphics - Notes
Polygons - Computer Graphics - Notes
 

Similar to CNN visualization implementaion

위성관측 데이터 활용 강수량 산출 AI 경진대회 1위 수상작
위성관측 데이터 활용 강수량 산출 AI 경진대회 1위 수상작위성관측 데이터 활용 강수량 산출 AI 경진대회 1위 수상작
위성관측 데이터 활용 강수량 산출 AI 경진대회 1위 수상작
DACON AI 데이콘
 
Facebook prophet
Facebook prophetFacebook prophet
Facebook prophet
Minho Lee
 
U-GAT-IT: Unsupervised Generative Attentional Networks with Adaptive Layer-In...
U-GAT-IT: Unsupervised Generative Attentional Networks with Adaptive Layer-In...U-GAT-IT: Unsupervised Generative Attentional Networks with Adaptive Layer-In...
U-GAT-IT: Unsupervised Generative Attentional Networks with Adaptive Layer-In...
jungminchung
 
Optimizing the graphics_pipeline_
Optimizing the graphics_pipeline_Optimizing the graphics_pipeline_
Optimizing the graphics_pipeline_ozlael ozlael
 
Shaderstudy Motion Blur
Shaderstudy Motion BlurShaderstudy Motion Blur
Shaderstudy Motion Bluryong gyun im
 
딥러닝 논문읽기 efficient netv2 논문리뷰
딥러닝 논문읽기 efficient netv2  논문리뷰딥러닝 논문읽기 efficient netv2  논문리뷰
딥러닝 논문읽기 efficient netv2 논문리뷰
taeseon ryu
 
[스프링 스터디 3일차] @MVC
[스프링 스터디 3일차] @MVC[스프링 스터디 3일차] @MVC
[스프링 스터디 3일차] @MVC
AnselmKim
 
Java performance and trouble shooting
Java performance and trouble shootingJava performance and trouble shooting
Java performance and trouble shooting
Anna Choi
 
위성관측 데이터 활용 강수량 산출 AI 경진대회 3위 수상작
위성관측 데이터 활용 강수량 산출 AI 경진대회 3위 수상작위성관측 데이터 활용 강수량 산출 AI 경진대회 3위 수상작
위성관측 데이터 활용 강수량 산출 AI 경진대회 3위 수상작
DACON AI 데이콘
 
딥러닝(Deep Learing) using DeepDetect
딥러닝(Deep Learing) using DeepDetect딥러닝(Deep Learing) using DeepDetect
딥러닝(Deep Learing) using DeepDetect
Junyi Song
 
20210131deit-210204074124.pdf
20210131deit-210204074124.pdf20210131deit-210204074124.pdf
20210131deit-210204074124.pdf
ssusera9c46c
 
Training data-efficient image transformers & distillation through attention
Training data-efficient image transformers & distillation through attentionTraining data-efficient image transformers & distillation through attention
Training data-efficient image transformers & distillation through attention
taeseon ryu
 
생체 광학 데이터 분석 AI 경진대회 6위 수상작
생체 광학 데이터 분석 AI 경진대회 6위 수상작생체 광학 데이터 분석 AI 경진대회 6위 수상작
생체 광학 데이터 분석 AI 경진대회 6위 수상작
DACON AI 데이콘
 
Rl
RlRl

Similar to CNN visualization implementaion (14)

위성관측 데이터 활용 강수량 산출 AI 경진대회 1위 수상작
위성관측 데이터 활용 강수량 산출 AI 경진대회 1위 수상작위성관측 데이터 활용 강수량 산출 AI 경진대회 1위 수상작
위성관측 데이터 활용 강수량 산출 AI 경진대회 1위 수상작
 
Facebook prophet
Facebook prophetFacebook prophet
Facebook prophet
 
U-GAT-IT: Unsupervised Generative Attentional Networks with Adaptive Layer-In...
U-GAT-IT: Unsupervised Generative Attentional Networks with Adaptive Layer-In...U-GAT-IT: Unsupervised Generative Attentional Networks with Adaptive Layer-In...
U-GAT-IT: Unsupervised Generative Attentional Networks with Adaptive Layer-In...
 
Optimizing the graphics_pipeline_
Optimizing the graphics_pipeline_Optimizing the graphics_pipeline_
Optimizing the graphics_pipeline_
 
Shaderstudy Motion Blur
Shaderstudy Motion BlurShaderstudy Motion Blur
Shaderstudy Motion Blur
 
딥러닝 논문읽기 efficient netv2 논문리뷰
딥러닝 논문읽기 efficient netv2  논문리뷰딥러닝 논문읽기 efficient netv2  논문리뷰
딥러닝 논문읽기 efficient netv2 논문리뷰
 
[스프링 스터디 3일차] @MVC
[스프링 스터디 3일차] @MVC[스프링 스터디 3일차] @MVC
[스프링 스터디 3일차] @MVC
 
Java performance and trouble shooting
Java performance and trouble shootingJava performance and trouble shooting
Java performance and trouble shooting
 
위성관측 데이터 활용 강수량 산출 AI 경진대회 3위 수상작
위성관측 데이터 활용 강수량 산출 AI 경진대회 3위 수상작위성관측 데이터 활용 강수량 산출 AI 경진대회 3위 수상작
위성관측 데이터 활용 강수량 산출 AI 경진대회 3위 수상작
 
딥러닝(Deep Learing) using DeepDetect
딥러닝(Deep Learing) using DeepDetect딥러닝(Deep Learing) using DeepDetect
딥러닝(Deep Learing) using DeepDetect
 
20210131deit-210204074124.pdf
20210131deit-210204074124.pdf20210131deit-210204074124.pdf
20210131deit-210204074124.pdf
 
Training data-efficient image transformers & distillation through attention
Training data-efficient image transformers & distillation through attentionTraining data-efficient image transformers & distillation through attention
Training data-efficient image transformers & distillation through attention
 
생체 광학 데이터 분석 AI 경진대회 6위 수상작
생체 광학 데이터 분석 AI 경진대회 6위 수상작생체 광학 데이터 분석 AI 경진대회 6위 수상작
생체 광학 데이터 분석 AI 경진대회 6위 수상작
 
Rl
RlRl
Rl
 

CNN visualization implementaion

  • 1. CNN Visualization Technique KAIST 전산학부 정태영 Implementation Detail
  • 2. CNN Visualization technique Implementation Detail • 가장 결과가 좋은 Grad-CAM과, 그와 같이 쓸 수 있는 Guided Backpropagation을 pytorch(0.4.0)로 구현하는 법에 대해 알아보자! • pytorch의 hook 함수와 opencv의 여러가지 유틸 함수를 사용하면 쉽게 구현할 수 있다. pytorch에 익숙치 않은 사람에게 적절한 난이도
  • 3. Overall • 위의 이미지에서 시각화에 준 condition(Cat / Dog)에 따라 그에 대응되는 부분만 표시해주는 것을 볼 수 있음 • 이미지에서 heatmap을 계산하는 것이므로 앞에서 나온 Guided Backpropagation과 결합해 Guided-Grad-CAM으로도 사용 가능
  • 5. Overall • 목표는 앞의 내용과 같이 임의의 주어진 pytorch CNN model에 대해 쉽 게 Grad-CAM을 적용하게 코딩하는 것 • 모델을 학습하는 것이 주된 내용이 아니므로 모델은 torchvision에서 제공 하는 ResNet101 pretrained model을 사용!
  • 6. Utils • 제일 중요한 2가지 util 함수 1. 이미지 전처리 함수 2. heatmap 구성 함수 • 이미지 전처리의 경우 주어진 모델의 test image preprocessing을 따르도록 하는 것이 좋음 • heatmap의 경우 opencv의 컬러맵을 활용
  • 7. Utils • torchvision의 transform 기능을 이용해서 이미지 전처리 • normaliz의 mean과 std 값은 torchvision에서 제공되는 모델이 사용했 던 hyperparameter 들. 원래는 이미지 픽셀의 평균값을 그때그때 계산해 서 사용하지만 torchvision에서 미리 계산해서 상수 값으로 사용함
  • 8. Utils • opencv의 resize와 color map을 사용해서 heatmap 구성 • Windows의 경우 COLORMAP_JET의 색 구성이 우분투와 반대로 되어 있는 경우가 있음. 해당하는 경우에만 52번 라인 사용해서 뒤집어줌
  • 9. Grad-CAM • 해야 하는 것 1. 주어진 레이블에 대한 target layer weight의 gradient 계산 2. target layer output과 위의 gradient를 weighted sum • 1)은 pytorch의 backward_hook을 사용해서 저장 가능 • 2)는 pytorch의 forward_hook을 사용해서 저장 가능
  • 10. Grad-CAM • 1)은 pytorch의 backward_hook을 사용해서 저장 가능 => #21 • 2)는 pytorch의 forward_hook을 사용해서 저장 가능 => #22
  • 11. Grad-CAM • forward hook의 파라미터는 module, input, output • module은 해당 layer의 object, input은 해당 레이어에 들어온 입력 텐서, output은 해당 layer가 forward pass한 결과 텐서
  • 12. Grad-CAM • backward hook의 파라미터는 module, grad_input, grad_output • module은 forward hook과 동일, grad_input은 해당 레이어에 들어온 입력의 gradient, grad_output은 forward pass의 결과로 나온 텐서의 gradient. 즉 grad_outpu로 grad_input을 새로 계산함(역전파)
  • 13. Grad-CAM • 주의할 점은 backward_hook에선 주어진 args를 변경하면 안 됨. 대신 backward_hook에서 텐서를 반환하면 해당 텐서를 grad_input 대 신 역전파 시켜 줌
  • 14. Grad-CAM • 이제 forward pass를 한 뒤 계산된 feature map과 gradient로 weighted sum 한 것을 반환해 heatmap을 만들 수 있음 • 주의할 점은 model의 forward pass를 호출할 때 model을 evaluation mode 로 설정해 줘야 함. 그렇지 않을 경우 batch norm 등에서 문제가 발생함
  • 15. Guided Backpropagation • 해야 하는 것 Backpropagation이 진행될 때 ReLU의 경우 해당 위치가 forward pass 의 output에서도 positive고 backward pass의 input에서도 positive 인 경우만 backpropagation을 진행 • 다행히 ReLU이기 때문에 원래 backpropagation일 때도 forward pass 의 outpu이 positive인 경우만 역전파가 진행됨. • 따라서 backpropagation에선 뒤쪽 layer으로부터 역전파된 gradient 의 값만 참조해서 수정하면 됨
  • 16. Guided Backpropagation • 새로운 grad_input을 constraint에 맞게 새로 계산해주는 hook을 등록
  • 17. Guided Backpropagation 보통 고정된 입력인 이미지에 대해선 gradient 계산을 하지 않지만, guided backpropagation의 목적 은 이미지에 대한 gradient를 계산하 는 것이므로 image 텐서에 requires_grad 함수 를 호출해 플래그를 켜줘야 함
  • 19. Result • 주어진 target class에 맞게 다른 heatmap이 나오는 것을 확인할 수 있음
  • 20. Result • 주어진 target class에 맞게 다른 heatmap이 나오는 것을 확인할 수 있음