Pipeline詳解及Spark MLlib使用示例(Scala/Java/Python)

     本文中,我們介紹機器學習管道的概念。機器學習管道提供一系列基於數據框的高級的接口來幫助用戶建立和調試實際的機器學習管道。

管道里的主要概念

       MLlib提供標準的接口來使聯合多個算法到單個的管道或者工作流,管道的概念源於scikit-learn項目。

       1.數據框:機器學習接口使用來自Spark SQL的數據框形式數據作爲數據集,它可以處理多種數據類型。比如,一個數據框可以有不同的列存儲文本、特徵向量、標籤值和預測值。

       2.轉換器:轉換器是將一個數據框變爲另一個數據框的算法。比如,一個機器學習模型就是一個轉換器,它將帶有特徵數據框轉爲預測值數據框。

       3.估計器:估計器是擬合一個數據框來產生轉換器的算法。比如,一個機器學習算法就是一個估計器,它訓練一個數據框產生一個模型。

       4.管道:一個管道串起多個轉換器和估計器,明確一個機器學習工作流。

       5.參數:管道中的所有轉換器和估計器使用共同的接口來指定參數。

數據框

       機器學習算法可以應用於多種類型的數據,如向量、文本、圖像和結構化數據。管道接口中採用來自Spark SQL的數據框來支持多種類型的數據。可以查看Spark SQLdatatype reference來了解數據框支持的基礎和結構化數據類型。除了Spark SQL指南中提到的數據類型外,數據框還可以使用機器學習向量類型。可以顯式地建立數據框或者隱式地從規則的RDD建立數據框,下面的代碼將會給出示例。數據框中的列需要命名。代碼中的示例使用如“text”,“features“和”label“的名字。

管道組件

轉換器

       轉換器包含特徵變化和學習模型。技術上來說,轉化器通過方法transform(),在原始數據上增加一列或者多列來將一個數據框轉爲另一個數據框。如:

       1.一個特徵轉換器輸入一個數據框,讀取一個文本列,將其映射爲新的特徵向量列。輸出一個新的帶有特徵向量列的數據框。

       2.一個學習模型轉換器輸入一個數據框,讀取包括特徵向量的列,預測每一個特徵向量的標籤。輸出一個新的帶有預測標籤列的數據框。

估計器

       估計器指用來擬合或者訓練數據的學習算法或者任何算法。技術上說,估計器通過fit()方法,接受一個數據框產生一個模型。比如,邏輯迴歸就是一個估計器,通過fit()來產生一個邏輯迴歸模型。

管道組件的特性

       轉換器的transform()方法和估計器的fit()方法都是無狀態性的。將來,有狀態性的算法可能通過其他概念得到支持。

       每個轉換器或估計器實例有唯一的編號,這個特徵在制定參數的時候非常有用。

管道

       在機器學習中,運行一系列算法來處理和學習數據是非常常見的。如一個文檔數據的處理工作流可能包括下列步驟:

       1.將文檔氛圍單個詞語。

       2.將每個文檔中的詞語轉爲數字化的特徵向量。

       3.使用特徵向量和標籤學習一個預測模型。

       MLlib將上述的工作流描述爲管道,它包含一系列需要被執行的有順序的管道階段(轉換器和估計器)。本節中我們將會使用上述文檔處理工作流作爲例子。

工作原理

       管道由一系列有順序的階段指定,每個狀態時轉換器或估計器。每個狀態的運行是有順序的,輸入的數據框通過每個階段進行改變。在轉換器階段,transform()方法被調用於數據框上。對於估計器階段,fit()方法被調用來產生一個轉換器,然後該轉換器的transform()方法被調用在數據框上。

       下面的圖說明簡單的文檔處理工作流的運行。

       上面的圖示中,第一行代表管道處理的三個階段。第一二個藍色的階段是轉換器,第三個紅色框中的邏輯迴歸是估計器。底下一行代表管道中的數據流,圓筒指數據框。管道的fit()方法被調用於原始的數據框中,裏面包含原始的文檔和標籤。分詞器的transform()方法將原始文檔分爲詞語,添加新的詞語列到數據框中。哈希處理的transform()方法將詞語列轉換爲特徵向量,添加新的向量列到數據框中。然後,因爲邏輯迴歸是估計器,管道先調用邏輯迴歸的fit()方法來產生邏輯迴歸模型。如果管道還有其它更多階段,在將數據框傳入下一個階段之前,管道會先調用邏輯迴歸模型的transform()方法。

       整個管道是一個估計器。所以當管道的fit()方法運行後,會產生一個管道模型,管道模型是轉換器。管道模型會在測試時被調用,下面的圖示說明用法。

       上面的圖示中,管道模型和原始管道有同樣數目的階段,然而原始管道中的估計器此時變爲了轉換器。當管道模型的transform()方法被調用於測試數據集時,數據依次經過管道的各個階段。每個階段的transform()方法更新數據集,並將之傳到下個階段。

       管道和管道模型有助於確認訓練數據和測試數據經過同樣的特徵處理流程。

