python - Pyspark 多标签文本分类

标签 python apache-spark pyspark apache-spark-ml databricks

我正在尝试预测未知文本的标签。我的数据如下所示:

+-----------------+-----------+
|      label      |   text    |
+-----------------+-----------+
| [0, 1, 0, 1, 0] | blah blah |
| [1, 1, 0, 0, 0] | foo bar   |
+-----------------+-----------+

使用多标签二值化方法对第一列进行编码。 我的管道:

tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
lsvc = LinearSVC(maxIter=10, regParam=0.1)
ovr = OneVsRest(classifier=lsvc)

pipeline = Pipeline(stages=[tokenizer, hashingTF, ovr])

model = pipeline.fit(result)

当我运行此代码时,我收到此错误:

ValueError: invalid literal for int() with base 10: '[1, 0, 1, 0, 1, 1, 1, 0, 0]'

有什么问题吗?

最佳答案

查看错误

invalid literal for int()

我们看到问题在于标签的预期类型不是数组,而是与样本类别相对应的单个值。换句话说,您需要将标签从多标签二值化编码转换为单个数字。

一种方法是首先将数组转换为字符串,然后使用 StringIndexer :

to_string_udf = udf(lambda x: ''.join(str(e) for e in x), StringType())
df = df.withColumn("labelstring", to_string_udf(df.label))

indexer = StringIndexer(inputCol="labelstring", outputCol="label")
indexed = indexer.fit(df).transform(df)

这将为每个唯一的数组创建一个单独的类别(类标签)。

关于python - Pyspark 多标签文本分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50361096/

相关文章:

MongoDB pyspark 连接器问题,[错误 13] 权限被拒绝 'home/.cache'

python - 为什么我的 Python 脚本文件夹中有多个 pip 版本?

python - 使用 python 请求进行网页抓取

python 查找并匹配精确的字符串

java - Java 中 int 数组键的 Apache Spark 类?

python - 当 ID 匹配时,在其他 Pyspark Dataframe 中逐列划分 Pyspark Dataframe

python - GA童话世代

sql - (Scala) 在 Apache Spark 中将字符串转换为日期

linux - Pyspark 按目录中的 filtetypes 列出文件

apache-spark - 如何将命名参数发送到 spark-submit