clickbait_embeddings / load_example.py
jjanoong2's picture
Upload load_example.py with huggingface_hub
b456012 verified
"""
분리된 임베딩 데이터 로드 및 사용 예제
제목과 본문이 따로 임베딩되어 있음:
- title_embeddings: (N, 768)
- content_embeddings: (N, 768)
"""
import numpy as np
import torch
import torch.nn as nn
from pathlib import Path
# ============================================================
# 1. 임베딩 데이터 로드
# ============================================================
def load_embeddings(file_path):
"""
.npz 파일에서 분리된 임베딩 데이터 로드
Returns:
title_embeddings: (N, 768) numpy array - 제목 임베딩
content_embeddings: (N, 768) numpy array - 본문 임베딩
labels: (N,) numpy array - 0 (비낚시성) 또는 1 (낚시성)
article_ids: (N,) numpy array - 기사 ID (참고용)
"""
data = np.load(file_path)
title_embeddings = data['title_embeddings']
content_embeddings = data['content_embeddings']
labels = data['labels']
article_ids = data['article_ids']
return title_embeddings, content_embeddings, labels, article_ids
# ============================================================
# 2. 데이터 로드 예제
# ============================================================
print("="*60)
print("분리된 임베딩 데이터 로드 예제")
print("="*60)
# 경로 설정
embeddings_dir = Path(r"C:\Users\Asus\Desktop\data_projext\embeddings")
train_path = embeddings_dir / "train_embeddings.npz"
val_path = embeddings_dir / "val_embeddings.npz"
test_path = embeddings_dir / "test_embeddings.npz"
# Train 데이터 로드
print("\n[Train 데이터]")
X_train_title, X_train_content, y_train, train_ids = load_embeddings(train_path)
print(f" 제목 임베딩: {X_train_title.shape} # (샘플 수, 768차원)")
print(f" 본문 임베딩: {X_train_content.shape} # (샘플 수, 768차원)")
print(f" 레이블: {y_train.shape} # (샘플 수,)")
# Validation 데이터 로드
print("\n[Validation 데이터]")
X_val_title, X_val_content, y_val, val_ids = load_embeddings(val_path)
print(f" 제목 임베딩: {X_val_title.shape}")
print(f" 본문 임베딩: {X_val_content.shape}")
print(f" 레이블: {y_val.shape}")
# Test 데이터 로드
print("\n[Test 데이터]")
X_test_title, X_test_content, y_test, test_ids = load_embeddings(test_path)
print(f" 제목 임베딩: {X_test_title.shape}")
print(f" 본문 임베딩: {X_test_content.shape}")
print(f" 레이블: {y_test.shape}")
# ============================================================
# 3. 합치는 방법
# ============================================================
print("\n" + "="*60)
print("제목과 본문 합치는 방법")
print("="*60)
# 방법 1: 단순 concatenate (가장 간단)
print("\n[방법 1] 단순 Concatenate")
X_train_concat = np.concatenate([X_train_title, X_train_content], axis=1)
print(f"결과: {X_train_concat.shape} # (N, 1536)")
print("→ 이제 일반 MLP로 학습 가능")
# 방법 2: 각각 처리 후 결합 (추천!)
print("\n[방법 2] 각각 처리 후 결합 (PyTorch)")
# ============================================================
# 4. PyTorch 모델 예제
# ============================================================
print("\n" + "="*60)
print("PyTorch 모델 예제")
print("="*60)
class ClickbaitClassifier(nn.Module):
"""
제목과 본문을 각각 처리한 후 결합하는 분류기
"""
def __init__(self):
super().__init__()
# 제목 처리 네트워크
self.title_network = nn.Sequential(
nn.Linear(768, 384),
nn.ReLU(),
nn.Dropout(0.3)
)
# 본문 처리 네트워크
self.content_network = nn.Sequential(
nn.Linear(768, 384),
nn.ReLU(),
nn.Dropout(0.3)
)
# 결합 후 분류기
self.classifier = nn.Sequential(
nn.Linear(768, 256), # 384 + 384 = 768
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(256, 2) # 2개 클래스 (0, 1)
)
def forward(self, title_emb, content_emb):
"""
Args:
title_emb: (batch_size, 768)
content_emb: (batch_size, 768)
Returns:
output: (batch_size, 2)
"""
# 제목과 본문 각각 처리
title_features = self.title_network(title_emb) # (batch, 384)
content_features = self.content_network(content_emb) # (batch, 384)
# 결합
combined = torch.cat([title_features, content_features], dim=1) # (batch, 768)
# 분류
output = self.classifier(combined) # (batch, 2)
return output
# 모델 생성
model = ClickbaitClassifier()
print(f"\n모델 생성 완료!")
print(f"총 파라미터 수: {sum(p.numel() for p in model.parameters()):,}")
# ============================================================
# 5. 학습 코드 예제
# ============================================================
print("\n" + "="*60)
print("학습 코드 예제")
print("="*60)
print("""
from torch.utils.data import Dataset, DataLoader
# 1. Dataset 클래스 정의
class ClickbaitDataset(Dataset):
def __init__(self, title_emb, content_emb, labels):
self.title_emb = torch.FloatTensor(title_emb)
self.content_emb = torch.FloatTensor(content_emb)
self.labels = torch.LongTensor(labels)
def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
return self.title_emb[idx], self.content_emb[idx], self.labels[idx]
# 2. DataLoader 생성
train_dataset = ClickbaitDataset(X_train_title, X_train_content, y_train)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
val_dataset = ClickbaitDataset(X_val_title, X_val_content, y_val)
val_loader = DataLoader(val_dataset, batch_size=64, shuffle=False)
# 3. 모델, Loss, Optimizer
model = ClickbaitClassifier()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 4. 학습 루프
for epoch in range(10):
model.train()
for title_batch, content_batch, label_batch in train_loader:
optimizer.zero_grad()
# Forward
outputs = model(title_batch, content_batch)
loss = criterion(outputs, label_batch)
# Backward
loss.backward()
optimizer.step()
# Validation
model.eval()
correct = 0
total = 0
with torch.no_grad():
for title_batch, content_batch, label_batch in val_loader:
outputs = model(title_batch, content_batch)
_, predicted = torch.max(outputs, 1)
total += label_batch.size(0)
correct += (predicted == label_batch).sum().item()
accuracy = correct / total
print(f'Epoch {epoch+1}, Accuracy: {accuracy:.4f}')
""")
# ============================================================
# 6. 간단한 MLP 버전 (방법 1 사용)
# ============================================================
print("\n" + "="*60)
print("간단한 MLP 버전 (Concatenate)")
print("="*60)
print("""
# 제목+본문 단순 결합
X_train = np.concatenate([X_train_title, X_train_content], axis=1) # (N, 1536)
X_val = np.concatenate([X_val_title, X_val_content], axis=1)
# 간단한 MLP
class SimpleMLP(nn.Module):
def __init__(self):
super().__init__()
self.network = nn.Sequential(
nn.Linear(1536, 768),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(768, 384),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(384, 2)
)
def forward(self, x):
return self.network(x)
model = SimpleMLP()
# 학습
X_train_tensor = torch.FloatTensor(X_train)
y_train_tensor = torch.LongTensor(y_train)
# ... (일반적인 학습 코드)
""")
# ============================================================
# 7. Scikit-learn 사용 (매우 간단)
# ============================================================
print("\n" + "="*60)
print("Scikit-learn 사용 (가장 간단)")
print("="*60)
print("""
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
# 제목+본문 결합
X_train = np.concatenate([X_train_title, X_train_content], axis=1)
X_val = np.concatenate([X_val_title, X_val_content], axis=1)
# Logistic Regression
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
y_pred = model.predict(X_val)
print(f'Accuracy: {accuracy_score(y_val, y_pred):.4f}')
# Random Forest
rf_model = RandomForestClassifier(n_estimators=100)
rf_model.fit(X_train, y_train)
rf_pred = rf_model.predict(X_val)
print(f'RF Accuracy: {accuracy_score(y_val, rf_pred):.4f}')
""")
# ============================================================
# 8. 중요 정보
# ============================================================
print("\n" + "="*60)
print("중요 정보")
print("="*60)
print("""
[데이터 형태]
- title_embeddings: (N, 768) - 제목만 SBERT 임베딩
- content_embeddings: (N, 768) - 본문만 SBERT 임베딩
- labels: (N,) - 0 (비낚시성) 또는 1 (낚시성)
- article_ids: (N,) - 기사 ID (학습에 사용 안 함!)
[합치는 방법]
1. 단순 concatenate: [title(768) + content(768)] = 1536차원
→ 간단하지만 제목/본문 구분 없음
2. 각각 처리 후 결합: 제목→384, 본문→384, 결합→768
→ 제목/본문에 다른 가중치 부여 가능 (추천!)
3. Attention 메커니즘: 제목과 본문의 상호작용 학습
→ 고급 방법, 성능 향상 가능
[주의사항]
- article_ids는 학습에 사용하지 말 것!
- Train/Val/Test 간 article_id 중복 없음 (검증 완료)
- 출력층은 2개 (Class 0, Class 1)
- Loss: CrossEntropyLoss 사용
[추천 순서]
1. 먼저 Scikit-learn으로 베이스라인 확인
2. 간단한 MLP (concatenate) 시도
3. 각각 처리 후 결합 모델 시도
4. 하이퍼파라미터 튜닝
""")
print("\n임베딩을 사용한 학습을 시작하세요!")