詳細信息

       DAG管道:管道的狀態是有序的隊列。這兒給的例子都是線性的管道,也就是說管道的每個階段使用上一個階段產生的數據。我們也可以產生非線性的管道,數據流向爲無向非環圖(DAG)。這種圖通常需要明確地指定每個階段的輸入和輸出列名(通常以指定參數的形式)。如果管道是DAG形式,則每個階段必須以拓撲序的形式指定。

       運行時間檢查:因爲管道可以運行在多種數據類型上,所以不能使用編譯時間檢查。管道和管道模型在實際運行管道之前就會進行運行時間檢查。這種檢查通過數據框摘要,它描述了數據框中各列的類型。

      管道的唯一階段:管道的的每個階段需要是唯一的實體。如同樣的實體“哈希變換”不可以進入管道兩次,因爲管道的每個階段必須有唯一的ID。當然“哈希變換1”和“哈希變換2”(都是哈希變換類型)可以進入同個管道兩次,因爲他們有不同的ID。

參數

      MLlib估計器和轉換器使用統一的接口來指定參數。Param是有完備文檔的已命名參數。ParamMap是一些列“參數-值”對。

      有兩種主要的方法來向算法傳遞參數:

      1.給實體設置參數。比如,lr是一個邏輯迴歸實體,通過lr.setMaxIter(10)來使得lr在擬合的時候最多迭代10次。這個接口與spark.mllib包相似。

2.傳遞ParamMap到fit()或者transform()。所有在ParamMap裏的參數都將通過設置被重寫。

      參數屬於指定估計器和轉換器實體過程。因此,如果我們有兩個邏輯迴歸實體lr1和lr2,我們可以建立一個ParamMap來指定兩個實體的最大迭代次數參數:ParamMap(lr1.maxIter -> 10, lr2.maxIter -> 20)。這在一個管道里有兩個算法都有最大迭代次數參數時非常有用。

存儲和讀取管道

      我們經常需要將管道存儲到磁盤以供下次使用。在Spark1.6中,模型導入導出功能新添了管道接口,支持大多數轉換器。請到算法接口文檔查看是否支持存儲和讀入。

代碼示例

      下面給出上述討論功能的代碼示例:

估計器、轉換器和Param示例:

Scala:

