如何预测Spark ML中的值

时间:2017-06-16 12:32:10

标签: scala apache-spark apache-spark-mllib prediction

非常新的Spark机器学习(4天之久)我在Spark Shell中执行以下代码我正在尝试预测某些值

我的要求是我的数据包含以下内容

 Userid,Date,SwipeIntime
 1, 1-Jan-2017,9.30
 1, 2-Jan-2017,9.35
 1, 3-Jan-2017,9.45
 1, 4-Jan-2017,9.26
 2, 1-Jan-2017,9.37
 2, 2-Jan-2017,9.35
 2, 3-Jan-2017,9.45
 2, 4-Jan-2017,9.46     

我需要预测什么将成为SwipeIntime Userid = 1将于2017年1月5日或任何日期出现

我试过的是Spark Shell中的以下代码

代码:

 case class LabeledDocument(Userid: Double, Date: String, label: Double)
 val training = spark.read.option("inferSchema", true).csv("/root/Predictiondata2.csv").toDF
 ("Userid","Date","label").toDF().as[LabeledDocument]
 import scala.beans.BeanInfo
 import org.apache.spark.{SparkConf, SparkContext}
 import org.apache.spark.ml.Pipeline
 import org.apache.spark.ml.classification.LogisticRegression
 import org.apache.spark.ml.feature.{HashingTF, Tokenizer}
 import org.apache.spark.mllib.linalg.Vector
 import org.apache.spark.sql.{Row, SQLContext}
 val tokenizer = new Tokenizer().setInputCol("Date").setOutputCol("words")
 val hashingTF = new HashingTF().setNumFeatures(1000).setInputCol(tokenizer.getOutputCol).setOutputCol("features")
 import org.apache.spark.ml.regression.LinearRegression
 val lr = new LinearRegression().setMaxIter(10).setRegParam(0.3).setElasticNetParam(0.8)
 val pipeline = new Pipeline().setStages(Array(tokenizer, hashingTF, lr))
 val model = pipeline.fit(training.toDF())
 case class Document(Userid: Integer, Date: String)
 val test = sc.parallelize(Seq(Document(4, "04-Jan-18"),Document(5, "01-Jan-17"),Document(2, "03-Jan-17")))
 model.transform(test.toDF()).show()

获取不正确的输出(所有用户使用相同的SwipeIntime)

 scala> model.transform(test.toDF()).show() 
 +------+---------+-----------+------------------+-----------------+
 |Userid|     Date|      words|          features|       prediction|
 +------+---------+-----------+------------------+-----------------+
 |     4|04-Jan-18|[04-jan-18]|(1000,[455],[1.0])|9.726888888888887|
 |     5|01-Jan-17|[01-jan-17]|(1000,[595],[1.0])|9.726888888888887|
 |     2|03-Jan-17|[03-jan-17]|(1000,[987],[1.0])|9.726888888888887|
 +------+---------+-----------+------------------+-----------------+

如果有人对上述代码提出任何建议以使工作正常,我将感激不尽。

1 个答案:

答案 0 :(得分:1)

为什么你认为它不起作用?因为预测都是一样的吗?

我遇到的问题与描述here类似,但在PySpark中。

我通过提高MaxIter并降低RegParam和ElasticNetParam来解决它。

尝试以这种方式设置:

val lr = new LinearRegression().setMaxIter(100).setRegParam(0.001).setElasticNetParam(0.0001)

希望它有效!

相关问题