Views
No views yet
0: 팩트체크가 불필요한 문장 (Non-checkworthy)1: 팩트체크가 필요한 주장 (Checkworthy claim) Predicted
0 1
Actual 0 203 7 (96.7% 정확도)
1 27 81 (75.0% 재현율)pip install transformers torch1from transformers import AutoTokenizer, AutoModelForSequenceClassification
2import torch
3
4# 모델 로드
5model_name = "jonghhhh/claim_factcheck"
6tokenizer = AutoTokenizer.from_pretrained(model_name)
7model = AutoModelForSequenceClassification.from_pretrained(model_name)
8
9# GPU 사용 (선택사항)
10device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11model.to(device)
12model.eval()
13
14print(f"✅ 모델 로드 완료! (Device: {device})")1def predict_claim(text):
2 """
3 입력 문장이 팩트체크가 필요한 주장인지 판단합니다.
4
5 Args:
6 text (str): 분석할 한국어 문장
7
8 Returns:
9 dict: {
10 'text': 입력 문장,
11 'is_checkworthy': True/False,
12 'confidence': 0.0~1.0 (확신도),
13 'label': 0 또는 1,
14 'probabilities': {'non_checkworthy': 0.xx, 'checkworthy': 0.xx}
15 }
16 """
17 # 토크나이징
18 inputs = tokenizer(
19 text,
20 truncation=True,
21 max_length=128,
22 return_tensors="pt"
23 )
24 inputs = {k: v.to(device) for k, v in inputs.items()}
25
26 # 추론
27 with torch.no_grad():
28 outputs = model(**inputs)
29 probs = torch.softmax(outputs.logits, dim=-1)
30 predicted_label = torch.argmax(probs, dim=-1).item()
31 confidence = probs[0][predicted_label].item()
32
33 return {
34 'text': text,
35 'is_checkworthy': bool(predicted_label),
36 'confidence': confidence,
37 'label': predicted_label,
38 'probabilities': {
39 'non_checkworthy': probs[0][0].item(),
40 'checkworthy': probs[0][1].item()
41 }
42 }
43
44# 사용 예시
45examples = [
46 "오늘 토론회는 SBS 상암동 스튜디오에서 진행하고 있고요.",
47 "청년 실업률이 최근 3년간 계속 상승하고 있습니다.",
48 "우리나라 GDP 성장률은 OECD 평균을 넘어섰습니다.",
49 "국민 여러분께 진심으로 감사드립니다."
50]
51
52for text in examples:
53 result = predict_claim(text)
54 print(f"\n📝 입력: {result['text']}")
55 print(f"{'🔍 팩트체크 필요' if result['is_checkworthy'] else '✅ 팩트체크 불필요'}")
56 print(f"확신도: {result['confidence']*100:.1f}%")
57 print(f"상세 확률: Non-CW {result['probabilities']['non_checkworthy']*100:.1f}% | CW {result['probabilities']['checkworthy']*100:.1f}%")📝 입력: 청년 실업률이 최근 3년간 계속 상승하고 있습니다.
🔍 팩트체크 필요
확신도: 94.3%
상세 확률: Non-CW 5.7% | CW 94.3%
📝 입력: 오늘 토론회는 SBS 상암동 스튜디오에서 진행하고 있고요.
✅ 팩트체크 불필요
확신도: 98.2%
상세 확률: Non-CW 98.2% | CW 1.8%1def predict_claims_batch(texts, batch_size=32):
2 """
3 여러 문장을 배치로 처리합니다.
4
5 Args:
6 texts (list): 문장 리스트
7 batch_size (int): 배치 크기
8
9 Returns:
10 list: 각 문장의 예측 결과 리스트
11 """
12 results = []
13
14 for i in range(0, len(texts), batch_size):
15 batch_texts = texts[i:i+batch_size]
16
17 # 배치 토크나이징
18 inputs = tokenizer(
19 batch_texts,
20 truncation=True,
21 max_length=128,
22 padding=True,
23 return_tensors="pt"
24 )
25 inputs = {k: v.to(device) for k, v in inputs.items()}
26
27 # 배치 추론
28 with torch.no_grad():
29 outputs = model(**inputs)
30 probs = torch.softmax(outputs.logits, dim=-1)
31 predicted_labels = torch.argmax(probs, dim=-1).cpu().numpy()
32
33 # 결과 저장
34 for j, text in enumerate(batch_texts):
35 results.append({
36 'text': text,
37 'is_checkworthy': bool(predicted_labels[j]),
38 'confidence': probs[j][predicted_labels[j]].item(),
39 'label': int(predicted_labels[j])
40 })
41
42 return results
43
44# 배치 추론 예시
45texts = [
46 "국회의원 정원을 300명으로 확대하겠습니다.",
47 "감사합니다.",
48 "2024년 경제성장률이 2.1%를 기록했습니다.",
49 # ... 더 많은 문장들
50]
51
52batch_results = predict_claims_batch(texts)
53checkworthy_claims = [r for r in batch_results if r['is_checkworthy']]
54print(f"✅ 총 {len(texts)}개 문장 중 {len(checkworthy_claims)}개가 팩트체크 필요")1# 뉴스 기사에서 팩트체크 대상 추출
2def extract_checkworthy_claims(article_text, threshold=0.7):
3 """
4 기사에서 팩트체크가 필요한 문장들을 추출합니다.
5
6 Args:
7 article_text (str): 뉴스 기사 전문
8 threshold (float): checkworthy 판단 임계값 (0.0~1.0)
9
10 Returns:
11 list: 팩트체크 대상 문장들
12 """
13 # 문장 분리 (간단한 예시)
14 sentences = [s.strip() for s in article_text.split('.') if s.strip()]
15
16 # 배치 예측
17 results = predict_claims_batch(sentences)
18
19 # 임계값 이상의 checkworthy 문장만 필터링
20 checkworthy_claims = [
21 r for r in results
22 if r['is_checkworthy'] and r['confidence'] >= threshold
23 ]
24
25 # 확신도 순으로 정렬
26 checkworthy_claims.sort(key=lambda x: x['confidence'], reverse=True)
27
28 return checkworthy_claims
29
30# 사용 예시
31article = """
32정부는 오늘 경제정책 방향을 발표했습니다.
33청년 실업률이 지난해 대비 2.3%p 감소했다고 밝혔습니다.
34이는 역대 최대 폭의 하락입니다.
35앞으로도 일자리 창출에 힘쓰겠다고 강조했습니다.
36"""
37
38claims = extract_checkworthy_claims(article, threshold=0.8)
39print(f"🔍 발견된 팩트체크 대상: {len(claims)}개\n")
40
41for i, claim in enumerate(claims, 1):
42 print(f"{i}. {claim['text']}")
43 print(f" 확신도: {claim['confidence']*100:.1f}%\n")1@misc{korean-claim-factcheck-2025,
2 author = {Jonghhhh},
3 title = {Korean Claim Detection Model for Fact-Checking},
4 year = {2025},
5 publisher = {Hugging Face},
6 howpublished = {\url{https://huggingface.co/jonghhhh/claim_factcheck}},
7 note = {Based on KcELECTRA-base-v2022}
8}claim-detection, fact-checking, korean, electra, text-classification, checkworthy, misinformation-detection