我想使用train将文本文档转换成特征向量,然后训练一种朴素贝叶斯算法来对它们进行分类。
我可以轻松地在没有标签的情况下加载文本文件,并使用HashingTF()将其转换为向量,然后使用IDF()根据单词的重要性对它们进行加权。但是如果我这样做了,我就去掉了标签,似乎不可能把标签和向量重新组合,即使顺序是一样的。
另一方面,我可以在每个文档上调用HashingTF()并保留标签,但是我不能在它上调用IDF(),因为它需要完整的文档集(标签就会碍事)。
朴素贝叶斯的星火文档只有一个例子,其中的点已经被标记和矢量化了,所以这没有多大帮助。
我也看过这个指南:model,但在这里,他只对每个文档应用散列函数,而不使用以色列国防军。
因此,我的问题是,是否有一种方法,不仅矢量化,而且重量的词使用以色列国防军为天真的贝叶斯分类器?主要的问题似乎是火花坚持只接受labeledPoints的rdd作为NaiveBayes的输入。
def parseLine(line):
label = row[1] # the label is the 2nd element of each row
features = row[3] # the text is the 4th element of each row
features = tokenize(features)
features = hashingTF.transform(features)
return LabeledPoint(label, features)
labeledData = data1.map(parseLine)发布于 2015-08-26 16:16:22
标准的PySpark方法(拆分-> transform -> zip)似乎工作得很好:
from pyspark.mllib.feature import HashingTF, IDF
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import NaiveBayes
training_raw = sc.parallelize([
{"text": "foo foo foo bar bar protein", "label": 1.0},
{"text": "foo bar dna for bar", "label": 0.0},
{"text": "foo bar foo dna foo", "label": 0.0},
{"text": "bar foo protein foo ", "label": 1.0}])
# Split data into labels and features, transform
# preservesPartitioning is not really required
# since map without partitioner shouldn't trigger repartitiong
labels = training_raw.map(
lambda doc: doc["label"], # Standard Python dict access
preservesPartitioning=True # This is obsolete.
)
tf = HashingTF(numFeatures=100).transform( ## Use much larger number in practice
training_raw.map(lambda doc: doc["text"].split(),
preservesPartitioning=True))
idf = IDF().fit(tf)
tfidf = idf.transform(tf)
# Combine using zip
training = labels.zip(tfidf).map(lambda x: LabeledPoint(x[0], x[1]))
# Train and check
model = NaiveBayes.train(training)
labels_and_preds = labels.zip(model.predict(tfidf)).map(
lambda x: {"actual": x[0], "predicted": float(x[1])})要获得一些统计数据,可以使用MulticlassMetrics
from pyspark.mllib.evaluation import MulticlassMetrics
from operator import itemgetter
metrics = MulticlassMetrics(
labels_and_preds.map(itemgetter("actual", "predicted")))
metrics.confusionMatrix().toArray()
## array([[ 2., 0.],
## [ 0., 2.]])相关
https://stackoverflow.com/questions/32231049
复制相似问题