VectorSlicer
class pyspark.ml.feature.VectorSlicer(inputCol=None, outputCol=None, indices=None, names=None)
这个类接受一个特征向量并输出一个带有原始特征子数组的新特征向量。 可以使用索引 (setIndices()) 或名称 (setNames()) 指定特征子集。 必须至少选择一项功能。 不允许有重复的特征,因此选定的索引和名称之间不能有重叠。 输出向量将首先使用所选索引对特征进行排序(按给定顺序),然后是所选名称(按给定顺序)
indices = Param(parent=‘undefined’, name=‘indices’, doc=‘从向量列中选择特征的索引数组。名称不能重叠。’)
names = Param(parent=‘undefined’, name=‘names’, doc=‘从向量列中选择特征的特征名称数组。这些名称必须由 ML org.apache.spark.ml.attribute.Attribute 指定. 不能与索引重叠。’)
01.创建数据
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("VectorSizeHint").master("local[*]").getOrCreate()
from pyspark.ml.linalg import Vectors
df = spark.createDataFrame([
(Vectors.dense([-2.0, 2.3, 0.0, 0.0, 1.0]),),
(Vectors.dense([0.0, 0.0, 0.0, 0.0, 0.0]),),
(Vectors.dense([0.6, -1.1, -3.0, 4.5, 3.3]),)], ["features"])
df.head(3)
输出结果:
[Row(features=DenseVector([-2.0, 2.3, 0.0, 0.0, 1.0])),
Row(features=DenseVector([0.0, 0.0, 0.0, 0.0, 0.0])),
Row(features=DenseVector([0.6, -1.1, -3.0, 4.5, 3.3]))]
02.使用VectorSlicer,选取索引为indices=[1, 4]的特征
from pyspark.ml.feature import VectorSlicer
vs = VectorSlicer(inputCol="features", outputCol="sliced", indices=[1, 4])
vs.transform(df).head(3)
输出结果:
[Row(features=DenseVector([-2.0, 2.3, 0.0, 0.0, 1.0]), sliced=DenseVector([2.3, 1.0])),
Row(features=DenseVector([0.0, 0.0, 0.0, 0.0, 0.0]), sliced=DenseVector([0.0, 0.0])),
Row(features=DenseVector([0.6, -1.1, -3.0, 4.5, 3.3]), sliced=DenseVector([-1.1, 3.3]))]