2017-12-19 24 views
1

ngrams를 사용하여 남성과 여성의 이름을 분류하는 작업을하십시오. 내가 만든 (N = 2,3,4)Python에서 CountVectorizer와 ngram을 결합하십시오.

name is_male 
Dorian  1 
Jerzy  1 
Deane  1 
Doti  0 
Betteann 0 
Donella  0 

특정 requarement이 ngrams을 만들려면이 작업

from nltk.util import ngrams 

을 사용하는 것입니다 : 그래서 는 dataframe 같이가 이름 목록, 사용 된 ngrams :

from nltk.util import ngrams 
from sklearn.feature_extraction.text import CountVectorizer 
count_vect = CountVectorizer() 

test_ngrams = [] 
for name in name_list: 
    test_ngrams.append(list(ngrams(name,3))) 

이제 어떻게 든이 모든 것을 c에 사용할 수 있도록 벡터화해야합니다. 누군가가 내가 할 방법을 설명해주십시오 수

AttributeError: 'list' object has no attribute 'lower' 

내가 목록 입력의 잘못된 유형이 여기에 이해, 그래서 나중에 MultinomialNB를 사용할 수 있습니다 lassification, 나는

X_train = count_vect.fit_transform(test_ngrams) 

받으십시오 시도 예. 나는 그것을 올바른 방법으로하고 있는가? 미리 감사드립니다.

+0

어떤 남성과 여성 모두 이름에 대한? 아마 1 대신 (is_male, is_female) 2 개의 기능을 갖는 것이 좋습니다. – sergzach

답변

1

AttributeError을받는 이유는 벡터 라이저의 시퀀스를 전달하기 때문입니다. 대신, 문자열의 반복 가능을 전달해야합니다. CountVectorizerdocumentation에서 :

fit_transform (Y raw_documents = 없음)

는 어휘 사전을 학습과 장기 - 문서 행렬을 반환한다.

이것은 fit 다음에 transform이있는 것과 같지만보다 효율적으로 구현됩니다.

매개 변수 :raw_documents :

STR, 유니 코드 또는 파일 객체 중 하나를 얻을 수있는 반복 가능한 반복자.

귀하의 질문에 대답하기 위해, CountVectorizerngram_range를 사용하여 N-그램을 만들 수있다 (다음은 bigrams을 생산) :

count_vect = CountVectorizer(ngram_range=(2,2)) 

corpus = [ 
    'This is the first document.', 
    'This is the second second document.', 
] 
X = count_vect.fit_transform(corpus) 

print(count_vect.get_feature_names()) 
['first document', 'is the', 'second document', 'second second', 'the first', 'the second', 'this is'] 

업데이트 :

당신 때문에 당신이 을 가지고 있다고 말하면은 NLTK를 사용하여 ngram을 생성해야합니다. f는 CountVectorizer의 기본 동작입니다.

분석기 : 즉, analyzer 이는 특징으로 원시 문자열 변환 문자열 { '워드', '문자', 'char_wb'} 또는 호출

[...]

호출 가능 인수가 전달되면 처리되지 않은 원시 입력에서 일련의 기능 을 추출하는 데 사용됩니다. 우리는 이미 ngrams을 제공하기 때문에

, 식별 기능은 충분하다 :

count_vect = CountVectorizer(
    analyzer=lambda x:x 
) 

완벽한 예 결합 NLTK의 ngrams 및 CountVectorizer을 :

corpus = [ 
    'This is the first document.', 
    'This is the second second document.', 
] 

def build_ngrams(text, n=2): 
    tokens = text.lower().split() 
    return list(nltk.ngrams(tokens, n)) 

corpus = [build_ngrams(document) for document in corpus] 

count_vect = CountVectorizer(
    analyzer=lambda x:x 
) 

X = count_vect.fit_transform(corpus) 
print(count_vect.get_feature_names()) 
[('first', 'document.'), ('is', 'the'), ('second', 'document.'), ('second', 'second'), ('the', 'first'), ('the', 'second'), ('this', 'is')] 
+0

답변 해 주셔서 감사합니다! 나는이 작업을 위해 CountVectorizer만을 사용했다. nltk에서 ngrams를 사용하는 것은 작업의 일부분이므로 함께 결합하는 방법을 모르겠습니다. –

+0

@AlexNikitin 알겠습니다. 질문을 특정 요구 사항으로 업데이트 해주십시오. –

+0

업데이트 됨. 유일한 요구 사항은 'nltk.util import ngrams'를 사용하여이 작업을 수행하는 것입니다. 감사! –