Python 对新文档进行分类-随机森林、文字袋
这是我第一次尝试使用ML和Python进行文档分类Python 对新文档进行分类-随机森林、文字袋,python,python-3.x,scikit-learn,nlp,Python,Python 3.x,Scikit Learn,Nlp,这是我第一次尝试使用ML和Python进行文档分类 我首先查询我的数据库,提取5000篇与洗钱有关的文章,并将它们转换成数据 然后,我提取了500篇与洗钱无关的文章,并将其转换为反洗钱文件 我将这两个dfs连接起来,并将其标记为“洗钱”或“其他” 我做预处理(删除标点符号和停止字、小写等) 然后根据文字袋原理将模型输入如下: vectorizer = CountVectorizer(analyzer = "word", tokenizer = No
vectorizer = CountVectorizer(analyzer = "word",
tokenizer = None,
preprocessor = None,
stop_words = None,
max_features = 5000)
text_features = vectorizer.fit_transform(full_df["processed full text"])
text_features = text_features.toarray()
labels = np.array(full_df['category'])
X_train, X_test, y_train, y_test = train_test_split(text_features, labels, test_size=0.33)
forest = RandomForestClassifier(n_estimators = 100)
forest = forest.fit(X_train, y_train)
y_pred = forest.predict(X_test)
accuracy_score(y_pred=y_pred, y_true=y_test)
forest.predict(test)
它显然会说:
ValueError: Number of features of the model must match the input. Model n_features is 5000 and input n_features is 45
我不知道如何克服这一点,以便能够对全新的文章进行分类。首先,尽管我的建议可能有效,但我强烈强调,此解决方案具有一些统计和计算结果,在运行此代码之前,您需要了解这些结果。 假设您有一个初始文本语料库
full_df[“已处理的全文”]
,test
是您想要测试的新文本。
然后,让我们用full\u df
和test
定义添加的full\u
文本语料库
text_features = vectorizer.fit_transform(full_added)
text_features = text_features.toarray()
您可以使用full_-df
作为您的列车组(X_-train=full_-df[“已处理全文”]
和y_-train=np.array(full_-df['category'])
)。
然后你就可以跑了
forest = RandomForestClassifier(n_estimators = 100)
forest = forest.fit(X_train, y_train)
y_pred = forest.predict(test)
当然,在这个解决方案中,您已经定义了参数,并且认为模型对新数据具有鲁棒性。p> 另一个注意事项是,如果您有一个新的文本流作为您想要分析的输入,这个解决方案将是可怕的,因为计算新的
矢量器的计算时间。fit_transform(full_added)
将显著增加
我希望有帮助 我的第一个朴素贝叶斯实现来自文本Blob库。速度非常慢,我的机器最终内存不足 第二次尝试基于本文,使用了sklearn.naiver_bayes库中的多项式nb。它就像一个符咒:
#initialize vectorizer
count_vectorizer = CountVectorizer(analyzer = "word",
tokenizer = None,
preprocessor = None,
stop_words = None,
max_features = 5000)
counts = count_vectorizer.fit_transform(df['processed full text'].values)
targets = df['category'].values
#divide into train and test sets
X_train, X_test, y_train, y_test = train_test_split(counts, targets, test_size=0.33)
#create classifier
classifier = MultinomialNB()
classifier.fit(X_train, y_train)
#check accuracy
y_pred = classifier.predict(X_test)
accuracy_score(y_true=y_test, y_pred=y_pred)
#check on completely new example
new_counts = count_vectorizer.transform([processed_test_string])
prediction = classifier.predict(new_counts)
prediction
输出:
array(['money laundering'],
dtype='<U16')
array(['洗钱'],
dtype='vectorize函数将文本语料库映射为(多维)文本空格。您应该检查,但从我的观点来看,由于映射函数依赖于语料库,因此如果您添加的新文本不是来自初始文本语料库,则预期先前的映射对该新文本没有微不足道的意义。这就是为什么在您的情况下,对于真正的新文本,代码不会运行。存在ML/statistical解决问题的方法,但我认为这更像是一个统计挑战,而不是一个编程问题。听起来你在重新装配向量器。记住,你在训练阶段装配向量器和分类器。在预测阶段,你只调用向量器上的transform并预测分类器。@Probaception是的,新文章应该适合模型。否则它没有任何意义。谢谢。是的,这是有意义的。我也同意这不是最好的解决方案,因为每一篇新文章都需要重新计算矩阵。我也尝试过本机贝叶斯,但训练部分太长,最终我的内存耗尽。。。