【发布时间】:2021-12-13 01:53:59
【问题描述】:
我是 pyspark 的新手。
我的数据框:
df = spark.createDataFrame([[10, 8], [3, 5], [1, 3], [1, 5], [2, 8], [8, 7]], list('AB'))
df.show()
+---+---+
| A| B|
+---+---+
| 10| 8|
| 3| 5|
| 1| 3|
| 1| 5|
| 2| 8|
| 8| 7|
+---+---+
通过VectorAssembler将 col'A' & col'B' 转换为向量:
from pyspark.ml.feature import VectorAssembler,Normalizer
Vector = VectorAssembler(inputCols=['A','B'], outputCol="Vector_AB").transform(df)
Normalizer的单位向量_AB:
Vector = Normalizer(inputCol="Vector_AB",outputCol="Unit_AB",p=2).transform(Vector)
+---+---+----------+--------------------+
| A| B| Vector_AB| Unit_AB|
+---+---+----------+--------------------+
| 10| 8|[10.0,8.0]|[0.78086880944303...|
| 3| 5| [3.0,5.0]|[0.51449575542752...|
| 1| 3| [1.0,3.0]|[0.31622776601683...|
| 1| 5| [1.0,5.0]|[0.19611613513818...|
| 2| 8| [2.0,8.0]|[0.24253562503633...|
| 8| 7| [8.0,7.0]|[0.75257669470687...|
+---+---+----------+--------------------+
如何计算Vector_AB的内积? (2个规范)
喜欢,
inputCol:'Vector_AB'-->[10.0,8.0],得到outputCol:Inner_Product_AB-->(10^2+8^2) = 164
我尝试:
Vector = Vector.withColumn('Inner_Product_AB', Vector['A']*Vector['A']+Vector['B']*Vector['B'])
有没有内置函数可以得到这个结果?
我想要的数据框:
+---+---+----------+--------------------+----------------+
| A| B| Vector_AB| Norm_AB|Inner_Product_AB|
+---+---+----------+--------------------+----------------+
| 10| 8|[10.0,8.0]|[0.78086880944303...| 164|
| 3| 5| [3.0,5.0]|[0.51449575542752...| 34|
| 1| 3| [1.0,3.0]|[0.31622776601683...| 10|
| 1| 5| [1.0,5.0]|[0.19611613513818...| 26|
| 2| 8| [2.0,8.0]|[0.24253562503633...| 68|
| 8| 7| [8.0,7.0]|[0.75257669470687...| 113|
+---+---+----------+--------------------+----------------+
那我想做向量运算:col['Norm_AB']/col['Inner_Product_AB']
有没有可以做这个操作的内置函数?
【问题讨论】: