본문 바로가기

교육/CS224N winter 2021

Clean your desk! Transformers for unsupervised clustering of document images

Abstract

  • 문서 분류를 위해 Clustering 을 목표로 한다
  • Multi-modal Transformer-based encoder : LayoutLM과 LayoutLMv2 사용
  • RVL-CDIP 문서, SROIE 영수증 및 machine learning 논문에 테스트 수행
  • 텍스트가 많은 문서에 LayoutLM이 이점이 있음에도 LayoutLMv2가 항상 성능을 상회한다
  • [CLS] 토큰이 Clustering에 항상 최선의 representation은 아니다

1. Introduction

 문서 분류를 돕기위해 unsupervised document clustering을 수행했다. 이는 문서 분류와 다르게 라벨이 필요없다. Document understanding은 본질적으로 multimodal이며 강력한 문서 representation을 얻기 위해서는 text와 visual features 모두 통합시키는 것이 필요하다. 

2. Related Work 

 최근에서야 text와 visual modalities를 통하하는 연구들이 시작되었다. 대표 예시는 BERT에 text 입력만 사용했지만 2D positional embeddings 추가한 LayoutLM이다. 후속 연구로 LayoutLMv2와 LayoutLMv3로 visual token을 추가할 뿐 아니라 text-image alignment와 text-image matching 사전학습 tasks를 적용했다. 이 외에도 DocFormer와 LAMBERT 같이 유사한  연구가 있다.
위의 연구들은 문서 분류나 entity 추출과 같은 특정 tasks에 미세조정했다. 그러나 일반적인 목적의 문서 embedding을 얻기위한 노력은 없었다. 따라서 이 작업의 핵심 기여는 multi-modal transformer-based architectures (LayoutLM과 LayoutLMv2)의 unsupervised document clustering을 평가하여 최적의 document embedding을 찾는 것이다. 

3. Methods

Unsupervised document clustering은 두 단계로 정의

  1. Document Embedding: 주어진 문서 $d_i$를 text, bounding boxes, 및 image로 전처리. 이후 모델 $m_{encoder}$를 통해 embedding $e_{di}$를 생성
  2. Document Clustering: embeddings $e_{di}$를 $N$ 문서에 대해 생성하여 모델 $m_{cluster}$로 $k$개의 clusters로 구분

이 때 encoder 모델 $m_{encoder}$에 대해 text-only와 vision-only baseline을 우선 테스트

  • Bag-of-Words (BoW): sklearn의 CountVectorizer를 이용하여 text를 encoding PCA를 통해 최대 크기를 1024로 감소
  • ResNet-18: Image2Vec을 이용하여 image를 encode 512의 embedding을 얻음
  • AlexNet: Image2Vec을 이용하여 image를 encode 4096의 embedding을 얻은 후 PCA를 통해 최대 크기를 1024로 감소

이후 Transformer 기반의 문서 인코딩 모델을 테스트했다. 마지막 층의 토큰 임베딩 (maximum sequence length, embedding dim)을 선택 혹은 pool 하여 (embedding dim,) shape의 단일 document embedding을 생성한다. 테스트에 사용한 모델은 LayoutLM과 LAyoutLMv2를 HuggingFace로부터 가져왔다.
 Clustering model $m_{cluster}$는 sklearn library의 *Gaussian Mixture Model (GMM)을 사용했다. 가시화에는 t-SNE를 사용했다. 

* 비원형 클러스터를 처리하고 클러스터에 문서를 부드럽게 할당할 수 있는 기능 때문에 K-Means와 반대로 GMM을 선택했다.

3.1. LayoutLM

https://enjoythehobby.tistory.com/entry/LayoutLM-Pre-training-of-Text-and-Layout-for-Document-Image-Understanding

 

LayoutLM: Pre-training of Text and Layout for Document Image Understanding

Abstract Pre-training 기법은 다양한 NLP 작업에서 최근 몇 년 간 효과적이라고 검증되었다. 그러나 대부분의 NLP application은 text-level에 집중되어있고 문서의 layout이나 style은 무시되었다. 본 논문에서

enjoythehobby.tistory.com

3.2. LayoutLMv2

LayoutLM과 달리 LayoutLMv2의 주요 이점은 visual feature도 입력으로 사용하며 MDC task를 TIA와 TIM으로 대체 했다는 것이다. 

3.2.1 Model Inputs

Figure 1. The LayoutLMv2 architecture, taken from [32], illustrating the visual and text inputs. Note that the diagram slightly misrepresents the inputs since the visual tokens are actually ap- pended, not prepended, to the text tokens.

Figure. 1 에 LayoutLMv2의 아키텍처의 개요를 보여주며 입력 생성 시 text embeddings에 visual token embedding을 연결한다. 각각에 1D, 2D, 그리고 segment embedding을 더해준다. 

  • Visual Embedding 
    • image는 224x224로 resize
    • ResNeXt-FPN 모델로 encode
    • 7x7로 average-pooled 후 49 sequence로 flattten
    • linear projection을 통해 차원 맞추고 모든 visual tokens는 [C]로 special segment 
  • Layout (2D Position) Embedding
    • Bounding box의 height와 width를 표현
    • 2D position embedding을 모두 연결하여 표현
    • $l_i = \texttt{Concat}(x_{0i}, x_{1i}, y_{0i}, y_{1i}, h_{i}, w_{i})$

3.2.2 Spatial-Aware Self-Attention

 LayoutLMv2의 경우 두 tokens의 상대적인 위치 차이를 모델에 내제화하기 위해 학습가능한 편차를 attention scores에 추가했다. 기존 Transformer의 attention이 $\alpha _{ij}$ 이고 $(x_i, y_i)$가 bounding box의 좌측상단 $(x_j, y_j)$가 우측하단이라고 하면 $\alpha '_{ij} = \alpha _{ij} + b^{(1D)}_{j-i} + b^{(2D)}_{x_j-x_i} + b^{(2D)}_{y_j-y_i}$ 로 새롭게 위치 관련 편차를 더해주어 attention을 정의한다.

3.2.3 Training Objectives

  • Text-Image Alignment (TIA)
    • Tokens의 몇 줄의  image region이 covered(mask라는 단어와의 혼동을 피하기 위함) 
    • 해당 text token이 covered 되었는지 유무를 예측 (binary cross entropy)
    • 만약 token이 [mask]일 경우 loss 계산에서 제외
  • Text-Image Matching (TIM)
    • [CLS] token을 사용하여 image와 text가 같은 문서의 페이지에 있는지 여부를 예측
    • 반례들은 page의 image를 drop 혹은 다른 문서의 이미지와 swap하여 생성
    • Binary cross entropy 계산

3.3. From Token to Document Embeddings

다음을 document embedding으로 테스트

  • [CLS] token
  • [SEP] token
  • 모든 token embeddings ([SEP], [CLS], 및 [PAD] 제외)를 평균
  • 모든 image embddings를 평균

4. Dataset

Figure 2. Examples of document images from the unlabeled datasets. The first row shows examples of documents from RVL- CDIP, such as a resume, memo, and news article. The second row shows a sample of receipts from SROIE2019.

  • SROIE2019의 626 문서 image
  • RVL-CDIP의 1,000개 문서 image
  • Unsupervised clustering 작업을 수행하기 때문에 라벨을 사용하지 않고 data split도 하지 않음

Figure 3. The papers on the top row are from the MLSys 2022 conference proceedings [9, 22]. To these papers, I either assigned the label mlsys no stamps (e.g. top-left) or mlsys stamps (e.g. top-right, which has green and red circular stamps on the page cor- ner). The papers on the bottom row are from the NeurIPS 2021 conference proceedings [5, 19]. To all of these papers, I simply assigned the label neurips. The MLSys papers are two-column and have smaller margins; the NeurIPS papers are one column, have wider margins, and slightly bolder headers. fashion

  • 독자 라벨된 데이터셋 생성 (Figure. 3)
    : MLSys2022 논문 20건 + NeuIPS2021 논문 10건, 유사한 LATEX 형식을 사용하지만 양식이 다르다
  • 해당 데이터는 모델을 평가하기 위해 사용됐으며, 학습에는 사용하지 않음
  • 모든 encoder $m_{encoder}$는 독립적인 데이터셋으로 사전 학습. 준비된 위의 세 데이터셋은 문서 embeddings $e_{d_i}$를 구하고 clustring 모델$m_{cluster}$을 최적화하는데 사용
  • 문서 페이지가 여러 장일 경우 첫 장만 사용하고 text는 512가 되도록 truncate 혹은 padding
  • Impira를 사용하여 text를 전처리 (OCR)
  • LayoutLMProcessor를 사용하여 image 전처리 (224x224로 resize, 7x7로 average pooled 후 49 tokens로 flatten)

5. Results and Discussion

LayoutLM과 LayoutLMv2 각각 Base와 Large 모델에 대해 테스트를 진행했다.

[사전 학습 파라미터는 skip]

Clustering 모델 $m_{cluster}$의 cluster 수 $k$는 SROIE-2019와 RVL-CDIP에는 10, ML 논문에는 3을 설정했다.

5.1. SROIE and RVL-CDIP

Table 1. Unsupervised Clustering Results with No Labels Metrics: (Silhouette Coefficient / Calinski-Harabasx (CH) score)

Unsupervised clustering metrics: the Silhouetee and Calinski-Harabasz (CH) scores

https://studying-haeung.tistory.com/10

 

[머신러닝] 클러스터링 평가지표 - 실루엣 계수 (1)

실루엣 계수(Silhouette Coefficient) : 각 데이터 포인트와 주위 데이터 포인트들과의 거리 계산을 통해 값을 구하며, 군집 안에 있는 데이터들은 잘 모여있는지, 군집끼리는 서로 잘 구분되는지 클러

studying-haeung.tistory.com

https://hongl.tistory.com/161

 

Clustering - Performance (1)

지난 포스트 [Machine Learning/Unsupervised Learning] - Clustering - Hungrian Algorithm 지난 포스트에서는 clustering 의 결과 할당된 군집 번호를 라벨과의 정확도가 최대화가 되도록 재할당하는 Hungarian Algorithm 에

