본문 바로가기

데이터사이언스/데이터사이언티스트4기

로이터 뉴스 데이터셋 머신러닝 다중분류

 

📋 2025-06-18 머신러닝 & 텍스트 분류 통합 캔버스 (코드+설명 포함)


1. 로이터 뉴스 데이터셋 로드 및 이해

from tensorflow.keras.datasets import reuters

(x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=10000, test_split=0.2)

print(f"훈련 데이터 개수: {len(x_train)}")
print(f"테스트 데이터 개수: {len(x_test)}")
  • 뉴스는 정수 시퀀스로 표현됨
  • 46개 주제 레이블 존재
  • 특수 토큰 <pad>, <sos>, <unk>가 0,1,2번 인덱스

2. 단어 인덱스 복원 및 텍스트 변환

word_index = reuters.get_word_index()
index_to_word = {index + 3: word for word, index in word_index.items()}
index_to_word[0] = "<pad>"
index_to_word[1] = "<sos>"
index_to_word[2] = "<unk>"

decoded_sample = ' '.join([index_to_word.get(i, '?') for i in x_train[0]])
print(decoded_sample)
  • 인덱스에 +3 보정
  • TF-IDF, CountVectorizer 변환 전 텍스트 복원 가능

3. 텍스트 벡터화

from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer

# CountVectorizer로 DTM 생성
dtmvector = CountVectorizer()
x_train_dtm = dtmvector.fit_transform(x_train_texts)  # x_train_texts: 복원된 텍스트 리스트

# TF-IDF 변환
tfidf_transformer = TfidfTransformer()
tfidfv = tfidf_transformer.fit_transform(x_train_dtm)
  • 훈련 데이터로 fit → 테스트 데이터는 transform 만 수행

4. 머신러닝 모델 학습 및 평가

4.1 Multinomial Naive Bayes

from sklearn.naive_bayes import MultinomialNB

model = MultinomialNB()
model.fit(tfidfv, y_train)

4.2 Complement Naive Bayes

from sklearn.naive_bayes import ComplementNB

cb = ComplementNB()
cb.fit(tfidfv, y_train)

4.3 Logistic Regression

from sklearn.linear_model import LogisticRegression

lr = LogisticRegression(C=10000, penalty='l2', max_iter=3000)
lr.fit(tfidfv, y_train)

4.4 Decision Tree

from sklearn.tree import DecisionTreeClassifier

tree = DecisionTreeClassifier(max_depth=10, random_state=0)
tree.fit(tfidfv, y_train)

4.5 Random Forest

from sklearn.ensemble import RandomForestClassifier

rf = RandomForestClassifier(random_state=0)
rf.fit(tfidfv, y_train)

4.6 Gradient Boosting

from sklearn.ensemble import GradientBoostingClassifier

grbt = GradientBoostingClassifier(random_state=0)
grbt.fit(tfidfv, y_train)

4.7 LinearSVC

from sklearn.svm import LinearSVC

svc = LinearSVC(max_iter=3000, random_state=0)
svc.fit(tfidfv, y_train)

4.8 SGDClassifier (예시)

from sklearn.linear_model import SGDClassifier

sgd_clf = SGDClassifier(loss='log_loss', max_iter=1000, tol=1e-3, random_state=0)
sgd_clf.fit(tfidfv, y_train)

5. Voting Classifier (Soft Voting 앙상블)

from sklearn.ensemble import VotingClassifier

voting_classifier = VotingClassifier(
    estimators=[('lr', lr), ('cnb', cb), ('gbc', grbt)],
    voting='soft'
)
voting_classifier.fit(tfidfv, y_train)

 

 

모델명 정확도 (Accuracy)

RandomizedSearchCV 튜닝 후 약 83.3%
Logistic Regression 약 80.9%
SGDClassifier 약 79.8%
VotingClassifier 약 79.5%
LinearSVC 약 78.8%
Complement Naive Bayes 약 77.1%
Gradient Boosting Classifier 약 76.6%
Random Forest Classifier 약 67.4%
Multinomial Naive Bayes 약 65.7%
Decision Tree Classifier 약 64.5%

 

 


6. 평가 지표 및 혼동 행렬

from sklearn.metrics import classification_report, confusion_matrix

y_pred = voting_classifier.predict(tfidf_transformer.transform(dtmvector.transform(x_test_texts)))

print(classification_report(y_test, y_pred, zero_division=0))

cm = confusion_matrix(y_test, y_pred)
import seaborn as sns
import matplotlib.pyplot as plt

sns.heatmap(cm, annot=True, fmt="d")
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
plt.show()

7. 주요 개념 정리

  • Accuracy, Precision, Recall, F1-score 개념과 공식
  • F1-score는 Precision과 Recall의 조화평균, 불균형 데이터에 중요
  • 테스트 데이터 변환 시 반드시 transform()만 사용해야 일관성 유지
  • 서포트 벡터 머신의 서포트 벡터는 결정 경계에 가장 가까운 데이터 포인트
  • 결정 트리의 max_depth로 모델 복잡도 조절
  • 랜덤 포레스트가 결정 트리의 과적합과 불안정성 문제를 해결
  • ComplementNB는 불균형 데이터에 강점이 있음