728x90

https://www.inference.vc/untitled/

 

ML beyond Curve Fitting: An Intro to Causal Inference and do-Calculus

Since writing this post back in 2018, I have extended this to a 4-part series on causal inference: ➡️️ Part 1: Intro to causal inference and do-calculus Part 2: Illustrating Interventions with a Toy Example Part 3: Counterfactuals Part 4: Causal Diag

www.inference.vc

 

causal inference에 대해 접한 적 있는가..? 아마 Bayesian network를 공부하면서 한번쯤을 보았을 것이다. (화살표로 인과관계 설명..) 그러나 요즘에 핫한 deep learning에서는 주로 causal inference를 사용하지 않기 때문에 접할일이 별로 없고 이것이 왜 중요하고 어떻게 사용되는지 접할일이 별로 없다. 그러나 causal inference는 deep learning을 보완하기 때문에 한번 공부해보자고 글쓴이가 말한다.. (Don't get discouraged by causal diagrams looking a lot like Bayesian networks not a coincidence seeing they were both pioneered by Pearl) they don't compete with, they complement deep learning.)

 

 

 

Basics

 

일단 causal calculus에서는 두가지의 conditional distributions을 구분한다. ML에서는 보통 둘중 하나만을 estimate하지만 둘다 하는 경우도 있다. 

 

1) observational p( y | x ) : 일반적으로 supervised ML에서 estimate하는 값이다.

(What is the distribution of Y given that I observe variable X takes value x.)

 

2) interventional p( y | do(x) ) : 위와 같은 경우는 data를 '측정' (observed) 했을 때, p(y|x)를 구하는 방법이라면, 

이 방법의 경우, 데이터를 분석하는 사람이 데이터를 직접적으로 setting해서 지정했을때 Y의 distribution을 의미한다.(What is the distribution of Y if I were to set the value of X to x.) ( intervene 한다고 표현 : if I intervened in the data generating process by artificially forcing the variable XX to take value xx, but otherwise simulating the rest of the variables according to the original process that generated the data.)

 

 

Aren't they the same thing?

 

위의 두 conditional distribution은 다르다.

observational p( y | x )는 기존과 같이 x를 observe하고 그에 맞는 y를 예측하기 때문에 p(y|x)라고 표현이 된다.

그러나 interventional p( y | do(x) ) 의 경우 x의 값이 intervene된 경우이기 때문에 실제로 x와 y가 관련이 있다고 볼 수 없고 p(y|x)라고 보기 보다는 오히여 p(y)로 보는 것이 맞다고 할 수 있다.

 

 

Which one do I want?

 

둘 중에 어떤 것을 사용할지는 어떤 문제를 푸느냐에 따라 다르다. x가 자연적으로 발생하는 상황에서 y를 측정하는 task라면 observational p( y | x )를 사용하는 것이 적합하고 이것은 이미 supervised learning에서 사용하고 있다.

(this is what Judea Pearl called curve fitting. This is all good for a range of important applications such as classification, image segmentation, super-resolution, voice transcription, machine translation, and many more.)

 

그러나 x를 우리가 선택하는 경우는 p(y|do(x)) 를 사용해야 된다. 예를들어서 의료분야에서는 특정 치료법을 적용했을때  결과 (y)를 알고 싶을 때가 있다. 이때, x는 자연적으로 발생한 것이 아니라 인위적으로 설정한 x이고 (proactively choose , intervene) 이때는 p(y|do(x))를 사용한다.

 

 

 

What exactly is p(y|do(x))

 

p(y|do(x))는 측정하려면 실험자가 x를 control하며 수행하는 randomized controlled trials or A/B tests로 부터 data를 collect해야 된다. 그러나 실제로 이러한 수행자체가 어려운 경우가 많다. (의료 관련 실험의 경우 여러가지 제약이 있다.)

때문에 직접적으로 p(y|do(x))를 측정하기 어려운 것을 간접적으로 계산하는 것이 'causal inference and do-calculus'이다.

 

 

 

How are all these things related?

 

 

일단 p(y|x)에 맞춰서 그린 diagram을 살펴보자. observable joint라고 적힌 그림에 있는 동그라미 3개가 바로 변수를 의미한다. (x, z, y)그리고 파란색의 작은 사각형이 이 3개의 변수의 joint distribution을 의미한다.이때 x값으로 부터 y를 측정하기를 원하는 것이고, z는 측정은 가능하지만 현재 task에서는 관심없는 변수를 의미한다.이는 우리가 평소에 하던 deep learning network를 이용해서 cross entropy loss를 사용하면 학습이 가능하다.

 

그러면 p(y|do(x))를 구하면 싶으면 어떻게 해야 될까?

 

 

원래라면 오른쪽 그림처럼 intervention joint distributuion에서 sampling을 진행하여, 모델을 학습시키면 된다. 그러나 앞서 이야기 한 것처럼 직접적으로 intervention joint distribution에서 sampling하는것은 어렵거나 불가능할 수 있고, 때문에 observable joint distribution으로 부터 sampling하여 p(y|do(x))를 계산하여야 한다.

 

 

Causal models

 

위와 같이 obervalble joint distribution에서 sampling한 data로 p(y|do(x))를 계산하려면, data간의 'causal structure'를 알고 있어야 한다. 이러한 data간의 causal 관계를 표현하면 아래 그림처럼 된다.

이렇게 causal 관계를 표현한식에서 intervention을 수행하는 것에 따라 우리는 기존의 causal model에서 mutilated를 수행할 수 있다. ( 기존 causal 관계도에서 화살표를 제거함) 이렇게 mutilated를 수행하여 우리가 원하는 x의 p(y|do(x)) 구하는 형태로 변형이 가능하다. (예시가 없어서 정확히는 이해 못했음) 이러한 과정을 거쳐서 원래의 intervention joint distribution을 근사한 emulated intervention joint distribution을 구할 수 있고, 따라서 p(y|do(x)) 또한 간접적으로 구할 수 있게 된다.

 

Do-calculus

 

이러한 과정에서 'Do-calculus'라는 것을 사용해서 수학적으로 표현할수 있다고 한다 (정확히 이해못함)

 

 

 

Summary

 

I wanted to emphasize again that this is not a question of whether you work on deep learning or causal inference. You can, and in many cases you should, do both. Causal inference and do-calculus allows you to understand a problem and establish what needs to be estimated from data based on your assumptions captured in a causal diagram. But once you've done that, you still need powerful tools to actually estimate that thing from data. Here, you can still use deep learning, SGD, variational bounds, etc. It is this cross-section of deep learning applied to causal inference which the recent article with Pearl claimed was under-explored.

 

 

 

 

 

 

 

728x90

'Math > Causal Inference' 카테고리의 다른 글

Part 3: Counterfactuals  (0) 2021.07.21
Part 2: Illustrating Interventions with a Toy Example  (0) 2021.07.16
728x90

Paper

https://arxiv.org/abs/2103.00887

 

Counterfactual Zero-Shot and Open-Set Visual Recognition

We present a novel counterfactual framework for both Zero-Shot Learning (ZSL) and Open-Set Recognition (OSR), whose common challenge is generalizing to the unseen-classes by only training on the seen-classes. Our idea stems from the observation that the ge

arxiv.org

 

Code

https://github.com/yue-zhongqi/gcm-cf

 

yue-zhongqi/gcm-cf

[CVPR 2021] Released code for Counterfactual Zero-Shot and Open-Set Visual Recognition - yue-zhongqi/gcm-cf

github.com

 

Abstract

본 논문에서는 Zero-Shot Learning과 Open-Set Recongniton에 대해 새로운 framework를 제안하였다. (counterfactual framework)  이 2가지 문제는 모두 training때 보지 못한 unseen data에 대해서 모델이 generalized (seen data, unseen data 모두 잘하는) 능력을 갖추는 것이 핵심인 문제이다.

 

2가지 문제 모두다 unseen data를 다루는 문제이기 때문에 unseen data를 생성하는 방법을 많이 사용한다.

그러나 기존의 방법들은 unseen data가 실제 unseen data의 distribution과 다른 distribution이 생성된다는 문제점이 있었다. 

 

이러한 이유를 본 논문에서는 생성된 샘플이 'Not Counterfactual Faithful'하기 때문이라고 설명하고 있다.

때문에 본 논문에서는 Counterfactual Faithful한 sample을 생성하여 원래 unseen data의 distributuion과 동일함 distribution을 샘플을 생성하는 것을 시도한다.

 

 Counterfactual faithful한 것의 의미는 다음과 같다.

"만약 특정 sample의 attribute는 유지한채 class에 대한 attribute만 변화하면 어떠한 sample이 만들어지는가?"

(완전히 무의미한 sample이 아닌 실제 존재하는 attribute 및 feature를 유지한채 sample을 생성한다는 의미인듯)

 

 이러한 방법으로 faithfulness를 확보하면 'Consistency Rule'를 unseen/seen binary classification에 적용할 수 있다.

예를 들면 다음과 같이 수행가능하다. 생성된 counterfactual sample이 특정 class에서 나온것이냐? 라는 물음에 binary classsification 형태로 yes or no를 도출가능하다.

 

 

Introduction

 

기존의 ZSL (Zero-Shot Learning) 이나 OSR (Open-Set Recongniton) 방법들은 기존 training dataset의 sample들을 이용해서 unseen dataset에 대한 sample을 생성하고 이를 이용해서 test time때 unseen class를 구분하는 알고리즘을 주로 사용했다. 그러나 이와 같은 방법은 생성된 unseen class에 대한 sample들이 실제 unseen class의 sample들과 다른 distribution을 가진다는 문제점이 존재한다. 아래 그림 (a)를 보자.

 

그림을 보면 생성된 unseen class와 True unseen class sample에 대한 차이가 존재하기 때문에 decision boundary가 불균형하게 형성되고 따라서 test때 true unseen class sample을 잘구분하지 못하는 것을 확인할 수 있다. 저자는 이러한 현상이 모든 ZSL 알고리즘에서 나타났다고 말한다. (Seen class에 대한 recall 값이 높음) 

 

(이와 같은 일이  openset 에서도 맞는 말인지는 생각해 봐야 한다. OOD 논문에서 GAN으로 생성한 sample을 openset으로 활용하는 경우 생성된 sample이 True seen class sample에 True unseen class sample보다 더 가까워야 되는 것이 아닌가 생각해본다.)

 

이러한 문제는 사실 feature의 disentanglement문제와 관련이 있다고 저자는 말한다. 만약 feature을 disentangle할 수 있다면, 생성하는 unseen class data를 more sensible하게 생성할 수 있을거라고 이야기한다. 그러나, feature를 disentanglement하는 일을 어려운 일이며, 적절한 supervision이 필요한 일이다. 

 