[plain] view plain copy
  1. import org.apache.spark.ml.classification.LogisticRegression  
  2. import org.apache.spark.ml.linalg.{Vector, Vectors}  
  3. import org.apache.spark.ml.param.ParamMap  
  4. import org.apache.spark.sql.Row  
  5.   
  6. // Prepare training data from a list of (label, features) tuples.  
  7. val training = spark.createDataFrame(Seq(  
  8.   (1.0, Vectors.dense(0.0, 1.1, 0.1)),  
  9.   (0.0, Vectors.dense(2.0, 1.0, -1.0)),  
  10.   (0.0, Vectors.dense(2.0, 1.3, 1.0)),  
  11.   (1.0, Vectors.dense(0.0, 1.2, -0.5))  
  12. )).toDF("label", "features")  
  13.   
  14. // Create a LogisticRegression instance. This instance is an Estimator.  
  15. val lr = new LogisticRegression()  
  16. // Print out the parameters, documentation, and any default values.  
  17. println("LogisticRegression parameters:\n" + lr.explainParams() + "\n")  
  18.   
  19. // We may set parameters using setter methods.  
  20. lr.setMaxIter(10)  
  21.   .setRegParam(0.01)  
  22.   
  23. // Learn a LogisticRegression model. This uses the parameters stored in lr.  
  24. val model1 = lr.fit(training)  
  25. // Since model1 is a Model (i.e., a Transformer produced by an Estimator),  
  26. // we can view the parameters it used during fit().  
  27. // This prints the parameter (name: value) pairs, where names are unique IDs for this  
  28. // LogisticRegression instance.  
  29. println("Model 1 was fit using parameters: " + model1.parent.extractParamMap)  
  30.   
  31. // We may alternatively specify parameters using a ParamMap,  
  32. // which supports several methods for specifying parameters.  
  33. val paramMap = ParamMap(lr.maxIter -> 20)  
  34.   .put(lr.maxIter, 30)  // Specify 1 Param. This overwrites the original maxIter.  
  35.   .put(lr.regParam -> 0.1, lr.threshold -> 0.55)  // Specify multiple Params.  
  36.   
  37. // One can also combine ParamMaps.  
  38. val paramMap2 = ParamMap(lr.probabilityCol -> "myProbability")  // Change output column name.  
  39. val paramMapCombined = paramMap ++ paramMap2  
  40.   
  41. // Now learn a new model using the paramMapCombined parameters.  
  42. // paramMapCombined overrides all parameters set earlier via lr.set* methods.  
  43. val model2 = lr.fit(training, paramMapCombined)  
  44. println("Model 2 was fit using parameters: " + model2.parent.extractParamMap)  
  45.   
  46. // Prepare test data.  
  47. val test = spark.createDataFrame(Seq(  
  48.   (1.0, Vectors.dense(-1.0, 1.5, 1.3)),  
  49.   (0.0, Vectors.dense(3.0, 2.0, -0.1)),  
  50.   (1.0, Vectors.dense(0.0, 2.2, -1.5))  
  51. )).toDF("label", "features")  
  52.   
  53. // Make predictions on test data using the Transformer.transform() method.  
  54. // LogisticRegression.transform will only use the 'features' column.  
  55. // Note that model2.transform() outputs a 'myProbability' column instead of the usual  
  56. // 'probability' column since we renamed the lr.probabilityCol parameter previously.  
  57. model2.transform(test)  
  58.   .select("features", "label", "myProbability", "prediction")  
  59.   .collect()  
  60.   .foreach { case Row(features: Vector, label: Double, prob: Vector, prediction: Double) =>  
  61.     println(s"($features, $label) -> prob=$prob, prediction=$prediction")  
  62.   }  
Java:

[java] view plain copy
  1. import java.util.Arrays;  
  2. import java.util.List;  
  3.   
  4. import org.apache.spark.ml.classification.LogisticRegression;  
  5. import org.apache.spark.ml.classification.LogisticRegressionModel;  
  6. import org.apache.spark.ml.linalg.VectorUDT;  
  7. import org.apache.spark.ml.linalg.Vectors;  
  8. import org.apache.spark.ml.param.ParamMap;  
  9. import org.apache.spark.sql.Dataset;  
  10. import org.apache.spark.sql.Row;  
  11. import org.apache.spark.sql.RowFactory;  
  12. import org.apache.spark.sql.types.DataTypes;  
  13. import org.apache.spark.sql.types.Metadata;  
  14. import org.apache.spark.sql.types.StructField;  
  15. import org.apache.spark.sql.types.StructType;  
  16.   
  17. // Prepare training data.  
  18. List<Row> dataTraining = Arrays.asList(  
  19.     RowFactory.create(1.0, Vectors.dense(0.01.10.1)),  
  20.     RowFactory.create(0.0, Vectors.dense(2.01.0, -1.0)),  
  21.     RowFactory.create(0.0, Vectors.dense(2.01.31.0)),  
  22.     RowFactory.create(1.0, Vectors.dense(0.01.2, -0.5))  
  23. );  
  24. StructType schema = new StructType(new StructField[]{  
  25.     new StructField("label", DataTypes.DoubleType, false, Metadata.empty()),  
  26.     new StructField("features"new VectorUDT(), false, Metadata.empty())  
  27. });  
  28. Dataset<Row> training = spark.createDataFrame(dataTraining, schema);  
  29.   
  30. // Create a LogisticRegression instance. This instance is an Estimator.  
  31. LogisticRegression lr = new LogisticRegression();  
  32. // Print out the parameters, documentation, and any default values.  
  33. System.out.println("LogisticRegression parameters:\n" + lr.explainParams() + "\n");  
  34.   
  35. // We may set parameters using setter methods.  
  36. lr.setMaxIter(10).setRegParam(0.01);  
  37.   
  38. // Learn a LogisticRegression model. This uses the parameters stored in lr.  
  39. LogisticRegressionModel model1 = lr.fit(training);  
  40. // Since model1 is a Model (i.e., a Transformer produced by an Estimator),  
  41. // we can view the parameters it used during fit().  
  42. // This prints the parameter (name: value) pairs, where names are unique IDs for this  
  43. // LogisticRegression instance.  
  44. System.out.println("Model 1 was fit using parameters: " + model1.parent().extractParamMap());  
  45.   
  46. // We may alternatively specify parameters using a ParamMap.  
  47. ParamMap paramMap = new ParamMap()  
  48.   .put(lr.maxIter().w(20))  // Specify 1 Param.  
  49.   .put(lr.maxIter(), 30)  // This overwrites the original maxIter.  
  50.   .put(lr.regParam().w(0.1), lr.threshold().w(0.55));  // Specify multiple Params.  
  51.   
  52. // One can also combine ParamMaps.  
  53. ParamMap paramMap2 = new ParamMap()  
  54.   .put(lr.probabilityCol().w("myProbability"));  // Change output column name  
  55. ParamMap paramMapCombined = paramMap.$plus$plus(paramMap2);  
  56.   
  57. // Now learn a new model using the paramMapCombined parameters.  
  58. // paramMapCombined overrides all parameters set earlier via lr.set* methods.  
  59. LogisticRegressionModel model2 = lr.fit(training, paramMapCombined);  
  60. System.out.println("Model 2 was fit using parameters: " + model2.parent().extractParamMap());  
  61.   
  62. // Prepare test documents.  
  63. List<Row> dataTest = Arrays.asList(  
  64.     RowFactory.create(1.0, Vectors.dense(-1.01.51.3)),  
  65.     RowFactory.create(0.0, Vectors.dense(3.02.0, -0.1)),  
  66.     RowFactory.create(1.0, Vectors.dense(0.02.2, -1.5))  
  67. );  
  68. Dataset<Row> test = spark.createDataFrame(dataTest, schema);  
  69.   
  70. // Make predictions on test documents using the Transformer.transform() method.  
  71. // LogisticRegression.transform will only use the 'features' column.  
  72. // Note that model2.transform() outputs a 'myProbability' column instead of the usual  
  73. // 'probability' column since we renamed the lr.probabilityCol parameter previously.  
  74. Dataset<Row> results = model2.transform(test);  
  75. Dataset<Row> rows = results.select("features""label""myProbability""prediction");  
  76. for (Row r: rows.collectAsList()) {  
  77.   System.out.println("(" + r.get(0) + ", " + r.get(1) + ") -> prob=" + r.get(2)  
  78.     + ", prediction=" + r.get(3));  
  79. }  
Python:

