pyspark之sparkML機器學習常見問題之一:removing nulls from dataset or using handleInvalid = "keep" or "skip".


使用python語言開發sparkML機器學習程序,遇到如異常:

Caused by: org.apache.spark.SparkException: Encountered null while assembling a row with handleInvalid = "keep". Consider
removing nulls from dataset or using handleInvalid = "keep" or "skip".
 at org.apache.spark.ml.feature.VectorAssembler$$anonfun$assemble$1.apply(VectorAssembler.scala:287)
 at org.apache.spark.ml.feature.VectorAssembler$$anonfun$assemble$1.apply(VectorAssembler.scala:255)
 at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
 at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:35)
 at org.apache.spark.ml.feature.VectorAssembler$.assemble(VectorAssembler.scala:255)
 at org.apache.spark.ml.feature.VectorAssembler$$anonfun$4.apply(VectorAssembler.scala:144)
 at org.apache.spark.ml.feature.VectorAssembler$$anonfun$4.apply(VectorAssembler.scala:143)
 ... 16 more

1.分析異常提示:

removing nulls from dataset or using handleInvalid = "keep" or "skip". 根據提示應該是說數據集中的特征列存在null值,建議將null值移除。或者配置參數handleInvalid = "keep" or "skip"。

首先在機器學習過程中,數據集的規范性非常重要。這里並不是說你爬取或直接拿來的數據就直接是很規范的。是需要我們在機器學習訓練之前對訓練數據集做預處理成完整規范的數據。比如null值預處理,特征值字符串形式轉換成數值類型,對訓練無關的列刪除等操作。

2.解決方法:

1)刪除null值列

2)  配置參數,這里采用第二種方式用於測試配置參數的執行效果

  參數說明:handleInvalid="skip" or "keep" ,skip即代表跳過null值不處理, keep代表保留null值

該參數需要放置在 特征列轉換特征向量的函數中: 這里使用skip方式

vec_assembler = VectorAssembler(inputCols=feature_cols, outputCol='features',handleInvalid="skip")
查看VectorAssembler源碼:
@keyword_only
def __init__(self, inputCols=None, outputCol=None, handleInvalid="error"):
"""
__init__(self, inputCols=None, outputCol=None, handleInvalid="error")
"""
super(VectorAssembler, self).__init__()
self._java_obj = self._new_java_obj("org.apache.spark.ml.feature.VectorAssembler", self.uid)
self._setDefault(handleInvalid="error")
kwargs = self._input_kwargs
self.setParams(**kwargs)

默認情況下該函數的handleInvalid="error" 參數定義為error 即如果特征列數據有問題會拋出異常提示。

 

3. 再次運行測試 異常解決


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM