Pyspark特征工程--VectorIndexer

VectorIndexer

class pyspark.ml.feature.VectorIndexer(maxCategories=20, inputCol=None, outputCol=None, handleInvalid=‘error’)

用于对 Vector 数据集中的分类特征列进行索引的类

两种使用模式:

​ 1.自动识别分类特征(默认行为)

​ 这有助于将未知向量的数据集处理成具有一些连续特征和一些分类特征的数据集。

​ 连续和分类之间的选择基于 maxCategories 参数。 将 maxCategories 设置为任何分类特征应具有的最大分类数。

​ 例如:特征 0 具有唯一值 {-1.0, 0.0},特征 1 具有唯一值 {1.0, 3.0, 5.0}。 如果 maxCategories = 2,则特征 0 将被声明为分类 并使用索引 {0, 1},而特征 1 将被声明为连续的。

​ 2.索引所有特征,如果所有特征都是分类的

​ 如果 maxCategories 设置为非常大,那么这将为所有特征建立一个唯一值的索引。

​ 警告:如果特征是连续的,这可能会导致问题,因为这会将所有唯一值收集到驱动程序。

​ 例如:特征 0 具有唯一值 {-1.0, 0.0},特征 1 具有唯一值 {1.0, 3.0, 5.0}。 如果 maxCategories >= 3,那么这两个特征都将被声 明为分类的。

​ 返回:一个模型,该模型可以将分类特征转换为使用基于 0 的索引

索引稳定性,当前版本2.4.5:

​ 不能保证在多次运行中选择相同的类别索引。 如果分类特征包括值 0,则保证将值 0 映射到索引 0。这保持向量稀疏性

maxCategories= Param(parent=‘undefined’, name=‘maxCategories’, doc=‘Threshold for the number of values a categorical feature can take (>= 2). If a feature is found to have > maxCategories values, then it is declared continuous.’)*

一个分类特征可以取值的数量阈值 (>= 2)。如果发现一个特征有 > maxCategories 值,那么它是必然连续

handleInvalid = Param(parent=‘undefined’, name=‘handleInvalid’, doc="如何处理无效数据(看不见的标签或 NULL 值)。选项是 ‘skip’(过滤掉包含无效数据的行),‘error’ ( 抛出错误)或“保留”(将无效数据放入特殊的附加存储桶中,位于特征类别数的索引处)。”)

categoryMaps特征价值指数。键是分类特征索引(列索引)。值是从原始特征值到基于 0 的类别索引的映射。如果某个要素不在其中,则将其视为连续要素。

01.创建数据

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("SQLTransformer").master("local[*]").getOrCreate()
from pyspark.ml.linalg import Vectors
df = spark.createDataFrame([(Vectors.dense([-1.0, 0.0]),),
    (Vectors.dense([0.0, 1.0]),), (Vectors.dense([0.0, 2.0]),)], ["a"])
df.show()

​ 输出结果:

+----------+
|         a|
+----------+
|[-1.0,0.0]|
| [0.0,1.0]|
| [0.0,2.0]|
+----------+

02.使用VectorIndexer

from pyspark.ml.feature import VectorIndexer
indexer = VectorIndexer(maxCategories=2, inputCol="a", outputCol="indexed")
model = indexer.fit(df)
model.transform(df).show()

​ 输出结果:

+----------+---------+
|         a|   vector|
+----------+---------+
|[-1.0,0.0]|[1.0,0.0]|
| [0.0,1.0]|[0.0,1.0]|
| [0.0,2.0]|[0.0,2.0]|
+----------+---------+

03.总特征个数

model.numFeatures

​ 输出结果:2

04.特征价值指数

model.categoryMaps

​ 输出结果:{0: {0.0: 0, -1.0: 1}}

05.重新设置参数,查看输出结果

params = {indexer.maxCategories: 3, indexer.outputCol: "vector"}
model2 = indexer.fit(df, params)
model2.transform(df).show()

​ 输出结果:

+----------+---------+
|         a|   vector|
+----------+---------+
|[-1.0,0.0]|[1.0,0.0]|
| [0.0,1.0]|[0.0,1.0]|
| [0.0,2.0]|[0.0,2.0]|
+----------+---------+
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值