【发布时间】:2018-10-27 10:57:58
【问题描述】:
我刚开始学习 Python。我正在使用 API 来构建 IDF 模型,但是我遇到了一些无法解决的 lambda 函数错误。 这是生成 IDF 的类:
class Idfs(DocumentFrequencies, Model):
def build(self, corpus):
log.info('Counting documents in corpus...')
N = float(corpus.count())
dfs = super(Idfs, self).build(corpus)
log.info('Building idf model: N=%i', N)
return dfs\
.map(lambda (term, (df,rank)): (term, df))\
.mapValues(lambda df: math.log(N/df))
@staticmethod
def format_item((term, idf)):
return {
'_id': term,
'idf': idf,
}
这是计算 DF 的类:
class DocumentFrequencies(ModelBuilder):
def __init__(self, lowercase=False, max_ngram=1, min_df=2):
self.lowercase = lowercase
self.max_ngram = max_ngram
self.min_df = min_df
def build(self, docs):
m = docs.map(lambda d: d['text'])
if self.lowercase:
m = m.map(lambda text: text.lower())
return m\
.flatMap(lambda text: set(ngrams(text, self.max_ngram)))\
.map(lambda t: (t, 1))\
.reduceByKey(add)\
.filter(lambda (k,v): v > self.min_df)
错误出现在这一行.map(lambda (term, (df, rank)): (term, df))\,这是错误信息:
TypeError: 'int' object is not iterable
这是我打电话给DocumentFrequencies.collect()时得到的:
Out[5]:
[(u'fawn', 3),
(u'1,800', 31),
(u'clotted', 3),
(u'comically', 11),
(u'Adjusting', 3),
(u'O(log', 6),
(u'unnecessarily', 15),
(u'evangelical', 53),
(u'naturopathic', 3),
(u'grenadiers', 4),
(u'stipulate', 4),
(u'Vikrant', 3),
(u'fractal', 18),
我不知道究竟是哪个参数导致了错误。我正在使用具有 2 个内核的 python 2.7、8 GB 1600 MHz DDR。这些是 pyspark 配置:
conf = pyspark.SparkConf().setAll([('spark.executor.memory', '8g'),('spark.driver.memory','8g'),('spark.network.timeout','100000000s'),('spark.executor.heartbeatInterval','10000000s'),('spark.driver.maxResultSize','8g'),('spark.driver.cores','2')])
提前致谢,
【问题讨论】:
-
我不熟悉 Idfs 和 Dfs,但看起来
dfs变量不是可迭代的。例如,列表和字符串是可以迭代的可迭代对象。请登录dfs一次,看看你得到了什么。 -
如错误中所述,您正在传递不可迭代的 int 值。检查输入。
-
@nightgaunt 我尝试记录它,而我得到的
12:03:54,896|INFO|text|PythonRDD[32] at RDD at PythonRDD.scala:48不是很有用。知道如何打印实际输出吗? -
如果
dfs是 RDD,那么 map 应该可以工作。您可以尝试dfs.collect()并登录。您还可以添加完整的跟踪吗?现在我感觉它可能不是发生错误的地方 -
@nightgaunt 但如果我将 api 方法编辑为
.map(lambda (term, df): (term,df))不会使这条线没用吗?我也不知道rank值应该来自哪里?如图所示dfs只产生term和df。
标签: python python-2.7 apache-spark pyspark typeerror