때문에 저자는 feature를 disentanglement하는 방법 대신 다른 방법을 제안하는데, 바로 Counterfactual Inference를 제안한다. (https://badlec.tistory.com/262?category=1035281)

 

X를 sample을 나타내는 Random variable, 이 sample을  encoding한 결과를  Z = z(X=x), (feature, attribute) , 그리고 class정보를 vector로 나타낸 것을 Y = y(X=x)라고 하면 sample x에 대한 counterfactual sample x_var는 다음과 같다.

 

만약 feature가  Z = z ( X = x ) 일때, Y가 특정 y Class라고 가정을 하면, X는 x_var가 될것이다. 

 

즉, 어떤 feature가 있을 때,  class에 대한 정보, vector만 바꾸어 주면 어떤 sample이 생성되는지 보고,

그 생성된 sample을 counterfactual이라고 본다.

 

이렇게 생성하는 경우 기존의 방법과 다른 점이 있다.

바로 기존 방법의 경우, sample-agnostic ( 부자연스러운 sample을 생성) 한다는 것이고, (gaussian noise z 기반으로 생성하기 때문.. 이라고 논문에서는 설명) 저자의 방법은 sample-specific한 방법이라고 설명하고 있다. ( sample을 feature, z(x)를 기반으로 생성하기 때문임.)

 

저자는 이러한 방식의 정당성을 부여하기 위해서 아무것도 없는 상태에서 unseen class sample을 생성하는 것보다, 특정 attribute, observed fact Z=z(x)를 기반으로 생성하는 것이 생성할 때, 잃어버리는(lost) feature, attribute없이 생성이 가능하다고 설명하고 있다. (마치 인간이 화석으로 부터 공룡의 모습을 상상하는 것 처럼..)

 

그리고 class attrribute Y와 class sample Z를 disentangle함으로 Counterfactual Faithfulness를 만족할 수 있다고 한다. 그리고 이를 만족하면 위 그림에서 (c) 부분과 같이 True sample unseen class와 유사한 distribution을 가지는 unseen class sample을 생성할 수 있다고 한다.

 

 

위와 같은 논리로 본 논문에서 제안한 counterfactual framework는 위와 같다. X sample이 input으로 들어오면 feature Z(Sample attribute)를 추출하고,  Class Attribute Y와 concat을 한다. (정보를 더해줌) 이렇게 만들어진 최종 feature, attribute를 이용해서 sample을 생성한다. 이때 생성된 sample과 원래 sample X와 비교하는 과정을 거치게 된다. (Consistency Rule 적용)  이때 원래 Sample과 유사하면, 기존에 봤던 Class라고 판단하고, 다르면 처음보는 Class라고 판단한다. (Yes, No 부분)

 

 

 

Method

 

논문에서 어찌되었던 Counterfactual 논리를 사용하고 있기 때문에, 자신들의 Causal Model을 소개하고 있다. 논문에서는 Generative Causal model이라고 소개하고 있으며, 다음과 같이 도식화해서 표현한다.

 

도식에 대한 자세한 설명은 논문을 참고하면 된다. 그러나 크게 중요하다고는 생각안한다.

openset recognition에 대한 알고리즘만 좀 더 살펴보겠다.

 

 

기존의 method는 다음과 같은 알고리즘에 따라 openset을 구분하였다.

1. 먼저 test sample x가 input으로 들어오면 모델의 파라메터를 기반으로 test sample에 대한 class를 예측하게 한다.

2. 이 class정보를 이용해서 Pθ(X|Z = z, Y = y)로 부터 sample x'을 생성한다.

3. 이렇게 생성한 x'이 원래 sample x와 유사하면 known, 안유사하면 unknown처리한다.

 

그러나 이러한 method의 경우  z가 보통 gaussian noise가 사용되고, 즉 , sample-specific한  sample이 생성되지 않는다.

이러한 경우 condition으로 주어지는 y가 entangle되어 있기 때문에 (여러 sample들의 정보를 함께 담고 있음)

실제로 생성되는 이미지도 sample들의 feature가 entangle(여러 sample, instance 정보들이 섞어있음)되어 생성되게 되고, 이는 실제의 class sample distribution과 다른 분포를 낳는 결과를 도출한다.

 

이와 다르게 본 논문에서는 Counterfactual sample을 생성하며 다음과 같은 과정을 거친다

 

1. feature extraction

먼저 “given the fact that Z = z(x)” 를 구하기 위해서 x sample에 대한 attribute z를 추출한다.

이는 다음과 같이 표현할 수 있다. z(x) ∼ Qφ(Z|X = x)

 

2. apply intervention target y

그 다음 “had Y been y”를 구한다. 기존 방법의 경우 classification model에 x sample을 넣고 예측하는 class y를 

사용했지만, 본 논문에서는 intervention target Y=y를 사용한다. (특정 class를 임의로 지정해줌)

 

3. Prediction

마지막으로 -“X would be x˜” 를 구한다. 방법은 x를 encoding한 Z , (Z = z(x) (fact))와 intervention target Y ( Y = y (counterfact) ) 로부터 sample x˜를 생성한다.   ( Pθ(X|Z = z(x), Y = y) )

이렇게 만드는 경우, 기존 방법은 클래스 정보만 있는 상황에서 noize기반으로 생성하였기 때문에 sample간의 feature가 entangle되어있는 sample이 생성되었다면, 이 경우, 특정 sample을 encoding한 정보를 함께 주는 상황에서 생성하기 때문에, 해당 class정보에서 해당 sample에 해당되는 feature만 disentangle하여 sample을 생성한다는 장점이 있다.

 

 

이렇게 생성한 sample이 우리는 true unseen class distribution에 속하길 바라는 것이다. 

그래서 기존 방법과 비교한 그림이 다음과 같다.

 

 

 

 

Inference in OSR

 

OSR에서는 다음과 같이 위의 방법을 활용한다. Counterfactual sample을 기존 y에 대해서 (intervention y) 생성하고,

이때, unknown sample과 distance를 계산해 일정 threshold보다 넘으면 openset으로 분류한다.

 

이때 자세한 과정은 다음과 같다.

test sample x 와 counterfactual samples x~간의 Euclidean distance를 모두 계산한 다음, 그 중에서 가장 작은 distance를 기준값으로 활용한다. 이때 d_min이 특정 threshold를 넘으면 unseen으로 분류한다.

 

 

 

 

Counterfactual-Faithful Training

 

위의 method는 모두 counterfactual-faithful 조건이 만족되야 한다는 것이 중요하다.

그리고 counterfactual-faithful은 다음 조건이 만족되면, 성립하게 된다.

 

Theorem. The counterfactual generation Xy[z(x)] is faithful if and only if the sample attribute Z and class attribute Y are group disentangled.

(sample attribute Z와 class attribute Y가 disentangle이 되는 경우, couterfactual generation은 faithful하다고 말할 수 있다.)

(증명은 아래 논문 Appendix에 있다,  )

https://arxiv.org/abs/1812.03253

 

Counterfactuals uncover the modular structure of deep generative models

Deep generative models can emulate the perceptual properties of complex image datasets, providing a latent representation of the data. However, manipulating such representation to perform meaningful and controllable transformations in the data space remain

arxiv.org

 

 

다음 그림은 이러한 disentanglement가 잘 되었을 때와 안되었을 때를 구분하여 나타낸 그림이다.

 

 

이러한 disentanglement는 fully하게 하는 것은 불가능에 가깝다.

https://arxiv.org/abs/1811.12359

 

Challenging Common Assumptions in the Unsupervised Learning of Disentangled Representations

The key idea behind the unsupervised learning of disentangled representations is that real-world data is generated by a few explanatory factors of variation which can be recovered by unsupervised learning algorithms. In this paper, we provide a sober look

arxiv.org

 

그래서 appoximation하여 disentanglement를 시도하게 되는데, 다음과 같은 objective를 활용하게 된다.

 

 

모든 Loss는 disentanglement를 위함이다.

 

 

 

1) L_z : Disentangling Z from Y

