• 카테고리

    질문 & 답변
  • 세부 분야

    데이터 분석

  • 해결 여부

    미해결

vectorizer.get_feature_names() 문의

20.03.29 17:28 작성 조회수 2.19k

1

안녕하세요.

아래와 같이 두 가지 질문 드립니다.

1. 아래와 같이 vocab 변수를 만들 때 train_data_features의 데이터를 지정해주지 않는데 어떻게 vocab 변수는 train_data_features의 feature 데이터를 가지고 있는건가요?

vocab = vectorizer.get_feature_names()

print(len(vocab))

vocab[:10]

아래 파이프라인 과정에서 처리되는건가요?

pipeline = Pipeline([

    ('vect', vectorizer),])

2. 아래 코드 해석 좀 부탁드릴께요..

# 벡터화 된 피처를 확인해 봄
import numpy as np
dist = np.sum(train_data_features, axis=0)
    
for tag, count in zip(vocab, dist):
    print(count, tag)
    
pd.DataFrame(dist, columns=vocab)

답변 6

·

답변을 작성해보세요.

2

안녕하세요. CountVectorizer 에는 여러 기능이 있어요. 

fit, fit_transform 등 위에서 여러 메소드가 있다는 것을 답변드렸는데요.

get_feature_names() 라는 것도 CountVectorizer 에서 사용할 수 있는 메소드 중 하나입니다.

위에서 정의한 CountVectorizer 에 데이터를 넣어주고 fit 혹은 fit_transform 을 하게 되면 벡터화와 함께 사전(get_feature_names)을 생성하게 됩니다.

Genie Lee님의 프로필

Genie Lee

2022.03.21

학생이 이해할 때 까지 차근히 답변해 주시는 박조은 강사님 정말 감사합니다!

1

김기만님의 프로필

김기만

질문자

2020.04.02

네 이제 이해가 되네요ㅜㅜ

이렇게 빨리 자세하게 답변 달아주셔서 정말 감사드립니다.

Genie Lee님의 프로필

Genie Lee

2022.03.21

저도 궁금했는데, 덕분에 이해가 되었어요! 질문 감사합니다!

0

감사합니다 :)

0

김기만님의 프로필

김기만

질문자

2020.04.02

답변 감사한데 제가 궁금한 점은 해결이 안되네요.

fit_transform을 통해서 반환하는 건 이해했구요.

제가 궁금한 부분은  vocab 변수가 어떻게 train_data_features의 데이터를 가지고 있는지가 궁금합니다. 

vocab = vectorizer.get_feature_names()

0

안녕하세요.

기존에 질문주신 내용에 새로운 질문이 추가되었네요.

답변 후에 기존 질문을 수정해서 새로운 질문을 올려주시면 질문이 변경된 것을 확인하기 어렵습니다,

새로운 질문을 올려주실 때는 알림이 오는데 질문을 수정했을 때는 알림이 오지 않습니다.

그래서 새로운 질문을 하실 때는 질문을 새로 작성해 주세요.

dist = np.sum(train_data_features, axis=0)

train_data_features 에는 벡터화된 피처에 있는 단어가 해당 문서에 등장하는지 여부가 있습니다.

등장하면 1, 등장하지 않으면 0 이 표시되는데 해당 숫자를 sum 으로 더하면 전체 문서에서 해당 단어가 등장하는 빈도수를 알 수 있겠죠.

빈도수를 구했다면 사전(vocab)과 묶어서 빈도수를 프린트 해보고

for tag, count in zip(vocab, dist):
    print(count, tag)

위에서 만든 전체 문서에서 해당 단어가 몇 번 등장하는지에 대한 내용을 데이터프레임 형태로 만드는 것입니다.

표형태로 컬럼은 벡터화한 단어사전으로 만들어 준다면 좀 더 보기가 편하기 때문이에요.

pd.DataFrame(dist, columns=vocab)

0

안녕하세요.

해당 코드 아래에 파이프라인으로 fit_transform을 해주게 되는데 해당 과정의 결과로 피처의 목록과 등장여부를 알 수 있습니다.

해당 문서에 대한 단어가 등장하는지에 대한 값과 함께 사전을 볼 수가 있습니다.

또, 파이프라인은 사이킷런의 여러 API 를 한번에 처리할 수 있도록 도와주는 기능입니다. 

예를 들면, 전처리, 벡터화 등을 묶어서 처리가 가능합니다.

%time train_data_features = pipeline.fit_transform(clean_train_reviews) train_data_features

CountVectorizer 는 아래와 같은 메소드 목록을 제공하고 있습니다.

아래 메소드 설명에 보시면  fit_transform 을 하면   term-document matrix 를 반환하는 것을 볼 수 있습니다.

build_analyzer(self)

Return a callable that handles preprocessing, tokenization and n-grams generation.

build_preprocessor(self)

Return a function to preprocess the text before tokenization.

build_tokenizer(self)

Return a function that splits a string into a sequence of tokens.

decode(self, doc)

Decode the input into a string of unicode symbols.

fit(self, raw_documents[, y])

Learn a vocabulary dictionary of all tokens in the raw documents.

fit_transform(self, raw_documents[, y])

Learn the vocabulary dictionary and return term-document matrix.

get_feature_names(self)

Array mapping from feature integer indices to feature name.

get_params(self[, deep])

Get parameters for this estimator.

get_stop_words(self)

Build or fetch the effective stop words list.

inverse_transform(self, X)

Return terms per document with nonzero entries in X.

set_params(self, \*\*params)

Set the parameters of this estimator.

transform(self, raw_documents)

Transform documents to document-term matrix.

아래 문서의 method 부분에 위 목록이 있습니다.

[sklearn.feature_extraction.text.CountVectorizer — scikit-learn 0.22.2 documentation](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html)