我对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)
我的数据帧如下所示:
+-----------------+----------+------+
| 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.
我试图通过仅阅读描述来预测品牌和燃料类型。
提前致谢
代码的两个小问题:
-
htf
变量没有使用,我假设管道中缺少它?由于这是创建下一阶段所需的rawFeatures
字段PipelineStage
,因此会出现Field does not exist
错误。 -
即使我们修复了这个问题 - 最后一个阶段(LogisticRegression)也会失败,因为它需要一个
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)))
。将成功完成此完成,但当然这里的标签只是为了示例,请根据需要创建标签。