데이터 분포 확인: 각 특성(Feature)의 분포를 시각화 (히스토그램, 박스 플롯 등).
결측치 확인: df.isnull().sum() 등으로 결측치의 수와 위치 파악.
이상치 확인: 박스 플롯이나 산점도 등으로 극단적인 값 확인.
타겟 변수 분포 확인: 분류 문제의 경우 클래스별 데이터 불균형 확인.
특성 간 관계 분석: 산점도 행렬(Scatter Matrix), 상관관계 히트맵(Correlation Heatmap) 등으로 특성 간의 관계 파악.
텍스트 데이터의 경우: 단어 빈도 분석, 워드 클라우드, 문장 길이 분포 등.
# EDA 예시 (Pandas, Matplotlib, Seaborn 사용)
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# CSV 파일 로드 가정
# df = pd.read_csv('your_data.csv')
# --- 예시 데이터 생성 (실제로는 수집한 데이터 사용) ---
data_dict = {
'text': [
"This movie is great and wonderful!",
"Absolutely terrible film, I hated it.",
"Not bad, but could have been better.",
"An amazing masterpiece of cinema.",
None, # 결측치 예시
"Just okay, nothing special to write home about."
],
'sentiment': [1, 0, 0, 1, 1, 0], # 1: 긍정, 0: 부정
'rating': [5, 1, 3, 5, 4, 3] # 1-5점 척도
}
df = pd.DataFrame(data_dict)
# --- 예시 데이터 생성 끝 ---
print("데이터 샘플:")
print(df.head())
print("\n데이터 정보:")
df.info()
print("\n수치형 데이터 기술 통계:")
print(df.describe())
print("\n결측치 확인:")
print(df.isnull().sum())
# 타겟 변수 분포 (분류 문제의 경우)
if 'sentiment' in df.columns:
plt.figure(figsize=(6, 4))
sns.countplot(x='sentiment', data=df)
plt.title('Sentiment Distribution')
plt.show()
# 텍스트 길이 분포 (텍스트 데이터의 경우)
if 'text' in df.columns:
df['text_length'] = df['text'].astype(str).apply(len) # 결측치 때문에 str로 변환 후 길이 계산
plt.figure(figsize=(8, 5))
sns.histplot(df['text_length'], kde=True)
plt.title('Distribution of Text Length')
plt.show()
# (선택) 워드 클라우드 (텍스트 데이터)
# from wordcloud import WordCloud
# if 'text' in df.columns:
# all_text = " ".join(review for review in df['text'].astype(str) if review) # 결측치 제외
# if all_text:
# wordcloud = WordCloud(width=800, height=400, background_color='white').generate(all_text)
# plt.figure(figsize=(10, 5))
# plt.imshow(wordcloud, interpolation='bilinear')
# plt.axis("off")
# plt.title("Word Cloud of Reviews")
# plt.show()
토큰화: 단어 또는 형태소 단위로 분리 (영어: NLTK, spaCy / 한국어: KoNLPy).
불용어 제거: 의미 없는 단어 제거.
어간 추출 (Stemming) 또는 표제어 추출 (Lemmatization): 단어의 기본형으로 통일.
# 텍스트 전처리 예시 (간단화)
import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# nltk.download('punkt') # 최초 실행 시
# nltk.download('stopwords') # 최초 실행 시
stop_words = set(stopwords.words('english'))
def preprocess_text(text):
if pd.isnull(text): # 결측치 처리
return ""
text = text.lower() # 소문자화
text = re.sub(r'<[^>]+>', '', text) # HTML 태그 제거
text = re.sub(r'[^a-z\s]', '', text) # 알파벳과 공백 외 문자 제거
tokens = word_tokenize(text) # 토큰화
tokens = [word for word in tokens if word not in stop_words and len(word) > 1] # 불용어 및 한 글자 단어 제거
# (선택) 표제어 추출 등 추가 가능
return " ".join(tokens)
if 'text' in df.columns:
df['processed_text'] = df['text'].apply(preprocess_text)
print("\n전처리된 텍스트 샘플:")
print(df[['text', 'processed_text']].head())
전처리된 데이터를 모델 학습용(Train Set)과 평가용(Test Set)으로 분리합니다.
sklearn.model_selection.train_test_split
주의: 데이터 분할은 모든 전처리(특히 스케일링, 인코딩 등)가 완료된 후, 또는 학습 데이터에 대해서만 fit하고 테스트 데이터에는 transform만 적용하는 방식으로 수행되어야 데이터 누수(Data Leakage)를 방지할 수 있습니다. (Pipeline 사용 권장)
Day 89: 프로젝트를 위한 탐색적 데이터 분석 (EDA) 심화 및 특징 공학 (Exploratory Data Analysis (EDA) for the project and Feature Engineering) - 수집/전처리된 데이터에 대한 심층적인 분석과 모델 성능 향상을 위한 특징 생성.