2014-11-12 2 views
2

scikit-learn을 사용하여 여러 텍스트 문서에서 ngrams을 작성합니다. 도큐멘트 번호countVectorizer을 사용하여 구축해야합니다.scikit learn과 count vectorizer에서 ngram을 생성합니다. 메모리 오류

: 나는 데이터의 엄청난 양의 시도 할 때

document1 = "john is a nice guy" 

document2 = "person can be a guy" 

그래서, 문서 주파수 여기

{'be': 1, 
'can': 1, 
'guy': 2, 
'is': 1, 
'john': 1, 
'nice': 1, 
'person': 1} 

문서는 단지 문자열 수 있지만 것입니다. MEMORY ERROR가 발생합니다.

코드 :

import numpy as np 
from sklearn.feature_extraction.text import CountVectorizer 
document = [Huge amount of data around 7MB] # ['john is a guy', 'person guy'] 
vectorizer = CountVectorizer(ngram_range=(1, 5)) 
X = vectorizer.fit_transform(document).todense() 
tranformer = vectorizer.transform(document).todense() 
matrix_terms = np.array(vectorizer.get_feature_names()) 
lst_freq = map(sum,zip(*tranformer.A))   
matrix_freq = np.array(lst_freq) 
final_matrix = np.array([matrix_terms,matrix_freq]) 

ERROR : 당신이 조밀 한 형식으로 대형 스파 스 매트릭스를 변환 할 때 코멘트가 언급 한 것처럼

Traceback (most recent call last): 
    File "demo1.py", line 13, in build_ngrams_matrix 
    X = vectorizer.fit_transform(document).todense() 
    File "/usr/local/lib/python2.7/dist-packages/scipy/sparse/base.py", line 605, in todense 
    return np.asmatrix(self.toarray(order=order, out=out)) 
    File "/usr/local/lib/python2.7/dist-packages/scipy/sparse/compressed.py", line 901, in toarray 
    return self.tocoo(copy=False).toarray(order=order, out=out) 
    File "/usr/local/lib/python2.7/dist-packages/scipy/sparse/coo.py", line 269, in toarray 
    B = self._process_toarray_args(order, out) 
    File "/usr/local/lib/python2.7/dist-packages/scipy/sparse/base.py", line 789, in _process_toarray_args 
    return np.zeros(self.shape, dtype=self.dtype, order=order) 
MemoryError 
+2

당신이 확인 되세요 http://stackoverflow.com/questions을/16332083/python-memoryerror-when-fitting-with-scikit-learn 또는 http://stackoverflow.com/questions/23879139/memory-error-at-python-while-converting-to-array? – fredtantini

+0

'MEMORY ERROR'을 생성하는 동안'todense() '를 사용한다고 생각합니다. 그러나'todense() '를 사용하지 않으면'sparse matrix'에서 결과를 얻습니다. 그 드문 드문 행렬을 읽는 것을 나는 모른다. 어떤 도움 plz? – iNikkz

+0

스파 스 매트릭스를 실제로보고 싶다면 'X [: 10, :]. todense()'와 같이 작은 행 (예 : 처음 10 행)을 살펴볼 수 있습니다. 합계와 같은 대부분의 다른 연산은 희소하고 밀도가 높은 행렬에 대해 같은 방식으로 작동하므로 실제로 todense/A/toarray를 호출 할 필요가 없습니다. – mbatchkarov

답변

9

, 당신은 메모리 문제로 실행중인 .

import numpy as np 
from sklearn.feature_extraction.text import CountVectorizer 
document = [Huge amount of data around 7MB] # ['john is a guy', 'person guy'] 
vectorizer = CountVectorizer(ngram_range=(1, 5)) 

# Don't need both X and transformer; they should be identical 
X = vectorizer.fit_transform(document) 
matrix_terms = np.array(vectorizer.get_feature_names()) 

# Use the axis keyword to sum over rows 
matrix_freq = np.asarray(X.sum(axis=0)).ravel() 
final_matrix = np.array([matrix_terms,matrix_freq]) 

편집 :이 같은 시도는 주파수 용어에서 사전을 원하는 경우, fit_transform를 호출 한 후이 시도 :

terms = vectorizer.get_feature_names() 
freqs = X.sum(axis=0).A1 
result = dict(zip(terms, freqs)) 
+0

감사합니다. @perimosocordiae. fit_transform()을 사용하는 것이 좋습니다. – iNikkz

+0

'@ perimosocordiae' : 도움이 더 필요합니다. 'final_matrix'는 행렬입니다. 이제 저는 이것을'빠른 '방식으로'사전'으로 변환하고 싶습니다. 나는'dict (zip (final_matrix [0], final_matrix [1]))'this를 사용했습니다. 하지만 몇 초 안에 시간이 걸립니다. 행렬을 사전으로 변환하는 다른 방법은 없습니까? – iNikkz

+1

훨씬 빠를 지 모르겠습니다 만 원하는 사전을 만드는 방법을 보여줄 수 있도록 답변을 업데이트했습니다. – perimosocordiae

관련 문제