簡體   English   中英

Spark中帶有術語頻率的多類分類

[英]Multiclass classification in Spark with Term Frequency

我對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.

我僅通過閱讀說明來嘗試預測品牌和燃料類型。

提前致謝

您的代碼有兩個小問題:

  1. htf變量未使用,我認為它在管道中丟失了嗎? 由於這是PipelineStage創建下一階段所需的rawFeatures字段,因此您將獲得Field does not exist錯誤。

  2. 即使我們解決了這個問題,最后一個階段(LogisticRegression)也會失敗,因為除了features字段之外,它還需要一個label類型為DoubleTypelabel字段。 在擬合之前,您需要將這樣的字段添加到數據框中。

更改代碼中的最后一行

// 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)))

...將成功完成此操作,但是這里的標簽只是為了示例的緣故,請根據需要創建標簽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM