使用Scikit-learn对预处理的文本进行分词

2024-05-23 17:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近创建了一个hadoop作业,它接受数千个文本文件并执行一些基本的文本处理。当工作完成后,我有两个输出文件,我用它们来训练积极和消极的情绪。两个文件如下所示:

word1 num_出现次数

wordN num_出现次数

我想使用sci工具包学习使用支持向量机进行分类,但我不确定如何分类,因为我不确定如何正确标记我的数据集。所有教程都假定您正在向sklearn.feature_extraction.text.CountVectorizer提供原始文本文件,并且没有进行任何预处理。我也尝试过使用FeatureHasher,但它不是散列一个单词和创建一个稀疏矩阵,而是为我传递的每个字符创建一个散列。在

也就是说,有没有人知道在我当前的输出文件中提取特征并将其传递给机器学习算法的最佳方法吗?谢谢!在


Tags: 文件hadoop工具包作业分类次数向量num
2条回答

看看TfidfTransformer。在

由于您使用的是文本特征,TF-IDF representation将为每个特征(单词)分配一个表示其在文本中重要性的数字。这种表示在基于文本的分类中非常常见。在

tfiddtransformer将输出一个矩阵,其中包含文件中使用的所有单词,每行代表一个文档,行中的每个单元格表示一个功能(单词),单元格中的值表示该功能的重要性。在

确保以适当的格式(矩阵)将字数统计数据传递给它,然后使用此TfidfTtransformer的输出可以训练分类器。在

(到目前为止,我还没有使用过它,只有矢量器版本,但我看到过它可以实现您想要的功能的场景)。在

你也许能帮上忙。在

import numpy as np
import copy
from numpy import *
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import LinearSVC
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.multiclass import OneVsRestClassifier
from sklearn import preprocessing

x_temp_list = []
y_temp_list = []
y_train_text = []
temp_list = []
another_temp_list = []

with open('newtrain.csv','r') as fp:
    lines = fp.readlines()

for line in lines:
    if len(line.strip()) > 1:
        fields = line.split(',')
        if len(line.split(',')) == 2:
            x_temp_list.append(fields[0].strip())
            y_temp_list.append(fields[1].strip())

X_train = np.array(x_temp_list)
y_train_text = np.array(y_temp_list)

X_test = np.array(['Barista'])

mlb = preprocessing.LabelBinarizer()
Y = mlb.fit_transform(y_train_text)

classifier = Pipeline([
    ('vectorizer', CountVectorizer()),
    ('tfidf', TfidfTransformer()),
    ('clf', OneVsRestClassifier(LinearSVC()))])

classifier.fit(X_train, Y)
predicted = classifier.predict(X_test)
all_labels = mlb.inverse_transform(predicted)
#all_labels = lb.inverse_transform(predicted)

for item, labels in zip(X_test, all_labels):
    print '%s => %s' % (item, labels)

相关问题 更多 >