인공지능(21일 오블완)

자연어 처리 프로젝트 따라하기 - 간단한 텍스트 분류 모델 만들기

@thiskorea 2024. 11. 23. 01:13

자연어 처리란?

자연어 처리(NLP, Natural Language Processing)는 텍스트 데이터를 분석하고 이해하여 의미를 추출하는 기술로, AI의 핵심 분야 중 하나입니다. 오늘은 Python의 Scikit-learn을 활용해 텍스트 분류 프로젝트를 진행하며 자연어 처리의 기본 원리를 익혀보겠습니다.


1. 프로젝트 개요

목표

  • 영화 리뷰 데이터를 기반으로, 리뷰가 긍정적인지 부정적인지를 분류하는 모델을 만듭니다.

데이터셋

  • IMDb 영화 리뷰 데이터셋을 사용합니다. 이 데이터셋에는 리뷰와 라벨(긍정/부정)이 포함되어 있습니다.

2. 필수 라이브러리 설치

필요한 라이브러리를 설치합니다.

bash
코드 복사
pip install pandas scikit-learn

3. 데이터 준비

IMDb 데이터셋은 아래 코드를 사용해 간단히 생성할 수 있습니다.

python
코드 복사
import pandas as pd # 간단한 데이터셋 생성 data = { "review": [ "This movie was fantastic! The acting was great and the story was compelling.", "Horrible movie. It was a waste of time and money.", "I loved the cinematography and the direction. A masterpiece!", "The movie was boring and too long. Not recommended.", "Amazing film! It kept me on the edge of my seat the whole time." ], "sentiment": ["positive", "negative", "positive", "negative", "positive"] } df = pd.DataFrame(data) # 데이터 확인 print(df)

출력 결과:

css
코드 복사
review sentiment 0 This movie was fantastic! The acting was great... positive 1 Horrible movie. It was a waste of time and mon... negative 2 I loved the cinematography and the direction.... positive 3 The movie was boring and too long. Not recomme... negative 4 Amazing film! It kept me on the edge of my sea... positive

4. 데이터 전처리

텍스트 데이터를 벡터화하여 머신러닝 모델이 이해할 수 있는 형식으로 변환합니다.

python
코드 복사
from sklearn.feature_extraction.text import CountVectorizer # CountVectorizer로 텍스트 벡터화 vectorizer = CountVectorizer(stop_words='english') X = vectorizer.fit_transform(df['review']) # 텍스트를 벡터로 변환 y = df['sentiment'] # 라벨 print("벡터화된 데이터의 크기:", X.shape)

5. 데이터 분할

훈련 데이터와 테스트 데이터를 나눕니다.

python
코드 복사
from sklearn.model_selection import train_test_split # 데이터 분할 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) print("훈련 데이터 크기:", X_train.shape) print("테스트 데이터 크기:", X_test.shape)

6. 텍스트 분류 모델 학습

로지스틱 회귀(Logistic Regression) 모델을 사용하여 텍스트 분류를 수행합니다.

python
코드 복사
from sklearn.linear_model import LogisticRegression # 모델 초기화 및 학습 model = LogisticRegression() model.fit(X_train, y_train) # 테스트 데이터로 예측 y_pred = model.predict(X_test)

7. 모델 평가

모델의 정확도를 평가합니다.

python
코드 복사
from sklearn.metrics import accuracy_score, classification_report # 정확도 계산 accuracy = accuracy_score(y_test, y_pred) print("모델 정확도:", accuracy) # 분류 보고서 출력 print("\n분류 보고서:") print(classification_report(y_test, y_pred))

8. 새로운 데이터 테스트

새로운 리뷰를 입력하여 감정을 예측해봅니다.

python
코드 복사
new_reviews = [ "The plot was amazing and the characters were so realistic.", "I didn't like the movie. It was poorly directed and very slow." ] # 텍스트 벡터화 new_reviews_vectorized = vectorizer.transform(new_reviews) # 예측 predictions = model.predict(new_reviews_vectorized) for review, sentiment in zip(new_reviews, predictions): print(f"Review: {review}\nPredicted Sentiment: {sentiment}\n")

출력 예시:

vbnet
코드 복사
Review: The plot was amazing and the characters were so realistic. Predicted Sentiment: positive Review: I didn't like the movie. It was poorly directed and very slow. Predicted Sentiment: negative

9. 프로젝트 확장 아이디어

이 프로젝트를 더 발전시키기 위해 다음과 같은 기능을 추가해보세요.

  1. TF-IDF 사용: CountVectorizer 대신 TF-IDF를 사용하여 중요한 단어에 더 높은 가중치를 부여.
  2. 다양한 모델 실험: SVM, Naive Bayes 등 다른 머신러닝 알고리즘 사용.
  3. 실시간 리뷰 감정 분석: 사용자로부터 텍스트를 입력받아 실시간으로 감정을 예측하는 애플리케이션 개발.

결론

이번 프로젝트를 통해 Scikit-learn을 활용한 간단한 텍스트 분류 모델을 구축했습니다. 텍스트 데이터를 벡터화하고, 머신러닝 모델을 학습시키는 과정을 통해 자연어 처리의 기본 개념을 익혔습니다. 다음 단계로 더 큰 데이터셋을 사용하거나, 딥러닝 모델을 활용해 프로젝트를 확장해 보세요.

다음 포스트에서는 AI 프로젝트에서의 윤리적 고려사항을 다루며, AI 개발 과정에서 반드시 신경 써야 할 윤리적 문제와 해결 방안을 살펴보겠습니다.