使用cv.fit_transform(corpus).toarray()

时间:2017-06-06 06:45:42

标签: python twitter scikit-learn

enter image description here如果有人可以帮助cv.fit_transform(corpus).toarray()来处理大小约为732066 x <140(推文)的语料库,我将不胜感激。文本已被清理以减少功能和维度,但我一直收到错误

这是我开始的方式

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd


# Importing the dataset
cols = ["text","geocoordinates0","geocoordinates1","grid"]
dataset = pd.read_csv('tweets.tsv', delimiter = '\t', usecols=cols, quoting = 3, error_bad_lines=False, low_memory=False)

# Removing Non-ASCII characters
def remove_non_ascii_1(dataset):
    return ''.join([i if ord(i) < 128 else ' ' for i in dataset])

# Cleaning the texts
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 732066):
    review = re.sub('[^a-zA-Z]', ' ', str(dataset['text'][i]))
    review = review.lower()
    review = review.split()
    ps = PorterStemmer()
    review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
    review = ' '.join(review)
    corpus.append(review)

# Creating the Bag of Words model
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, 3].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Applying k-Fold Cross Validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)
accuracies.mean()
accuracies.std()

以下是输出错误:

  

X = cv.fit_transform(corpus).toarray()Traceback(最近一次调用   最后):

     

文件&#34;&#34;,第1行,in       X = cv.fit_transform(语料库).toarray()

     

文件   &#34; C:\ Anaconda3 \ ENVS \ py35 \ lib中\站点包\ SciPy的\稀疏\ compressed.py&#34 ;,   第920行,在toarray       return self.tocoo(copy = False).toarray(order = order,out = out)

     

文件   &#34; C:\ Anaconda3 \ ENVS \ py35 \ lib中\站点包\ SciPy的\稀疏\ coo.py&#34 ;,   第252行,在toarray中       B = self._process_toarray_args(order,out)

     

文件   &#34; C:\ Anaconda3 \ ENVS \ py35 \ lib中\站点包\ SciPy的\稀疏\ base.py&#34 ;,   第1009行,位于_process_toarray_args中       return np.zeros(self.shape,dtype = self.dtype,order = order)

     

的MemoryError

非常感谢!

PS:根据@Kumar的建议删除arraylist并使用MultinomiaNB后,我现在有以下错误:

from sklearn.naive_bayes import MultinomialNB 
classifier = MultinomialNB()
classifier.fit(X_train, y_train)
  

追踪(最近一次呼叫最后一次):

     

文件&#34;&#34;,第1行,in       classifier.fit(X_train,y_train)

     

文件   &#34; C:\ Anaconda3 \ ENVS \ py35 \ lib中\站点包\ sklearn \ naive_bayes.py&#34 ;,   第566行,合适       Y = labelbin.fit_transform(y)

     

文件   &#34; C:\ Anaconda3 \ ENVS \ py35 \ lib中\站点包\ sklearn \ base.py&#34 ;,   第494行,在fit_transform中       return self.fit(X,** fit_params).transform(X)

     

文件   &#34; C:\ Anaconda3 \ ENVS \ py35 \ lib中\站点包\ sklearn \预处理\ label.py&#34 ;,   第296行,合适       self.y_type_ = type_of_target(y)

     

文件   &#34; C:\ Anaconda3 \ ENVS \ py35 \ lib中\站点包\ sklearn \ utils的\ multiclass.py&#34 ;,   第275行,在type_of_target中       if(len(np.unique(y))&gt; 2)或(y.ndim&gt; = 2和len(y [0])&gt; 1):

     

文件   &#34; C:\ Anaconda3 \ ENVS \ py35 \ lib中\站点包\ numpy的\ lib中\ arraysetops.py&#34 ;,   第198行,独一无二       ar.sort()

     

TypeError:unorderable类型:str()&gt;浮动()

1 个答案:

答案 0 :(得分:1)

我只是说,删除.toarray()并用MultinomialNB替换GaussianNB。

.... 
....
# Other code
....
....

X = cv.fit_transform(corpus)
y = dataset.iloc[:, 3].values

# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

.... 
....
# Other code