[python] view plain copy
  1. from pyspark.ml.linalg import Vectors  
  2. from pyspark.ml.classification import LogisticRegression  
  3.   
  4. # Prepare training data from a list of (label, features) tuples.  
  5. training = spark.createDataFrame([  
  6.     (1.0, Vectors.dense([0.01.10.1])),  
  7.     (0.0, Vectors.dense([2.01.0, -1.0])),  
  8.     (0.0, Vectors.dense([2.01.31.0])),  
  9.     (1.0, Vectors.dense([0.01.2, -0.5]))], ["label""features"])  
  10.   
  11. # Create a LogisticRegression instance. This instance is an Estimator.  
  12. lr = LogisticRegression(maxIter=10, regParam=0.01)  
  13. # Print out the parameters, documentation, and any default values.  
  14. print "LogisticRegression parameters:\n" + lr.explainParams() + "\n"  
  15.   
  16. # Learn a LogisticRegression model. This uses the parameters stored in lr.  
  17. model1 = lr.fit(training)  
  18.   
  19. # Since model1 is a Model (i.e., a transformer produced by an Estimator),  
  20. # we can view the parameters it used during fit().  
  21. # This prints the parameter (name: value) pairs, where names are unique IDs for this  
  22. # LogisticRegression instance.  
  23. print "Model 1 was fit using parameters: "  
  24. print model1.extractParamMap()  
  25.   
  26. # We may alternatively specify parameters using a Python dictionary as a paramMap  
  27. paramMap = {lr.maxIter: 20}  
  28. paramMap[lr.maxIter] = 30  # Specify 1 Param, overwriting the original maxIter.  
  29. paramMap.update({lr.regParam: 0.1, lr.threshold: 0.55})  # Specify multiple Params.  
  30.   
  31. # You can combine paramMaps, which are python dictionaries.  
  32. paramMap2 = {lr.probabilityCol: "myProbability"}  # Change output column name  
  33. paramMapCombined = paramMap.copy()  
  34. paramMapCombined.update(paramMap2)  
  35.   
  36. # Now learn a new model using the paramMapCombined parameters.  
  37. # paramMapCombined overrides all parameters set earlier via lr.set* methods.  
  38. model2 = lr.fit(training, paramMapCombined)  
  39. print "Model 2 was fit using parameters: "  
  40. print model2.extractParamMap()  
  41.   
  42. # Prepare test data  
  43. test = spark.createDataFrame([  
  44.     (1.0, Vectors.dense([-1.01.51.3])),  
  45.     (0.0, Vectors.dense([3.02.0, -0.1])),  
  46.     (1.0, Vectors.dense([0.02.2, -1.5]))], ["label""features"])  
  47.   
  48. # Make predictions on test data using the Transformer.transform() method.  
  49. # LogisticRegression.transform will only use the 'features' column.  
  50. # Note that model2.transform() outputs a "myProbability" column instead of the usual  
  51. # 'probability' column since we renamed the lr.probabilityCol parameter previously.  
  52. prediction = model2.transform(test)  
  53. selected = prediction.select("features""label""myProbability""prediction")  
  54. for row in selected.collect():  
  55.     print row  

管道示例:

Scala:

[plain] view plain copy
  1. import org.apache.spark.ml.{Pipeline, PipelineModel}  
  2. import org.apache.spark.ml.classification.LogisticRegression  
  3. import org.apache.spark.ml.feature.{HashingTF, Tokenizer}  
  4. import org.apache.spark.ml.linalg.Vector  
  5. import org.apache.spark.sql.Row  
  6.   
  7. // Prepare training documents from a list of (id, text, label) tuples.  
  8. val training = spark.createDataFrame(Seq(  
  9.   (0L, "a b c d e spark", 1.0),  
  10.   (1L, "b d", 0.0),  
  11.   (2L, "spark f g h", 1.0),  
  12.   (3L, "hadoop mapreduce", 0.0)  
  13. )).toDF("id", "text", "label")  
  14.   
  15. // Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.  
  16. val tokenizer = new Tokenizer()  
  17.   .setInputCol("text")  
  18.   .setOutputCol("words")  
  19. val hashingTF = new HashingTF()  
  20.   .setNumFeatures(1000)  
  21.   .setInputCol(tokenizer.getOutputCol)  
  22.   .setOutputCol("features")  
  23. val lr = new LogisticRegression()  
  24.   .setMaxIter(10)  
  25.   .setRegParam(0.01)  
  26. val pipeline = new Pipeline()  
  27.   .setStages(Array(tokenizer, hashingTF, lr))  
  28.   
  29. // Fit the pipeline to training documents.  
  30. val model = pipeline.fit(training)  
  31.   
  32. // Now we can optionally save the fitted pipeline to disk  
  33. model.write.overwrite().save("/tmp/spark-logistic-regression-model")  
  34.   
  35. // We can also save this unfit pipeline to disk  
  36. pipeline.write.overwrite().save("/tmp/unfit-lr-model")  
  37.   
  38. // And load it back in during production  
  39. val sameModel = PipelineModel.load("/tmp/spark-logistic-regression-model")  
  40.   
  41. // Prepare test documents, which are unlabeled (id, text) tuples.  
  42. val test = spark.createDataFrame(Seq(  
  43.   (4L, "spark i j k"),  
  44.   (5L, "l m n"),  
  45.   (6L, "mapreduce spark"),  
  46.   (7L, "apache hadoop")  
  47. )).toDF("id", "text")  
  48.   
  49. // Make predictions on test documents.  
  50. model.transform(test)  
  51.   .select("id", "text", "probability", "prediction")  
  52.   .collect()  
  53.   .foreach { case Row(id: Long, text: String, prob: Vector, prediction: Double) =>  
  54.     println(s"($id, $text) --> prob=$prob, prediction=$prediction")  
  55.   }  
