내가 하는 지도 주제 모델링 재고: ModernBERT와 GPT-4o mini 활용

R-Blogger · 블로그·해설 · 2024-12-22

R-Blogger블로그·해설한국어2024-12-22

내가 하는 지도 주제 모델링 재고: ModernBERT와 GPT-4o mini 활용

스위스 텍스트 분류 파이프라인 재고하기 2023년 7월에 작성한 글에서 감독 Wes Anderson의 영화 Asteroid City에 대한 720개의 Letterboxd 리뷰를 사용해 감독의 독특한 시각적 스타일(1) 혹은 비(0) 여부를 라벨링한 supervised 텍스트 분류 파이프라인을 소개했습니다. 본 포스트에서는 기존 bag‑of‑words 접근 방식의 한계를 극복하고, ModernBERT와 GPT‑4o mini를 활용한 대안적 방법을 탐구합니다. 원본 파이프라인 요약 텍스트 읽기 → 테마 내용 코딩 가이드 작성 → 사람에 의해 라벨링 워드 vs. 단어‑및‑바이그램 토크나이징, 표제어 추출 여부, 불용어 제거 여부, 단어 빈도 필터 등 다양한 전처리 정의 → workflowset에 저장 각 전처리별로 elastic net, XGBoost, 랜덤 포레스트 등 표준 모델 적용 주제별 모델을 별도 실행 (예: 5개 주제라면 5번 파이프라인 실행) bag‑of‑words 기반 supervised 모델이 실제 테스트 세트에서 26%를 19%로 예측해 절대 오차 7점이 발생함 ModernBERT 소개 및 활용 ModernBERT는 bidirectional encoder‑only 구조로, 문장과 각 단어의 위치 정보를 이용해 텍스트를 768차원 숫자 벡터로 변환합니다. 이 방식은 synonyms와 homonyms 같은 의미 구분에 강합니다. 1) Fill‑Masking 방법 Masking을 이용해 문장을 예측하는 방법입니다. 예시는 다음과 같습니다. from transformers import pipeline pipe = pipeline('fill-mask', model='answerdotai/ModernBERT-base') pipe('The dog DNA test said my dog is almost half American pit[MASK] terrier.') 위 예제에서 가장 확률 높은 예측은 ' bull'이며, 81% 확률로 문장을 완성합니다. 이를 활용해 리뷰에 [MASK]를 삽입하고 “visual style에 대해 논의했는가?”라는 질문을 던집니다. # prep from transformers import pipeline import pandas as pd dat = pd.read_csv('ratings_coded.csv') dat = dat[dat['visual_style'] != 9] dat['masked_class'] = '' # fill mask pipe = pipeline('fill-mask', model='answerdotai/ModernBERT-base') for i in dat.index: review = dat['text'][i].lower() prompt = f'''this is a movie review: question: did the review discuss the visual style of the film, yes or no? answer:[MASK]''' out = pipe(prompt) tmp = out[0]['token_str'].strip().lower() if tmp not in ['yes', 'no']: tmp = out[1]['token_str'].strip().lower() dat.loc[i, 'masked_class'] = tmp dat.to_csv('ratings_masked.csv') 2) Embedding 기반 분류 Embedding을 얻어 LASSO 회귀로 예측합니다. # prep import pandas as pd from sentence_transformers import SentenceTransformer dat = pd.read_csv('ratings_coded.csv') text = dat['text'] # get embeddings model = SentenceTransformer('answerdotai/ModernBERT-base') embeddings = model.encode(text) dat_embeddings = pd.DataFrame(embeddings).add_prefix('embed_') dat_out = pd.concat([dat, dat_embeddings], axis=1) dat_out.to_csv('ratings_embedded.csv', index=False) Generative 모델: GPT‑4o mini 활용 정의 없이 “Zero‑shot”으로 질문을 던지고, 모델이 스스로 0/1을 반환하도록 합니다. 먼저 Anderson의 시각적 스타일에 대한 짧은 설명을 요청합니다. # prep import re import pandas as pd from openai import OpenAI API_KEY='' model='gpt-4o-mini' client = OpenAI(api_key=API_KEY) # get description description = client.chat.completions.create( model=model, messages=[ { 'role': 'user', 'content': "Provide a brief description of director Wes Anderson's visual style." } ], temperature=0 ) description = description.choices[0].message.content with open('description.txt', 'w') as file: file.write(description) with open('description.txt', 'r') as file: description = file.read() Wes Anderson’s visual style is characterized by its meticulous symmetry, vibrant color palettes, and whimsical, storybook-like aesthetics. He often employs a distinctive use of wide-angle lenses, which creates a flat, two-dimensional look that enhances the surreal quality of his films. Anderson’s compositions are carefully arranged, with a focus on geometric shapes and patterns, often featuring centered framing and balanced scenes. His sets are richly detailed, filled with quirky props and vintage elements that contribute to a nostalgic atmosphere. Additionally, he frequently uses stop‑motion animation and unique transitions, further emphasizing his playful and imaginative storytelling approach. Overall, Anderson’s style is instantly recognizable and evokes a sense of
원문 URL
전체 글은 원문 페이지에서 이어서 읽을 수 있습니다.
원문에서 전체 글 읽기
작성자
R-Blogger
출처
R-Blogger
플랫폼
R-Blogger
분류
블로그·해설
언어
한국어
발행일
2024-12-22