hongl.tistory.com

각각의 metric의 값은 얼마나 cluster 간 거리가 가까운지 cluster 내 데이터 간 거리가 큰지를 의미하며, Silhouette score는 [-1,1]의 범위를 CH score는 [0,∞] 범위를 갖는다. 두 점수 모두 클수록 좋다.

Table 1. Unsupervised Clustering Results with No Labels Metrics: (Silhouette Coefficient / Calinski-Harabasx (CH) score) Method

여러 모델에 대한 평가는 Table. 1에 기술 되었으며, LayoutLMv2 Base가 가장 좋은 지표를 보여준다. 이는 multi-modal learning이 document clustering에 도움을 준다는 결과를 보여준다. 그러나 RVL-CDIP의 결과는 LayoutLM Base가 좋다는 점과 Baseline들을 봤을 때 clustering은 데이터셋 별로 차이가 존재하는 것을 알 수 있다.(SROIE는 visual, RVL-CDIP는 text가 좀 더 중요하다)

 Large 모델의 경우 성능이 저하되는 결과를 확인했다. Base와 Large의 차이는 token embedding 차원의 크기이며, 가능한 해석은 차원이 큰 경우 clustering이 더 어렵다는 것이다. 또다른 가능한 해석은 학습동안 수렴이 완료되지 않았다는 것이다. 

 Document embeddings의 경우 LayoutLM은 [SEP]이 가장 좋은 성능을 보여주었는데 이는 [CLS]가 사전학습 task 중 "overfitting" 되어서일 수 있다.  LayoutLMv2의 경우 image tokens hidden states의 평균이 가장 좋은 성능을 보여준다. 

Figure 4. These t-SNE plots show document embeddings from the four mencoder models on the SROIE dataset. In quadrant order: Bag of Words (BoW), AlexNet, and LayoutLM (Base), and LayoutLMv2 (Base). Each point corresponds to the first page document embedding. For LayoutLM, I use the [SEP] output hidden state and for LayoutLMv2 I average all of the image token ouput hidden states. Each color represents a predicted cluster. The clusters get progressively tighter and better separated.
Figure 5. Zooming into the light pink cluster from the LayoutLM base model in Figure 4, we can inspect the documents within it. The left and right plots show that two different receipts from Gardenia Bakery have been clustered together.

Figure.4 와 Figure.5를 통해 가시화된 결과를 확인할 수 있다. 

5.2. ML Conference Papers

 

Table 2. Unsupervised Clustering Results with Labels Metrics: P/R (per-class); Accuracy (overall)

직접 생성한 ML 논문 데이터로 cluster 품질을 평가했다. $m_{cluster}$ 예측값 0,1,2는 mlsys_no_stamps, mlsys_stamps, neurips를 의미한다. 과정에서 각 cluster와 라벨의 매칭 정확도가 최대가 되도록했다. 이는 Linear Sum Assignment을 이용하여 수행했다. 이 relabelled 결과를 토대로 Table. 2 를 만들었다. 

https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html

 

scipy.optimize.linear_sum_assignment — SciPy v1.11.2 Manual

[2] DF Crouse. On implementing 2D rectangular assignment algorithms. IEEE Transactions on Aerospace and Electronic Systems, 52(4):1679-1696, August 2016, DOI:10.1109/TAES.2016.140952

docs.scipy.org

각각 LayoutLM Base [SEP]와 LayoutLMv2 Base image token hidden states의 평균을 이용했다. 결과는 분명하게 여백, 폰트, 다단 및 colored stamp와 같은 visual cues의 차이가 존재함에도  LayoutLMv2가 항상 최선은 아니라는 것이다. 추가적으로 footer에 학회 이름이 적혀있는 것과 같은 textual cues도 분명히 존재한다. 

6. Conclusion

  • RVL-CDIP 1,000개, SROIE 626개, ML 논문 30개 데이터 
  • Transformer-based multi-modal encoding model : LayoutLM, LayoutLMv2
  • Visual token 덕에 LayoutLMv2가 LayoutLM 성능을 상회하는 것처럼 보이지만 text-heavy 문서에는 LayoutLM 문서가 좋다
  • LayoutLM에는 [SEP] 출력이 LayoutLMv2에는 image token 출력의 평균이 성능이 좋다

 

 *** 이후 버전

https://web.stanford.edu/class/cs224n/reports/custom_117051501.pdf

Table 1: Layout Identification Results (Silhouette Coefficient / Calinski-Harabasx (CH) Index)

더 다양한 인코딩 정보, 미세조정의 영향, cluster 개수 (k) 최적화 등등 추가 연구됨

'교육 > CS224N winter 2021' 카테고리의 다른 글

Lec10) Transformers and Pretraining  (0) 2022.07.05
Lec 9) Self-Attention & Transformers  (0) 2022.06.16
Lec 8) Attention  (0) 2022.06.16
Lec 7) Translation, Seq2Seq  (0) 2022.06.14
Lec 6) Simple and LSTM RNNs  (0) 2022.05.18