- B-VAE Loss (L_z)를 일단 minimize한다.

 

- disentanglement 분야를 잘몰라서 정확히는 모르겠지만 B값을 조정하여 Z를 Y distribution에 영향을 받지 않도록 objectieve를 줄 수 있다고 한다. (논문 참고)

 

 

 

2) L_y : Disentangling Y from Z

 

위의 Loss만으로는 disentangle이 충분하지 않다고 하고, L_y Loss를 추가한다. 이유는 논문에서는 최근 over-parameterized model의 경우 Y없이 noise Z 만으로 sample을 생성하는 경우가 있고, 이는 생성된 sample이 non-faithful한 것으로 leadinig이 가능하다고 한다. 어찌되었든 disentangle term을 더 넣어야 된다.

 

사용하는 term은 다음과 같이 contrastive loss term을 적용한다. 

원래 sample x와 그 sample을 encoding한 후 원래 class를 기반으로 그대로 생성한 sample x_y간의 거리는 가깝게 한다.

그러나 원래 sample x와 다른 class를 intervention하여 생성한 x'과의 거리를 멀게 만든다.

 

 

이때 사용하는 dist는 Euclidean distance이다.

 

이는 똑같은 encoding Z로 부터 class Y에 대해서 intervene되기 전과 후의 차이를 크게 만드는 것이기 때문에 disentanglement에 더욱 도움을 주게 된다.

 

 

 

3) L_F : Further Disentangling by Faithfulness

잘모르겠지만.. VAE의 lower bound를 더 loose하게 하면 더욱 faithfulness를 증가할 수 있다고 한다.

그리고 이를 위해 WGAN을 사용한다. discriminator를 사용해서 원본 x에 대해서는 1에 가까운 값,

생성된 x'에는 0에 가까운 값을 출력하도록 한다.

 

 

 

Experiments

 

[Implementation detail]

OSR에서 사용된 네트워크는 CGDL에서 사용된 네트워크를 본 논문에서도 사용하였다. (Ladder-VAE)

X는 실제 이미지가 사용된다. openset을 구분하는 방법은 reconstuction error가 사용된다.

 

result는 F1-score로 측정이 되었다.

CGDL밖에 비교를 안했는데, 자신의 disentanglement 기법이 효과가 있음을 알려주는데, 힘을 쏟았다고 생각한다.

 

또한 Openness가 커져도 본 논문의 method인 GCM-CF는 강건함을 볼 수 있다.

 

 

Summary

- 본 논문은 기존의 ZSL과 OSR 방법에서 주로 사용하는 unseen class에 대한 생성 방법론에 대해 문제점을 제기하고, developed된 unseen class sample을 생성하는 방법을 제시한 논문이다. 기존의 gan 기반 unseen class 생성 방법은 sample간의 feature (attribute) entanglement 현상이 있어 실제로 생성했을 때, true unseen class distribution과 다른 것을 확인할 수 있었다. (seen class에 대한 recall 값이 높은 것으로 간접적으로 증명) 이때, true unseen class distribution에 맞는 sample을 생성하기 위해서 counterfatual faithfulness라는 개념을 가지고 온다. 이는 ICLR 2020 논문에서 수학적으로 증명한 내용인데, 만약 sample을 생성할 때, 생성할 때, 기반이 되는 정보인 Z( feature, attribute), 와 Y (class)가 disentanglement된 다음 제공되면 생성되는 sample이 counterfactual faithfulness, 즉 true unseen class distribution과 유사하다는 것이 보장된다는 것이다. 

 

그래서 이를 기반으로 unseen class sample을 생성하게 되고, 이러한 방법은 기존의 unseen class sample을 생성하는 것 보다 더 정확하게 생성이 가능하기 때문에, 더 좋은 성능을 보였다는 내용의 논문이다.

 

 

Pros

 

문제제기가 잘된 논문이라고 생각한다. 기존 생성모델 기반으로 OSR 문제를 푸는 방식에서 부족한 부분을 잘지적했다고 생각한다. 생성모델의 disentanglement 문제에 대해 잘이해했기 때문에 쓸 수 있는 논문이라고 생각한다. 

 

 

Cons

 

다른 OSR 논문들과의 비교가 부족하다고 생각한다. split도 다른 듯 하다. 하지만 논문자체가 OSR이 중심이 아니라 기존의 생성 방법에서 문제점이 있다는 것을 잘지적하고 그에 대해 해결법을 잘제시한 논문이라 다른 method와의 비교가 부족하지만 논문이 되었다고 생각한다.

 

 

 

 

728x90
728x90

Paper

https://arxiv.org/abs/1711.09325

 

Training Confidence-calibrated Classifiers for Detecting Out-of-Distribution Samples

The problem of detecting whether a test sample is from in-distribution (i.e., training distribution by a classifier) or out-of-distribution sufficiently different from it arises in many real-world machine learning applications. However, the state-of-art de

arxiv.org

 

Code

https://github.com/alinlab/Confident_classifier

 

alinlab/Confident_classifier

Training Confidence-Calibrated Classifier for Detecting Out-of-Distribution Samples / ICLR 2018 - alinlab/Confident_classifier

github.com

 

 

728x90
728x90

Paper

https://openaccess.thecvf.com/content_ECCV_2018/papers/Lawrence_Neal_Open_Set_Learning_ECCV_2018_paper.pdf

 

Code

https://github.com/lwneal/counterfactual-open-set

 

lwneal/counterfactual-open-set

Counterfactual Image Generation. Contribute to lwneal/counterfactual-open-set development by creating an account on GitHub.

github.com

 

 

Open Set Learning with Counterfactual Images는 openset example을 생성해 학습에 이용하여 Openset을 걸러내는 아이디어를 사용한 논문 중 하나이다.

 

high-level로 아이디어를 설명하면 기존 Know class sample을 이용해서 known samplerhk 유사하지만 known sample은 아닌 openset example을 생성하여 이를 openset recognition에 활용한다.

 

 

G-openmax와 다른 점은 Vanila GAN을 이용해서 openset example을 생성한 것이 아니라 encoder-decoder 형태의 GAN을 사용했다는 것이다.

 

 

본 논문에서 사용하는 Generative model은 다음과 같이 Loss function이 구성된다.

 

 

L_D 에서 D(G(E(x))) 는 생성된 image가 discriminator에 들어갔을 때 loss값을 의미한다. 그리고 D(x)는 real image가 discriminator안에 들어갔을때 loss값을 의미한다. 

 

수식은 잘 이해가 안되서 code를 살펴보았고, 다음과 같이 optimization이 진행된다.

 

 

 

1. discriminator update

-먼저 discriminator를 update한다. 

 

1) Classifiy sampled images as fake

noise = make_noise(batch_size, latent_size, sample_scale)
fake_images = netG(noise, sample_scale)

logits = netD(fake_images)[:,0]
loss_fake_sampled = F.softplus(logits).mean()

 

2) Classify real exampleds as real

logits = netD(images)[:,0]
loss_real = F.softplus(-logits).mean() * options['discriminator_weight']

 

3) calculate P(D)

gp = calc_gradient_penalty(netD, images.data, fake_images.data)

(29. Gulrajani, I., Ahmed, F., Arjovsky, M., Dumoulin, V., Courville, A.: Improved training of wasserstein gans. arXiv preprint arXiv:1704.00028 (2017))

 

 

 

2. Generator Update

- 그 다음 generator를 update한다.

 

# Minimize fakeness of autoencoded images
fake_images = netG(netE(images, ac_scale), ac_scale)
logits = netD(fake_images)[:,0]

errG = -logits.mean() * options['generator_weight']

 

 

 

3. Autoencoder update

- reconstruction loss를 통해 auto encoder 및  generator를 update

netG.zero_grad()
netE.zero_grad()

 

reconstructed = netG(netE(images, ac_scale), ac_scale)
err_reconstruction = torch.mean(torch.abs(images - reconstructed)) * options['reconstruction_weight']
err_reconstruction.backward()

 

 

 

4. Classifier update

 

netC.zero_grad()

# Classify real examples into the correct K classes with hinge loss
classifier_logits = netC(images)
errC = F.softplus(classifier_logits * -labels).mean()
errC.backward()
log.collect('Classifier Loss', errC)

optimizerC.step()

 

 

논문에서는 실제 이미지와 유사한 openset example을 생성하는 것이 목적이기 때문에 다음과 같이 latent vector를

optimization한다.

이때, z* 를 만들때, openset example은 confidence가 낮다고 가정한다. 그래서 다음과 같이 objective를 설정한다.

이때 second term은 기존의 classifier logit에 unknown class logit을 추가하고, unknown class에 대한 score (logit)값을 0으로 잡은 term이다. 

 

unknown class logit은 0으로 정의했기 때문에 사실상 아래의 첫 항처럼 표현 되서 1이 되는 것이고, 뒷 부분은 known class의 logit값들이다. 이때, 이 term을 minimize하면 known class에 대한 logit이 작아지고, 본 논문에서 정의한 것과 같이 confidence가 낮은 sample, 즉 open example이 생성된다.

 

이때 생성하는 과정은 다음과 같다.

1. 먼저 trainigset에서 random하게 하나의 image를 sample하여 encoder에 넣는다. ( z = E(x) )

2. 위의 optimization식을 이용해 z*를 만들어낸다.

3. 만들어낸 z*를 이용해 counter factual image를 생성한다. ( G(z*) )

4. 생성된 G(z*) image들을 이용해 K+1 class로 label하여 학습시킨다.  

 

 

코드는 아래와 같다.

 

for i in range(max_iters):
z = to_torch(z_value, requires_grad=True)
z_0 = to_torch(z0_value)
logits = netC(netG(z, gan_scale))
augmented_logits = F.pad(logits, pad=(0,1))

cf_loss = F.nll_loss(F.log_softmax(augmented_logits, dim=1), target_label)

distance_loss = torch.sum(
(
z.mean(dim=-1).mean(dim=-1)
-
z_0.mean(dim=-1).mean(dim=-1)
) ** 2
) * distance_weight

total_loss = cf_loss + distance_loss

scores = F.softmax(augmented_logits, dim=1)

log.collect('Counterfactual loss', cf_loss)
log.collect('Distance Loss', distance_loss)
log.collect('Classification as {}'.format(target_class), scores[0][target_class])
log.print_every(n_sec=1)

dc_dz = autograd.grad(total_loss, z, total_loss)[0]
z = z - dc_dz * speed
z = clamp_to_unit_sphere(z, gan_scale)

# TODO: Workaround for Pytorch memory leak
# Convert back to numpy and destroy the computational graph
# See https://github.com/pytorch/pytorch/issues/4661
z_value = to_np(z)
del z
print(log)
z = to_torch(z_value)

 

 

-Technical Details of Compared Approaches

 

위의 과정을 자세히 설명하면 다음과 같다.

먼저 training set을 이용해 encoder, generator, discriminator를 학슶기킨다.

 

그 이후 학습된 모델들을 이용해서 openset example을 생성한다.

본 논문에서는 6400장의 exemple image를 생성한다.

 

이 image들을 통해서 K+1 classifier를 학습시키고,

이때 기존에 학습시켰던 K-classifier의 weight를 initial값으로 활용한다.

 

그리고 Openset metric은 다음과 같이 사용한다.

 

 

위 식의 의미는 다음과 같다.

open class로 정해진 확률 - closed class에 정해진 확률에서 가장 큰 값

 

이렇게 하면 closed class에 큰 값으로 확률이 mapping된 sample의 경우,

그 class에 속할 확률이 높기 때문에 Openset이라는 확률을 줄여주는 방식이다.

 

 

Results

 

- Opinion

 

Pros

기존의 G-openmax의 경우 DC-GAN을 이용해서 open example을 생성하지만,

본 논문 같은 경우에는 closed set과 유사한 sample을 생성하기 위해 추가적인 optimizaiton식을 사용하는 것이 특징이다.

또한 classifier에 open class를 추가하여 활용하기 때문에 좀 더 좋은 부분이 있다고 생각하긴 한다.

 

그러나 가장 최신 논문인 placeholder처럼 classifier를 embedding space의 중앙에 위치한다거나 하는 skill이 없기 때문에

성능은 높지 않다고 생각되어진다.

 

Cons

Open example을 생성할 때 결국 classifier의 confidence 값을 활용하는데, classifier의 현재 featrure extracting하는 능력을 기반으로 이를 판단하고 생성하게 된다. 결국 기존 classfiier가 openset으로 판단하는 능력을 좀더 interpolation하는 기능은 있지만 실제로 openset을 잘 걸러내는 방법이라고 보기는 어렵다고 생각한다. ( 좋은 openset example이라고 할 수 없다고 생각)

 

 

728x90
728x90

Paper

https://arxiv.org/abs/1707.07418

 

 

G-openmax는 openmax에다가 gan을 이용하여 생성한 sample들을 이용해서 추가적으로 openset에 대한 mean vector를 만들어 distance를 구하고 openset여부를 판별하는 방법이다.

과정은 아래와 같다.

 

- 먼저 Known Class에 대해서 Net을 학습시킨다.

- Unknown sample을 생성하기 위한 generative model을 학습시킨다.  (DCGAN)

- 이때, 생성한 sample들 중에서 openset sample을 선정해야 한다.

 

- openset sample을 DCGAN으로 생성한 sample을 Net에 통과시켜서 틀린 sample들로 선정한다.

: Net이 커버하지 못하는 sample이므로.. open sample이라고 생각.

 

-본 논문에서 open space는 original space의 sub-space라고 가정한다.

- 즉,openset 또한 training dataset이 내부에 존재하는 set이라고 생각, 그러므로  openset은 다른 분포의 데이터셋을 포함하지 않는다고 가정한다.

(Thus, in this paper we assume that open space classes belong to a subspace of the original space, which includes known classes. In order to preserve it, we also do not consider an unlikely scenario when the test set contains objects from other datasets. )

 

- 이러한 가정을 하는 경우, openset problem은 closed set에서 sampling을 하는 문제로 바꿀 수 있다는 점이 장점이다.

(The advantage of building algorithm based on this assumption is that we would turn an open space classification problem into a standard closed set problem by sampling objects from known subspace.)

 

이때 생성을 하는 방법은 DC-GAN을 이용한다. (논문에서는 VAE에도 적용할 수 있다고 하긴 한다. -맞는 말임)

생성하는 방법은 원래는 특정 Class에 대해서 one-hot vector로 생성하지만, 여기서는 open-example을 만드는 것이 목표이기 때문에 normal distribution을 이용하여 class vector를 생성한다. - we can generate a class mixture vector m ∈ R N using any distribution Pnorm (e.g. Normal distribution) by sampling m1,...,mN−1 from Pnorm, and assigning mN = 1 − ∑ N−1 i=1 mi , such that ∑ N i=1 mi = 1 as for the basis vectors bi ∈ R N. The dimensionality of class subspace space (number of classes) is typically much smaller than the dimensionality of the original space (number of pixels), so the generated open set images will be located is a small nonlinear subspace of it as desired.)

 

 

어찌 되었던 이렇게 생성된 unknown sample을 이용해서 Net_G를 학습시킨다.

 

Openmax는 known class에 대해서 mean vector와  traininig sample에 대해서 disrance들을 구하고 weibull fitting을 진행했고, 이를 통해 logit값을 recalibaration해서 각 class에 이상치인 정도를 openset score로 고려하였다.

 

이렇게 known class에 대해 이상치에 대한 probability를 계산하고 이를 기반으로 openset score를 구하는 방식을 논문에서는 pseudo probability estimation으로 openset을 추론한다고 표현한다.

 

그러나 G-openmax는 이러한 pseudo probability estimation을 사용하지 않는다. 

 

GAN을 이용해 생성한 sample을 사용해 직접적으로 openset에 대한 mean vector를 만들고, weibull distribution도 직접적으로 fitting한다. (non-pseudo probability estimation)

 

그래서 G-openmax의 경우, test time때 input으로 sample이 들어오는 경우  Known class와 Unknown class에 대해 모두 weibull distribution에 대해 이상치 확률값을 도출하고 이를 통해 calibration을 하고 softmax를 통과시킨다.

 

이때, unknown class를 판별하는 방법은 Weibull model로 calibration을 하고 softmax를 통과해 나온 최종 확률이 특정 threshold값을 넘지 않을때 이다.

 

 

- GAN으로 생성된 openset example results

 

GAN으로 생성된 sample들의 결과이다.  MNIST와 같은 경우는 다른 2class의 정보가 섞임으로서, 새로운 8이라던가, 9 class와 같은 모형이 생성되기도 하고, 이는 openset recognition에 도움이 된다고 생각을 한다. 그러나 더욱 복잡한 dataset의 경우 gan으로 sample들을 생성하더라도, openset을 나타내는 sample이라고 보기 어려운 sample들이 생성되었고, 이는 크게 도움이 안되는듯 하다.

 

(However, we perfomed the same experiment as in [3] and figured out there are no obvious performance improvement by using G-OpenMax over the natural image setting. A more general reason might be that the generated images are not plausible with respect to the training classes in order to be good candidates to represent unknown classes from open space. More specifically, unlike the MNIST and HASYv2 dataset, ImageNet classes enjoy large variety, therefore not many common features are encoded in the learned latent space. Since our method is based on disentangling class information from other object features, the results it produces in this case do not differ much from interpolation in the pixel space.)

 

 

Pros

 

GAN을 이용해 Openset example을 생성한다는 idea가 재밌긴 하다.

idea 자체는 closed set의 sample들을 조합해서 training data가 나타내지 못하는 open-sub space공간을 GAN으로 생성하겠다는 것이다. 그러나, open space를 기존 training sample로 채운다는 것이 쉽지 않은 방법이라고 생각한다.

 

그래서 MNIST와 같은 간단한 데이터셋에 대해서는 이게 가능하지만, IMAGENET과 같은 real-image에서는 잘안되는 것을 확인할 수 있다.

 

 

Cons

 

간단한 데이터셋에서 밖에 안되는 것이 사실 큰 단점이다.

그래도 interpolation 개념을 가져와 open example을 생성하는 개념은 재밌는 생각이다.

728x90
728x90

Paper

https://arxiv.org/abs/1511.06233

 

Towards Open Set Deep Networks

Deep networks have produced significant gains for various visual recognition problems, leading to high impact academic and commercial applications. Recent work in deep networks highlighted that it is easy to generate images that humans would never classify

arxiv.org

 

Code

https://github.com/abhijitbendale/OSDN

 

abhijitbendale/OSDN

Code and data for the research paper "Towards Open Set Deep Networks" A Bendale, T Boult, CVPR 2016 - abhijitbendale/OSDN

github.com

https://github.com/takumayagi/openmax-cifar10

 

takumayagi/openmax-cifar10

