2016-12-20 38 views
0

首先,我使用spark 1.6.0。我想在pyspark.ml.regression.LinearRegressionModel中使用L1懲罰進行特徵選擇。如何在pyspark.ml.regression.LinearRegressionModel中使用L1懲罰進行特徵選擇?

但我不能得到詳細的係數調用函數時:

lr = LogisticRegression(elasticNetParam=1.0, regParam=0.01,maxIter=100,fitIntercept=False,standardization=False) 
model = lr.fit(df_one_hot_train) 
print model.coefficients.toArray().astype(float).tolist() 

我只得到稀疏的列表,如:

[0,0,0,0,0,..,-0.0871650387514,..,] 

雖然當我使用sklearn.linear_model.LogisticRegression模型,我可以在coef_ list中得到沒有零值的詳細列表,如:

[0.03098372361467529,-0.13709075166114365,-0.15069548597557908,-0.017968044053830862] 

隨着火花的更好表現,我可以更快地完成我的工作。我只想使用L1懲罰來選擇特徵。

我想我應該使用更詳細的係數值作爲我的特徵選擇工作,就像sklearn一樣,我該如何解決我的問題?

回答

0

以下是Spark 2.1中的工作代碼片段。

的關鍵在於提取值是:

stages(4).asInstanceOf[LinearRegressionModel] 

星火1.6可能有類似的東西。

val holIndIndexer = new StringIndexer().setInputCol("holInd").setOutputCol("holIndIndexer") 

val holIndEncoder = new OneHotEncoder().setInputCol("holIndIndexer").setOutputCol("holIndVec") 

val time_intervaLEncoder = new OneHotEncoder().setInputCol("time_interval").setOutputCol("time_intervaLVec") 

val assemblerL1 = (new VectorAssembler() 
      .setInputCols(Array("time_intervaLVec", "holIndVec", "length")).setOutputCol("features")) 

val lrL1 = new LinearRegression().setFeaturesCol("features").setLabelCol("travel_time") 

val pipelineL1 = new Pipeline().setStages(Array(holIndIndexer,holIndEncoder,time_intervaLEncoder,assemblerL1, lrL1)) 

val modelL1 = pipelineL1.fit(dfTimeMlFull) 

val l1Coeff =modelL1.stages(4).asInstanceOf[LinearRegressionModel].coefficients 

println(l1Coeff)