【发布时间】:2016-10-19 07:53:53
【问题描述】:
所以,我正在尝试训练一个朴素贝叶斯分类器。在预处理数据时遇到了很多麻烦,我现在已经生成了两个 RDD:
- 训练集:由一组稀疏向量组成;
- 标签:每个向量的对应标签列表 (0,1)。
我需要运行这样的东西:
# Train a naive Bayes model.
model = NaiveBayes.train(training, 1.0)
但“训练”是从跑步中衍生出来的数据集:
def parseLine(line):
parts = line.split(',')
label = float(parts[0])
features = Vectors.dense([float(x) for x in parts[1].split(' ')])
return LabeledPoint(label, features)
data = sc.textFile('data/mllib/sample_naive_bayes_data.txt').map(parseLine)
基于 python here 的文档。我的问题是,鉴于我不想从 txt 文件加载数据,并且我已经以映射到稀疏向量 (RDD) 的记录和相应的标记列表的形式创建了训练集,我该如何运行朴素贝叶斯?
这是我的部分代码:
# Function
def featurize(tokens_kv, dictionary):
"""
:param tokens_kv: list of tuples of the form (word, tf-idf score)
:param dictionary: list of n words
:return: sparse_vector of size n
"""
# MUST sort tokens_kv by key
tokens_kv = collections.OrderedDict(sorted(tokens_kv.items()))
vector_size = len(dictionary)
non_zero_indexes = []
index_tfidf_values = []
for key, value in tokens_kv.iteritems():
index = 0
for word in dictionary:
if key == word:
non_zero_indexes.append(index)
index_tfidf_values.append(value)
index += 1
print non_zero_indexes
print index_tfidf_values
return SparseVector(vector_size, non_zero_indexes, index_tfidf_values)
# Feature Extraction
Training_Set_Vectors = (TFsIDFs_Vector_Weights_RDDs
.map(lambda (tokens): featurize(tokens, Dictionary_BV.value))
.cache())
... 标签只是 1 和 0 的列表。我知道我可能需要以某种方式使用labeledpoint,但我很困惑如何...... RDDs不是一个列表,而labels是一个列表我希望像想出一种简单的方法来创建labeledpoint对象[i]结合 sparse-vectors[i],corresponding-labels[i] 各自的值...有什么想法吗?
【问题讨论】:
标签: python classification pyspark naivebayes