【问题标题】:Make VectorAssembler always choose DenseVector让 VectorAssembler 总是选择 DenseVector
【发布时间】:2018-12-21 09:12:00
【问题描述】:

这是我使用df.columns 的数据框的结构。

['LastName',
 'FirstName',
 'Stud. ID',
 '10 Relations',
 'Related to Politics',
 '3NF',
 'Documentation & Scripts',
 'SQL',
 'Data (CSV, etc.)',
 '20 Relations',
 'Google News',
 'Cheated',
 'Sum',
 'Delay Factor',
 'Grade (out of 2)']

我已经使用

在 pyspark 中转换了这个数据框
assembler = VectorAssembler(inputCols=['10 Relations',
 'Related to Politics',
 '3NF'],outputCol='features')

output = assembler.transform(df)。现在它包含一些 Row 对象。这些对象具有这种架构(这是我运行output.printSchema() 时得到的)

root
 |-- LastName: string (nullable = true)
 |-- FirstName: string (nullable = true)
 |-- Stud. ID: integer (nullable = true)
 |-- 10 Relations: integer (nullable = true)
 |-- Related to Politics: integer (nullable = true)
 |-- 3NF: integer (nullable = true)
 |-- Documentation & Scripts: integer (nullable = true)
 |-- SQL: integer (nullable = true)
 |-- Data (CSV, etc.): integer (nullable = true)
 |-- 20 Relations: integer (nullable = true)
 |-- Google News: integer (nullable = true)
 |-- Cheated: integer (nullable = true)
 |-- Sum: integer (nullable = true)
 |-- Delay Factor: double (nullable = true)
 |-- Grade (out of 2): double (nullable = true)
 |-- features: vector (nullable = true)

对于每一行,汇编器选择使特征向量稀疏或密集(出于内存原因)。但这是一个大问题。因为我想使用这些转换后的数据来制作线性回归模型。所以,我正在寻找一种让 VectorAssembler 始终选择密集向量的方法。

有什么想法吗?

注意:我已阅读this post。但问题是,由于 Row 类是 tuple 的子类,所以 Row 对象生成后无法更改。

【问题讨论】:

    标签: python pyspark


    【解决方案1】:

    Sparse 和 Dense 向量都继承自 pyspark.ml.linalg.Vector。所以这两种向量类型都有.toarray() 共同的方法。您可以将它们转换为 numpy 数组,然后使用简单的 udf 密集 vetor。

    from pyspark.ml.linalg import DenseVector, SparseVector, Vectors, VectorUDT
    from pyspark.sql import functions as F
    from pyspark.sql.types import *
    
    
    v = Vectors.dense([1,3]) # dense vector
    u = SparseVector(2, {}) # sparse vector
    
    # toDense function converts both vector  type into Dense Vector
    toDense = lambda v: Vectors.dense(v.toArray()) 
    toDense(u), toDense(v)
    

    结果:

    DenseVector([0.0, 0.0]), DenseVector([1.0, 3.0])
    

    然后你就可以用这个函数创建udf了。

    df = sqlContext.createDataFrame([
        ((v,)), 
        ((u,))
       ], ['feature'])
    
    toDense = lambda v: Vectors.dense(v.toArray())
    toDenseUdf = F.udf(toDense, VectorUDT())
    df.withColumn('feature', toDenseUdf('feature')).show()
    

    结果:

    +---------+
    |  feature|
    +---------+
    |[1.0,3.0]|
    |[0.0,0.0]|
    +---------+
    

    您在列中有单个向量类型。

    【讨论】:

      猜你喜欢
      • 2016-06-21
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 2016-08-15
      相关资源
      最近更新 更多