A simple training/evaluation code of open set recognition using OpenMax (https://arxiv.org/abs/1511.06233) - takumayagi/openmax-cifar10

github.com

 

출처 : 2020.02.21. HCAI Open Seminar
Open Set Recognition In Deep Networks 김상훈

 

http://dmqm.korea.ac.kr/uploads/seminar/Open%20Set%20Recognition%20in%20Deep%20Networks_%EA%B9%80%EC%83%81%ED%9B%88.pdf

 

Openmax의 기본 알고리즘은 다음과 같다.

 

- 기존 openset recognition은 softmax로 thresholding한다.

- 그러나 이러한 방식은 open class가 input으로 들어온다는 가정이 없는 상황에서의 사용하는 방법이기 때문에 성능이 낮다.

- openmax에서는 이러한 단점을 해결하기 위해서 input과 다른 class weight간의 거리를 측정하여 openset을 걸러낸다.

- 또한 openset에 대한 logit을 따로 두기 때문에 openset이 Input으로 들어온다는 가정 또한 들어가게 된다.

 

그림으로 표현하면 위와 같이 되며, 이를 거리 기반으로 openset을 걸러내는 방법이기 때문에 distance-based라고 볼 수 있다.

 

- 또한 openmax에서는 input으로 들어온 값이 이상치 (abnormal value)인지 확인하기 위해 Extreme Value Theorem을 적용하고 극단의 값, 이상치에 대한 분포인 Weibull 분포를 활용하여 이상치 여부를 판단한다.

 

 

-이와 같이 거리 기반, Webull분포를 활용하기 위해 사용하는 실제 알고리즘은 아래와 같다.

 

- 각 클래스의 weight (mean vector)와 거리를 구하기 위해 먼저 각 클래스 별로 mean vector 값을 구한다. (classifier weight값과 동일)

 

 

- 이 mean vector의 값과 각 트레이닝 셋의 class당  logit값간의 거리(distance) 값을 모두 구한다.

- 이는 distance값을 구하고 거리가 큰 값들을 추출하여 Weibull distribution에 fitting 시키기 위함이다.

 

- 이렇게 각 클래스 별로 이상치 값에 대한 분포, webull distribution이 준비가 되면 다음과 같이 하여 이상치를 탐지한다.

 

이렇게 하면 클래스에 대한 Weibull 분포에 맞춰서 확률이 도출된다. (각 클래스의 기준에 이상치일 확률들)

 

-이 확률을 기반으로 원래의 logit값을 조정하고, open class의 logit을 도출한다.

 

Open class가 아닌 경우는 다음과 같이 된다.

 

 

 

Pros

 

일단 거리기반으로 openset이  input으로 들어올 수 있다는 가정이 들어 갔다는 것이 큰 장점이다.

또한 Class 별로 logit에 대한 weibull distribution을 따로 두었기 때문에 class별로 threshold값이 지정되는 효과도 어느정도 있다고 본다. 그러나 결국에는 모든 Class에 대한 결과를 합쳐서 고려하기 때문에 이러한 효과는 희석되는 듯하다. (정확히는 모르겠음)

 

Cons

 

거리기반으로 openset input에 대한 대비를 하기는 했지만, 기타 다른 논문들 처럼 open example을 활용한다던가,  기존 training class를 좀 더 뭉치게 만든다던가 하는 방법이 없기 때문에, 다른 논문들에 비해 성능이 낮다는 단점이 있다. 옛날 논문이기 때문에 어느정도 고려를 해주어야 하는 듯 하다.

 

728x90
728x90
  • python3.6 on ubuntu18.04 is necessary so you CANNOT remove that version(it includes system libraries)
  • prerequires: installed python3.8.
  • so you've 2 python 3.x(3.6, 3.8)
  1. check current state
    $pip -V
    (out)pip 20.0.2 from /home/amaruak00/.local/lib/python3.6/site-packages/pip (python 3.6)
  2. install venv, dev
    $sudo apt-get install python3.8-venv python3.8-dev
  3. update 3.8 pip
    $sudo /usr/bin/python3.8 -m pip install --upgrade pip
    (upgrading)
  4. check
    $pip -V
    (out)pip 20.0.2 from /home/amaruak00/.local/lib/python3.8/site-packages/pip (python 3.8)
  5. setting python3.8 as python3
    $sudo update-alternatives --config python3
    $sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 0 (마지막 인자는 실행 priority)
    #check python3.8 as primarly
    • If some libraries are seems crash, uninstall & reinstall
    • (ex)pip uninstall Pillow / pip install Pillow



https://amaruak00.tistory.com/24

 

Point pip command to python 3.8 from 3.6 on ubuntu 18.04

python3.6 on ubuntu18.04 is necessary so you CANNOT remove that version(it includes system libraries) prerequires: installed python3.8. so you've 2 python 3.x(3.6, 3.8) check current state $pip -V (..

amaruak00.tistory.com

 

728x90
728x90

- scp를 통해 폴더전송을 하려고 했으나 권한 때문에 전송이 안됐었음.

 

- docker를 통해 폴더를 생성할 경우 root 계정으로 폴더가 생성되는데, vclab 계정으로 전송하려고 하니 안됐음

 

- 전송받는 폴더의 권한을 root -> vclab으로 변경해줘야 됨.

 

chown vclab:vclab CHC/

 

첫번째는 '소유자', 두번째는 '소유그룹'을 의미

 

즉, 소유자, 소유그룹 모두 vclab으로 변경한다는 의미의 명령어.

 

https://peemangit.tistory.com/184

 

[Linux] chown 명령어 설명

1) chown 명령어 설명 -  chown 명령어는 소유자, 소유자와 소유그룹, 소유그룹을 변경시킬 수 있다. 1.1) 소유자 명 변경 chown [소유자] [파일 이름] 1.2) 소유자와 소유 그룹을 동시에 변경 chown [소유

peemangit.tistory.com

 

728x90

+ Recent posts