Java:

[java] view plain copy
  1. import java.util.Arrays;  
  2.   
  3. import org.apache.spark.ml.Pipeline;  
  4. import org.apache.spark.ml.PipelineModel;  
  5. import org.apache.spark.ml.PipelineStage;  
  6. import org.apache.spark.ml.classification.LogisticRegression;  
  7. import org.apache.spark.ml.feature.HashingTF;  
  8. import org.apache.spark.ml.feature.Tokenizer;  
  9. import org.apache.spark.sql.Dataset;  
  10. import org.apache.spark.sql.Row;  
  11.   
  12. // Prepare training documents, which are labeled.  
  13. Dataset<Row> training = spark.createDataFrame(Arrays.asList(  
  14.   new JavaLabeledDocument(0L, "a b c d e spark"1.0),  
  15.   new JavaLabeledDocument(1L, "b d"0.0),  
  16.   new JavaLabeledDocument(2L, "spark f g h"1.0),  
  17.   new JavaLabeledDocument(3L, "hadoop mapreduce"0.0)  
  18. ), JavaLabeledDocument.class);  
  19.   
  20. // Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.  
  21. Tokenizer tokenizer = new Tokenizer()  
  22.   .setInputCol("text")  
  23.   .setOutputCol("words");  
  24. HashingTF hashingTF = new HashingTF()  
  25.   .setNumFeatures(1000)  
  26.   .setInputCol(tokenizer.getOutputCol())  
  27.   .setOutputCol("features");  
  28. LogisticRegression lr = new LogisticRegression()  
  29.   .setMaxIter(10)  
  30.   .setRegParam(0.01);  
  31. Pipeline pipeline = new Pipeline()  
  32.   .setStages(new PipelineStage[] {tokenizer, hashingTF, lr});  
  33.   
  34. // Fit the pipeline to training documents.  
  35. PipelineModel model = pipeline.fit(training);  
  36.   
  37. // Prepare test documents, which are unlabeled.  
  38. Dataset<Row> test = spark.createDataFrame(Arrays.asList(  
  39.   new JavaDocument(4L, "spark i j k"),  
  40.   new JavaDocument(5L, "l m n"),  
  41.   new JavaDocument(6L, "mapreduce spark"),  
  42.   new JavaDocument(7L, "apache hadoop")  
  43. ), JavaDocument.class);  
  44.   
  45. // Make predictions on test documents.  
  46. Dataset<Row> predictions = model.transform(test);  
  47. for (Row r : predictions.select("id""text""probability""prediction").collectAsList()) {  
  48.   System.out.println("(" + r.get(0) + ", " + r.get(1) + ") --> prob=" + r.get(2)  
  49.     + ", prediction=" + r.get(3));  
  50. }  
Python:

[python] view plain copy
  1. from pyspark.ml import Pipeline  
  2. from pyspark.ml.classification import LogisticRegression  
  3. from pyspark.ml.feature import HashingTF, Tokenizer  
  4.   
  5. # Prepare training documents from a list of (id, text, label) tuples.  
  6. training = spark.createDataFrame([  
  7.     (0"a b c d e spark"1.0),  
  8.     (1"b d"0.0),  
  9.     (2"spark f g h"1.0),  
  10.     (3"hadoop mapreduce"0.0)], ["id""text""label"])  
  11.   
  12. # Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.  
  13. tokenizer = Tokenizer(inputCol="text", outputCol="words")  
  14. hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")  
  15. lr = LogisticRegression(maxIter=10, regParam=0.01)  
  16. pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])  
  17.   
  18. # Fit the pipeline to training documents.  
  19. model = pipeline.fit(training)  
  20.   
  21. # Prepare test documents, which are unlabeled (id, text) tuples.  
  22. test = spark.createDataFrame([  
  23.     (4"spark i j k"),  
  24.     (5"l m n"),  
  25.     (6"mapreduce spark"),  
  26.     (7"apache hadoop")], ["id""text"])  
  27.   
  28. # Make predictions on test documents and print columns of interest.  
  29. prediction = model.transform(test)  
  30. selected = prediction.select("id""text""prediction")  
  31. for row in selected.collect():  
  32.     print(row)  

文章出處:https://blog.csdn.net/liulingyuan6/article/details/53576550

發佈了6 篇原創文章 · 獲贊 18 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章