Tf-Idf 표현

Python으로 배우는 Machine Learning 특성 공학

Robert O'Callaghan

Director of Data Science, Ordergroove

TF-IDF 소개

print(speech_df['Counts_the'].head())
0    21
1    13
2    29
3    22
4    20
Python으로 배우는 Machine Learning 특성 공학

TF-IDF

Python으로 배우는 Machine Learning 특성 공학

벡터라이저 임포트

from sklearn.feature_extraction.text import TfidfVectorizer
tv = TfidfVectorizer()
print(tv)
TfidfVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
        dtype=<type 'numpy.float64'>, encoding=u'utf-8', input=u'content',
        lowercase=True, max_df=1.0, max_features=None, min_df=1,
        ngram_range=(1, 1), norm=u'l2', preprocessor=None, smooth_idf=True,
        stop_words=None, strip_accents=None, sublinear_tf=False,
        token_pattern=u'(?u)\\b\\w\\w+\\b', tokenizer=None, use_idf=True,
        vocabulary=None)
Python으로 배우는 Machine Learning 특성 공학

최대 피처 수와 불용어

tv = TfidfVectorizer(max_features=100, 
                     stop_words='english')

max_features: TF-IDF로 생성할 컬럼 수의 최대값

stop_words: 제외할 일반 단어 목록(예: "and", "the")

Python으로 배우는 Machine Learning 특성 공학

텍스트 학습(fit)

tv.fit(train_speech_df['text'])
train_tv_transformed = tv.transform(train_speech_df['text'])
Python으로 배우는 Machine Learning 특성 공학

모두 합치기

train_tv_df = pd.DataFrame(train_tv_transformed.toarray(),
                           columns=tv.get_feature_names())\
                                 .add_prefix('TFIDF_')

train_speech_df = pd.concat([train_speech_df, train_tv_df], 
                            axis=1, sort=False)
Python으로 배우는 Machine Learning 특성 공학

변환 결과 점검

examine_row = train_tv_df.iloc[0]
print(examine_row.sort_values(ascending=False))
TFIDF_government    0.367430
TFIDF_public        0.333237
TFIDF_present       0.315182
TFIDF_duty          0.238637
TFIDF_citizens      0.229644
Name: 0, dtype: float64
Python으로 배우는 Machine Learning 특성 공학

새 데이터에 벡터라이저 적용

test_tv_transformed = tv.transform(test_df['text_clean'])

test_tv_df = pd.DataFrame(test_tv_transformed.toarray(),
                          columns=tv.get_feature_names())\
                            .add_prefix('TFIDF_')

test_speech_df = pd.concat([test_speech_df, test_tv_df], 
                           axis=1, sort=False)
Python으로 배우는 Machine Learning 특성 공학

연습해 봅시다!

Python으로 배우는 Machine Learning 특성 공학

Preparing Video For Download...