【问题标题】:"expected zero arguments for construction of ClassDict (for numpy.dtype)" when calling UDF that returns FloatType()调用返回 FloatType() 的 UDF 时,“预期构造 ClassDict 的零参数(用于 numpy.dtype)”
【发布时间】:2019-05-16 22:12:04
【问题描述】:

相信和这个有关:Spark Error:expected zero arguments for construction of ClassDict (for numpy.core.multiarray._reconstruct)

我有一个数据框

id col_1 col_2
1 [1,2] [1,3]
2 [2,1] [3,4]

我想在col_1col_2 之间创建另一列cosine

from scipy.spatial.distance import cosine

def cosine_distance(a,b):
    try:
        return cosine(a, b)
    except Exception as e:
        return 0.0 # in case division by zero

我定义了一个udf

cosine_distance_udf = udf (cosine_distance, FloatType())

最后:

new_df = df.withColumn('cosine_distance', cosine_distance_udf('col_1', 'col_2'))

我有错误:PickleException: expected zero arguments for construction of ClassDict (for numpy.dtype)

我做错了什么?

【问题讨论】:

  • 如果你这样做return float(cosine(a, b))怎么办?
  • @coldspeed 难以置信,它运作良好。非常感谢。
  • 我写了一个例子并解释了原因。此外,这可能是重复的,但我认为它不是那个特定问题的重复,@ArnonRotem-Gal-Oz
  • @coldspeed 看来你是对的 - 我删除了近距离投票

标签: python dataframe pyspark pyspark-sql


【解决方案1】:

查看cosine的返回类型,错误原因就清楚了:

type(cosine([1, 2], [1, 3]))
# numpy.float64

但是,np.float64float 的子类:

issubclass(np.float64, float)
# True

因此,对您的功能稍作改动,

def cosine_distance(a, b):
    try:
        return float(cosine(a, b)) # cosine(a, b).item()
    except Exception as e:
        return 0.0 # in case division by zero

这会起作用

df.withColumn('cosine_distance', cosine_distance_udf('col_1', 'col_2')).show()

+------+------+---------------+
| col_1| col_2|cosine_distance|
+------+------+---------------+
|[1, 2]|[3, 4]|     0.01613009|
|[2, 1]|[3, 4]|     0.10557281|
+------+------+---------------+

【讨论】:

    猜你喜欢
    • 2021-07-31
    • 2020-07-25
    • 1970-01-01
    • 2015-07-06
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    相关资源
    最近更新 更多