gpt4 book ai didi

scala - 在 Spark 中将连续变量转换为分类变量

转载 作者:行者123 更新时间:2023-12-01 15:00:00 24 4
gpt4 key购买 nike

我正在尝试将一些连续变量转换为分类变量,以便对它们应用一些 ML 算法,并且我想创建类似从 6:00 到 12:00 的类别->“早上”或类似 ddMM 到“的格式的日期”夏天”之类的。
这些变量已经被转换为整数。喜欢 recode我认为 R 中的函数。

+----------+
|CRSDepTime|
+----------+
| 745|
| 1053|
| 1915|
| 1755|
| 832|
| 630|
| 820|
| 945|
| 1245|
| 1645|
| 620|
| 1125|
| 2045|
| 1340|
| 1540|
| 730|
| 1145|
| 525|
| 630|
| 1520|
+----------+

我用这句话解决了这个问题!!
df = df.withColumn("Season", when(df("Month") >= 12 and df("Month") <=3, "Fall")
.when(df("Month") >= 4 and df("Month") <= 6, "Spring")
.when(df("Month") >= 7 and df("Month") <= 9, "Summer").otherwise("Autumm"))

最佳答案

有两个Transformers可用于将连续变量转换为分类变量:

  • Bucketizer
  • QuantileDiscretizer
  • Bucketizer需要拆分,因此可以在这里使用:
    import org.apache.spark.ml.feature._

    val df = Seq(
    745, 1053, 1915, 1755, 832, 630, 820, 945,
    1245, 1645, 620, 1125, 2045, 1340, 1540, 730,
    1145, 525, 630, 1520
    ).toDF("CRSDepTime")

    val bucketizer = new Bucketizer()
    .setInputCol("CRSDepTime")
    .setOutputCol("bucketedFeatures")
    .setSplits(Array(0, 600, 1200, 1800, 2400))

    // +----------+----------------+
    // |CRSDepTime|bucketedFeatures|
    // +----------+----------------+
    // | 745| 1.0|
    // | 1053| 1.0|
    // | 1915| 3.0|
    // | 1755| 2.0|
    // | 832| 1.0|
    // | 630| 1.0|
    // | 820| 1.0|
    // | 945| 1.0|
    // | 1245| 2.0|
    // | 1645| 2.0|
    // +----------+----------------+
    // only showing top 10 rows

    通常它会与 OneHotEncoder 一起使用:
    import org.apache.spark.ml.Pipeline

    val encoder = new OneHotEncoder()
    .setInputCol(bucketizer.getOutputCol)
    .setOutputCol("CRSDepTimeencoded")

    val pipeline = new Pipeline().setStages(Array(bucketizer, encoder))

    pipeline.fit(df).transform(df).show(10)

    // +----------+----------------+-----------------+
    // |CRSDepTime|bucketedFeatures|CRSDepTimeencoded|
    // +----------+----------------+-----------------+
    // | 745| 1.0| (3,[1],[1.0])|
    // | 1053| 1.0| (3,[1],[1.0])|
    // | 1915| 3.0| (3,[],[])|
    // | 1755| 2.0| (3,[2],[1.0])|
    // | 832| 1.0| (3,[1],[1.0])|
    // | 630| 1.0| (3,[1],[1.0])|
    // | 820| 1.0| (3,[1],[1.0])|
    // | 945| 1.0| (3,[1],[1.0])|
    // | 1245| 2.0| (3,[2],[1.0])|
    // | 1645| 2.0| (3,[2],[1.0])|
    // +----------+----------------+-----------------+
    // only showing top 10 rows

    关于scala - 在 Spark 中将连续变量转换为分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47638862/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com