我是Apache Spark和MLlib的新手,并试图做我的第一个多类分类模型。我坚持了一下......这是我的代码:
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)
我的DataFrame看起来像这样:
+-----------------+----------+------+
| 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 :(得分:0)
您的代码存在两个小问题:
htf
变量未被使用,我认为它在管道中丢失了?由于这是PipelineStage
创建下一阶段所需的rawFeatures
字段,因此会出现Field does not exist
错误。
即使我们解决了这个问题 - 最后一个阶段(LogisticRegression)也会失败,因为除label
字段外,它还需要DoubleType
字段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)))
...将成功完成此项目,但当然这里的标签只是为了示例,请根据需要创建标签。