我正在努力在 Python 中使用 Scikit learn 中的随机森林。我的问题是我将它用于文本分类(在 3 个类中 - 正/负/中性)并且我提取的特征主要是单词/unigrams,所以我需要将这些转换为数字特征。我找到了一种方法来做到这一点DictVectorizer
's fit_transform
:
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer(sparse=False)
rf = RandomForestClassifier(n_estimators = 100)
trainFeatures1 = vec.fit_transform(trainFeatures)
# Fit the training data to the training output and create the decision trees
rf = rf.fit(trainFeatures1.toarray(), LabelEncoder().fit_transform(trainLabels))
testFeatures1 = vec.fit_transform(testFeatures)
# Take the same decision trees and run on the test data
Output = rf.score(testFeatures1.toarray(), LabelEncoder().fit_transform(testLabels))
print "accuracy: " + str(Output)
我的问题是该fit_transform
方法正在处理包含大约 8000 个实例的训练数据集,但是当我尝试将我的测试集也转换为数字特征(大约 80000 个实例)时,我收到一个内存错误说:
testFeatures1 = vec.fit_transform(testFeatures)
File "C:\Python27\lib\site-packages\sklearn\feature_extraction\dict_vectorizer.py", line 143, in fit_transform
return self.transform(X)
File "C:\Python27\lib\site-packages\sklearn\feature_extraction\dict_vectorizer.py", line 251, in transform
Xa = np.zeros((len(X), len(vocab)), dtype=dtype)
MemoryError
什么可能导致这种情况,是否有任何解决方法?非常感谢!