Datasets:
File size: 10,062 Bytes
b456012 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
"""
분리된 임베딩 데이터 로드 및 사용 예제
제목과 본문이 따로 임베딩되어 있음:
- 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임베딩을 사용한 학습을 시작하세요!")
|