【问题标题】:How to map the coefficient obtained from logistic regression model to the feature names in pyspark如何将从逻辑回归模型获得的系数映射到pyspark中的特征名称
【发布时间】:2019-09-22 02:06:57
【问题描述】:

我使用管道流构建了一个逻辑回归模型,该模型流向 databricks 列出的模型。 https://docs.databricks.com/spark/latest/mllib/binary-classification-mllib-pipelines.html

特征(数字和字符串特征)使用OneHotEncoderEstimator 编码,然后使用标准缩放器进行转换。

我想知道如何将从逻辑回归获得的权重(系数)映射到原始数据框中的特征名称。

也就是说,如何得到与模型得到的权重或系数相对应的特征

谢谢

我试图从 lrModel.schema 中提取特征,它给出了一个 structField 的列表,显示了这些特征

我试图从模式中提取特征并映射到权重但没有成功

from pyspark.ml.classification import LogisticRegression

# Create initial LogisticRegression model
lr = LogisticRegression(labelCol="label", featuresCol="scaledFeatures", maxIter=10)

# Train model with Training Data

lrModel = lr.fit(trainingData)

predictions = lrModel.transform(trainingData)

LRschema = predictions.schema

提取元组列表的预期结果(特征权重,特征名称)

【问题讨论】:

  • 在转换后的数据框中使用 features 列的架构
  • 非常感谢您的回答。它为我打开了一扇门,让我了解这个特征编号在向量中是如何工作的,我想我设法对它进行了排序。 pyspark 中是否有直接的方法可以将权重直接与命名的特征匹配,或者我必须通过模式对其进行排序
  • 可能有属性访问器,但我没有使用它们,并且模式/元数据是 spark 存储这些信息的方式。您可以发布您的答案并标记它,以便其他人可以从中受益

标签: pyspark logistic-regression feature-extraction


【解决方案1】:

不是 LogisticRegression 的直接输出,但可以使用我使用的以下函数获得:

def ExtractFeatureCoeficient(model, dataset, excludedCols = None):
    test = model.transform(dataset)
    weights = model.coefficients
    print('This is model weights: \n', weights)
    weights = [(float(w),) for w in weights]  # convert numpy type to float, and to tuple
    if excludedCols == None:
        feature_col = [f for f in test.schema.names if f not in ['y', 'classWeights', 'features', 'label', 'rawPrediction', 'probability', 'prediction']]
    else:
        feature_col = [f for f in test.schema.names if f not in excludedCols]
    if len(weights) == len(feature_col):
        weightsDF = sqlContext.createDataFrame(zip(weights, feature_col), schema= ["Coeficients", "FeatureName"])
    else:
        print('Coeficients are not matching with remaining Fetures in the model, please check field lists with model.transform(dataset).schema.names')
    
    return weightsDF

results = ExtractFeatureCoeficient(lr_model, trainingData)

results.show()

这将生成一个包含以下字段的 spark 数据框:

+--------------------+--------------------+
|         Coeficients|         FeatureName|
+--------------------+--------------------+
|[0.15834847825223...|    name            |
|               [0.0]|  lat               |
+--------------------+--------------------+

或者您可以如下拟合 GML 模型:

model = GeneralizedLinearRegression(family="binomial", link="logit", featuresCol="features", labelCol="label", maxIter = 1000, regParam = 0.8, weightCol="classWeights")

# Train model.  This also runs the indexer.
models = glmModel.fit(trainingData)

# then get summary of the model:

summary = model.summary
print(summary)

生成输出:

Coefficients:
        Feature       Estimate Std Error  T Value P Value
    (Intercept)       -1.3079    0.0705 -18.5549  0.0000
    name               0.1248    0.0158   7.9129  0.0000
    lat                0.0239    0.0209   1.1455  0.2520

【讨论】:

    【解决方案2】:

    假设你有一个逻辑回归可以使用,这个 Pandas 解决方法会给你结果。

    lr = LogisticRegression(labelCol="label", featuresCol="features",maxIter=50,threshold=0.5)
    
    lr_model=lr.fit(train_set)
    
    print("Intercept: " + str(lr_model.intercept))  
    
    pd.DataFrame({'coefficients':lr_model.coefficients, 'feature':list(pd.DataFrame(train_set.schema["features"].metadata["ml_attr"]["attrs"]['numeric']).sort_values('idx')['name'])})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-12
      • 2021-07-05
      • 2016-05-17
      • 2016-03-07
      • 2021-12-26
      • 2018-07-08
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多