Data Analysis & ML/Text Mining

[Text Mining][텍스트마이닝][NLP] Feature Vectorize(TF-IDF, TfidfVectorizer)

YSY^ 2020. 9. 15. 18:39

TF-IDF (Term Frequency - Inverse Document Frequency)

  • 개별 문서에 많이 나오는 단어가 높은 값을 가지도록 하되 동시에 여러 문서에 자주 나오는 단어에는 페널티를 주는 방식
  • 어떤 문서에 특정 단어가 많이 나오면 그 단어는 해당 문서를 설명하는 중요한 단어일 수 있다. 그러나 그 단어가 다른 문서에도 많이 나온다면 언어 특성이나 주제상 많이 사용되는 단어 일 수 있다.
    • 전체 문서에 고르게 많이 나오는 단어들은 각각의 문서가 다른 문서와 다른 특징을 찾는데 도움이 안된다. 그래서 페널티를 주어 작은 값이 되도록 한다.
  • 각 문서의 길이가 길고 문서개수가 많은 경우 Count 방식 보다 TF-IDF 방식이 더 좋은 예측 성능을 내는 경우가 많다.

공식

  • TF (Term Frequency) : 해당 단어가 해당 문서에 몇번 나오는지를 나타내는 지표
  • DF (Document Frequency) : 해당 단어가 몇개의 문서에 나오는지를 나타내는 지표

TfidfVectorizer

주요 생성자 매개변수

  • stop_word :stopword 지정
    • str: "english" - 영문 불용어는 제공됨
    • list: stopword 리스트
  • max_df: 특정 횟수 이상나오는 것은 무시하도록 설정(무시할 횟수/비율 지정)
    • int(횟수), float(비율)
  • min_df: 특정 횟수 이하로 나오는 것은 무시하도록 설정(무시할 횟수/비율 지정)
  • max_features: 최대 token 수
    • 빈도수가 높은 순서대로 정렬 후 지정한 max_features 개수만큼만 사용한다.
  • ngram_range: n_gram 범위 지정
    • n_gram:
    • 튜플 (범위 최소값, 범위 최대값)
    • (1, 2) : 토큰화된 단어를 1개씩 그리고 순서대로 2개씩 묶어서 Feature를 추출

메소드

  • fit(X)
    • 학습
    • 매개변수: 문장을 가진 1차원 배열형태(list, ndarray)
    • Train(훈련) 데이터셋 으로 학습한다. Test 데이터셋은 Train 셋으로 학습한 CountVectorizer를 이용해 변환만 한다.
  • transform(X)
    • DTM 변환
  • fit_transform(X)
    • 학습/변환 한번에 처리
train = ["He really likes football. He wants to be a football player.", 
         "Football is a popular sport in Europe.", 
         "Which country started football?"]
test = ["He really likes baseball. He wants to be a baseball player.", 
        "Baseball is a popular sport in Korea."]
# 텍스트 전처리 함수
import nltk
from nltk.stem import SnowballStemmer
from nltk.corpus import stopwords

def text_preprocessing(documents):
    """documents(매개변수): document 리스트"""
    stemmer = SnowballStemmer("english")
    stop_words = stopwords.words('english')

    return_list = []
    for doc in documents:
        doc = doc.lower()
        tokens = nltk.regexp_tokenize(doc, r'[A-Za-z]+')
        #불용어 처리
        tokens = [token for token in tokens if token not in stop_words]
        #stemming(어간추출)
        tokens = [stemmer.stem(token) for token in tokens]

        return_list.append(' '.join(tokens))

    return return_list
train_pre = text_preprocessing(train)
test_pre = text_preprocessing(test)
train_pre
# ['realli like footbal want footbal player', 'footbal popular sport europ', 'countri start footbal']
from sklearn.feature_extraction.text import TfidfVectorizer

tfidf = TfidfVectorizer()
# train_tfidf  = tfidf.fit_transform(train_pre)
tfidf.fit(train_pre)
train_tfidf = tfidf.transform(train_pre)
test_tfidf = tfidf.transform(test_pre)

 

728x90
반응형