scikit-learn에서 제공하는 자연어 처리 기능들에 대해 알아본다.
feature_extraction
feature_extraction.text
위 두 서브패키지가 문서(글자, 자연어)에 대한 전처리 기능을 제공하고 있다.
DictVectorizer
:A
는 몇개, B
는 몇개 이런식으로 각 문자의 수를 세어놓은 사전 자료형 변수를 입력받아 BOW 인코딩한 수치 벡터로 변환한다.from sklearn.feature_extraction import DictVectorizer v = DictVectorizer(sparse=False) D = [{'A': 1, 'B': 2}, {'B': 3, 'C': 1}] X = v.fit_transform(D) X
출력화면 :
array([[1., 2., 0.], [0., 3., 1.]])
v.feature_names_
출력화면 :
['A', 'B', 'C']
v.transform({'C': 4, 'D': 3})
출력화면 :
array([[0., 0., 4.]])
CountVectorizer
:
문서 집합에서 단어 토큰을 생성하고 각 단어의 수를 세어 BOW 인코딩 벡터를 만든다.
from sklearn.feature_extraction.text import CountVectorizer corpus = [ 'This is the first document.', 'This is the second second document.', 'And the third one.', 'Is this the first document?', 'The last document?', ] vect = CountVectorizer() vect.fit(corpus) vect.vocabulary_
출력화면 :
{'this': 9, 'is': 3, 'the': 7, 'first': 2, 'document': 1, 'second': 6, 'and': 0, 'third': 8, 'one': 5, 'last': 4}
vect.transform(['This is the second document.']).toarray()
출력화면 :
array([[0, 1, 0, 1, 0, 0, 1, 1, 0, 1]])
vect.transform(['Something completely new.']).toarray()
출력화면 :
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
vect.transform(corpus).toarray()
출력화면 :
array([[0, 1, 1, 1, 0, 0, 0, 1, 0, 1], [0, 1, 0, 1, 0, 0, 2, 1, 0, 1], [1, 0, 0, 0, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 0, 0, 0, 1, 0, 1], [0, 1, 0, 0, 1, 0, 0, 1, 0, 0]])
이때 토큰을 어떻게 나눌지, 무시할 토큰의 개수 등을 정할 수 있는 여러 파라미터값들이 존재한다. 해당 부분은 위 링크를 통해 더 자세하게 알아본다.
TfidfVectorizer
:
CountVectorizer와 비슷하지만 TF-IDF 방식으로 단어의 가중치를 조정한 BOW 인코딩 벡터를 만든다. TF-IDF(Term Frequency – Inverse Document Frequency) 인코딩은 단어를 갯수 그대로 카운트하지 않고 모든 문서에 공통적으로 들어있는 단어의 경우 문서 구별 능력이 떨어진다고 보아 가중치를 축소하는 방법이다.
from sklearn.feature_extraction.text import TfidfVectorizer tfidv = TfidfVectorizer().fit(corpus) tfidv.transform(corpus).toarray()
출력화면 :
array([[0. , 0.38947624, 0.55775063, 0.4629834 , 0. , 0. , 0. , 0.32941651, 0. , 0.4629834 ], [0. , 0.24151532, 0. , 0.28709733, 0. , 0. , 0.85737594, 0.20427211, 0. , 0.28709733], [0.55666851, 0. , 0. , 0. , 0. , 0.55666851, 0. , 0.26525553, 0.55666851, 0. ], [0. , 0.38947624, 0.55775063, 0.4629834 , 0. , 0. , 0. , 0.32941651, 0. , 0.4629834 ], [0. , 0.45333103, 0. , 0. , 0.80465933, 0. , 0. , 0.38342448, 0. , 0. ]])
HashingVectorizer
:
해시 함수(hash function)을 사용하여 적은 메모리와 빠른 속도로 BOW 인코딩 벡터를 만든다. CountVectorizer는 모든 작업을 메모리 상에서 수행하므로 처리할 문서의 크기가 커지면 속도가 느려지거나 실행이 불가능해진다. 이 때 HashingVectorizer를 사용하면 해시 함수를 사용하여 단어에 대한 인덱스 번호를 생성하기 때문에 메모리 및 실행 시간을 줄일 수 있다.