2016-04-23 50 views
0

我对Apache Spark和MLib很陌生,试图完成我的第一个多类分类模型。我停留在一些点...这里是我的代码:Spark中的多类分类与术语频率

val input = sc.textFile("cars2.csv").map(line => line.split(";").toSeq) 

创建数据帧:

val sql = new SQLContext(sc) 
val schema = StructType(List(StructField("Description", StringType), StructField("Brand", StringType), StructField("Fuel", StringType))) 
val dataframe = sql.createDataFrame(input.map(row => Row(row(0), row(1), row(2))), schema) 

我的数据帧是这样的:

+-----------------+----------+------+ 
|  Description|  Brand| Fuel| 
+-----------------+----------+------+ 
| giulietta 1.4TB|alfa romeo|PETROL| 
|    4c|alfa romeo|PETROL| 
| giulietta 2.0JTD|alfa romeo|DIESEL| 
| Mito 1.4 Tjet |alfa romeo|PETROL| 
|  a1 1.4 TFSI|  AUDI|PETROL| 
|  a1 1.0 TFSI|  AUDi|PETROL| 
|  a3 1.4 TFSI|  AUDI|PETROL| 
|  a3 1.2 TFSI|  AUDI|PETROL| 
|  a3 2.0 Tdi|  AUDI|DIESEL| 
|  a3 1.6 TDi|  AUDI|DIESEL| 
|  a3 1.8tsi|  AUDI|PETROL| 
|    RS3 |  AUDI|PETROL| 
|    S3|  AUDI|PETROL| 
|  A4 2.0TDI|  AUDI|DIESEL| 
|  A4 2.0TDI|  AUDI|DIESEL| 
|  A4 1.4 tfsi|  AUDI|PETROL| 
|  A4 2.0TFSI|  AUDI|PETROL| 
|  A4 3.0TDI|  AUDI|DIESEL| 
|   X5 3.0D|  BMW|DIESEL| 
|    750I|  BMW|PETROL| 

然后:

//Tokenize 
val tokenizer = new Tokenizer().setInputCol("Description").setOutputCol("tokens") 
val tokenized = tokenizer.transform(dataframe) 

    //Creating term-frequency 
val htf = new HashingTF().setInputCol(tokenizer.getOutputCol).setOutputCol("rawFeatures").setNumFeatures(500) 
val tf = htf.transform(tokenized) 

val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features") 


// Model & Pipeline 
import org.apache.spark.ml.classification.LogisticRegression 
val lr = new LogisticRegression().setMaxIter(20).setRegParam(0.01) 

import org.apache.spark.ml.Pipeline 
val pipeline = new Pipeline().setStages(Array(tokenizer, idf, lr)) 
//Model 
val model = pipeline.fit(dataframe) 

错误:

java.lang.IllegalArgumentException: Field "rawFeatures" does not exist. 

我想通过阅读说明来预测品牌和燃料类型。

在此先感谢

回答

0

两个小问题与您的代码:不使用

  1. htf变量,我认为它是从管道不见了?由于这是PipelineStage创建下一阶段所需的rawFeatures字段,因此会出现Field does not exist错误。

  2. 即使我们解决这个问题 - 最终阶段(逻辑回归),因为它需要DoubleType类型label场,除了features场将失败。在装配之前,您需要将这样的字段添加到您的数据框中。

改变你的代码的最后行..

// pipeline - with "htf" stage added 
val pipeline = new Pipeline().setStages(Array(tokenizer, htf, idf, lr)) 
//Model - with an addition (constant...) label field 
val model = pipeline.fit(dataframe.withColumn("label", lit(1.0))) 

...将使这一成功完成,当然这里的标签仅仅是例子的缘故,创建标签为你觉得合适。