【问题标题】:How to pass multiple Columns as features in a Logistic Regression Classifier in Spark? [duplicate]如何在 Spark 的 Logistic 回归分类器中将多个列作为特征传递? [复制]
【发布时间】:2019-07-12 14:03:54
【问题描述】:

我正在尝试使用简单的数据集运行逻辑回归以了解 pyspark 的语法。 我的数据看起来有 11 列,其中前 10 列是特征,最后一列(第 11 列)是标签。 我想将这 10 列作为特征传递,将第 11 列作为标签传递。 但我只知道使用featuresCol="col_header_name" 作为单列传递 我已经使用 pandas 从 csv 文件中读取了数据,但我已将其转换为 RDD。 这是代码:

from pyspark.ml.classification import LogisticRegression
from pyspark.sql import SQLContext
from pyspark import SparkContext
import pandas as pd
data = pd.read_csv('abc.csv')
sc = SparkContext("local", "App Name")
sql = SQLContext(sc)
spDF = sql.createDataFrame(data)
tri=LogisticRegression(maxIter=10,regParam=0.01,featuresCol="single_column",labelCol="label")
lr_model = tri.fit(spDF)

如果我使用 featuresCol=[list_of_header_names] 我会出错。 我使用了 sk-learn,它的语法非常简单,例如:

reg=LogisticRegression()
reg=reg.fit(Dataframe_of_features,Label_array)

【问题讨论】:

  • 有什么错误?
  • TypeError: Invalid param value given for param "featuresCol". Could not convert <class 'list'> to string type 这是有道理的,因为根据语法,featuresCol="name_of_column" 是一个字符串。
  • 当你有featuresCol="single_column"时,这真的是错误吗?

标签: python apache-spark machine-learning pyspark logistic-regression


【解决方案1】:

您需要使用 Vector Assembler 将所有列组合成一个特征数组。

from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
assembler = VectorAssembler(inputCols=[list_of_header_names],outputCol="features")
spDF = assembler.transform(spDF)

然后,您可以将所有变量的组装数组作为输入传递给逻辑回归。

tri=LogisticRegression(maxIter=10,
                       regParam=0.01,
                       featuresCol="features",
                       labelCol="label")
lr_model = tri.fit(spDF)

【讨论】:

  • 它有效,谢谢!还有一件事。MaxIter、RegParam 和 ElasticNetParam 是什么?
  • MaxIter 为最大迭代次数,RegParam 为正则化参数。 Elastic Net Param 指定您希望损失函数为 L1 还是 L2。
  • 谢谢,但我知道完整的表格!我想知道他们的目的。
猜你喜欢
  • 1970-01-01
  • 2019-06-08
  • 2018-10-15
  • 2021-07-24
  • 2015-08-06
  • 2019-06-13
  • 2018-07-19
  • 2017-10-24
  • 2017-08-30
相关资源
最近更新 更多