Collecting all String Columns into an Array
%scala var StringfeatureCol = Array("FavoriteColor", "FavoriteMusicGenre", "FavoriteBeverage", "FavoriteSoftDrink", "Gender");
StringIndexer encodes a string column of labels to a column of label indices.
Example of StringIndexer
%scala import org.apache.spark.ml.feature.StringIndexer val df = spark.createDataFrame( Seq((0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")) ).toDF("id", "category") df.show() val indexer = new StringIndexer() .setInputCol("category") .setOutputCol("categoryIndex") val indexed = indexer.fit(df).transform(df) indexed.show() Output: +---+--------+ | id|category| +---+--------+ | 0| a| | 1| b| | 2| c| | 3| a| | 4| a| | 5| c| +---+--------+ +---+--------+-------------+ | id|category|categoryIndex| +---+--------+-------------+ | 0| a| 0.0| | 1| b| 2.0| | 2| c| 1.0| | 3| a| 0.0| | 4| a| 0.0| | 5| c| 1.0| +---+--------+-------------+
Define the Pipeline
A predictive model often requires multiple stages of feature preparation.
A pipeline consists of a series of transformer and estimator stages that typically prepare a DataFrame for modeling and then train a predictive model.
In this case, you will create a pipeline with stages:
- A StringIndexer estimator that converts string values to indexes for categorical features
- A VectorAssembler that combines categorical features into a single vector
%scala import org.apache.spark.ml.attribute.Attribute import org.apache.spark.ml.feature.{IndexToString, StringIndexer} import org.apache.spark.ml.{Pipeline, PipelineModel} val indexers = StringfeatureCol.map { colName => new StringIndexer().setInputCol(colName).setHandleInvalid("skip").setOutputCol(colName + "_indexed") } val pipeline = new Pipeline() .setStages(indexers) val GenderFinalDF = pipeline.fit(csv).transform(csv)
Print Schema to view String Columns are converted in to equivalent Numerical Columns
%scala GenderFinalDF.printSchema() Output: root |-- FavoriteColor: string (nullable = true) |-- FavoriteMusicGenre: string (nullable = true) |-- FavoriteBeverage: string (nullable = true) |-- FavoriteSoftDrink: string (nullable = true) |-- Gender: string (nullable = true) |-- FavoriteColor_indexed: double (nullable = false) |-- FavoriteMusicGenre_indexed: double (nullable = false) |-- FavoriteBeverage_indexed: double (nullable = false) |-- FavoriteSoftDrink_indexed: double (nullable = false) |-- Gender_indexed: double (nullable = false)
Display Data
%scala GenderFinalDF.show() Output: +-------------+------------------+----------------+-----------------+------+---------------------+--------------------------+------------------------+-------------------------+--------------+ |FavoriteColor|FavoriteMusicGenre|FavoriteBeverage|FavoriteSoftDrink|Gender|FavoriteColor_indexed|FavoriteMusicGenre_indexed|FavoriteBeverage_indexed|FavoriteSoftDrink_indexed|Gender_indexed| +-------------+------------------+----------------+-----------------+------+---------------------+--------------------------+------------------------+-------------------------+--------------+ | Cool| Rock| Vodka| 7UP/Sprite| F| 0.0| 0.0| 4.0| 2.0| 0.0| | Neutral| Hip hop| Vodka| Coca Cola/Pepsi| F| 2.0| 3.0| 4.0| 0.0| 0.0| | Warm| Rock| Wine| Coca Cola/Pepsi| F| 1.0| 0.0| 3.0| 0.0| 0.0| | Warm| Folk/Traditional| Whiskey| Fanta| F| 1.0| 5.0| 5.0| 1.0| 0.0| | Cool| Rock| Vodka| Coca Cola/Pepsi| F| 0.0| 0.0| 4.0| 0.0| 0.0| | Warm| Jazz/Blues| Doesn't drink| Fanta| F| 1.0| 6.0| 0.0| 1.0| 0.0| | Cool| Pop| Beer| Coca Cola/Pepsi| F| 0.0| 1.0| 1.0| 0.0| 0.0| | Warm| Pop| Whiskey| Fanta| F| 1.0| 1.0| 5.0| 1.0| 0.0| | Warm| Rock| Other| 7UP/Sprite| F| 1.0| 0.0| 2.0| 2.0| 0.0| | Neutral| Pop| Wine| Coca Cola/Pepsi| F| 2.0| 1.0| 3.0| 0.0| 0.0| | Cool| Pop| Other| 7UP/Sprite| F| 0.0| 1.0| 2.0| 2.0| 0.0| | Warm| Pop| Other| 7UP/Sprite| F| 1.0| 1.0| 2.0| 2.0| 0.0| | Warm| Pop| Wine| 7UP/Sprite| F| 1.0| 1.0| 3.0| 2.0| 0.0| | Warm| Electronic| Wine| Coca Cola/Pepsi| F| 1.0| 2.0| 3.0| 0.0| 0.0| | Cool| Rock| Beer| Coca Cola/Pepsi| F| 0.0| 0.0| 1.0| 0.0| 0.0| | Warm| Jazz/Blues| Wine| Coca Cola/Pepsi| F| 1.0| 6.0| 3.0| 0.0| 0.0| | Cool| Pop| Wine| 7UP/Sprite| F| 0.0| 1.0| 3.0| 2.0| 0.0| | Cool| Rock| Other| Coca Cola/Pepsi| F| 0.0| 0.0| 2.0| 0.0| 0.0| | Cool| Rock| Other| Coca Cola/Pepsi| F| 0.0| 0.0| 2.0| 0.0| 0.0| | Cool| Pop| Doesn't drink| 7UP/Sprite| F| 0.0| 1.0| 0.0| 2.0| 0.0| +-------------+------------------+----------------+-----------------+------+---------------------+--------------------------+------------------------+-------------------------+--------------+ only showing top 20 rows
Split the Data
It is common practice when building machine learning models to split the source data, using some of it to train the model and reserving some to test the trained model. In this project, you will use 70% of the data for training, and reserve 30% for testing.
%scala val splits = GenderFinalDF.randomSplit(Array(0.7, 0.3)) val train = splits(0) val test = splits(1) val train_rows = train.count() val test_rows = test.count() println("Training Rows: " + train_rows + " Testing Rows: " + test_rows)
Prepare the Training Data
To train the Classification model, you need a training data set that includes a vector of numeric features, and a label column. In this project, you will use the VectorAssembler class to transform the feature columns into a vector, and then rename the class column to the label.
VectorAssembler()
VectorAssembler(): is a transformer that combines a given list of columns into a single vector column. It is useful for combining raw features and features generated by different feature transformers into a single feature vector, in order to train ML models like logistic regression and decision trees.
VectorAssembler accepts the following input column types: all numeric types, boolean type, and vector type.
In each row, the values of the input columns will be concatenated into a vector in the specified order.
%scala import org.apache.spark.ml.feature.VectorAssembler val assembler = new VectorAssembler().setInputCols(Array("FavoriteColor_indexed", "FavoriteMusicGenre_indexed", "FavoriteBeverage_indexed", "FavoriteSoftDrink_indexed")).setOutputCol("features") val training = assembler.transform(train).select($"features", $"Gender_indexed".alias("label")) training.show(false) Output: +-----------------+-----+ |features |label| +-----------------+-----+ |[0.0,2.0,1.0,0.0]|1.0 | |[0.0,2.0,0.0,1.0]|1.0 | |[0.0,2.0,5.0,0.0]|1.0 | |[0.0,5.0,1.0,3.0]|1.0 | |[0.0,5.0,5.0,2.0]|0.0 | |[0.0,3.0,1.0,0.0]|1.0 | |[0.0,3.0,0.0,3.0]|1.0 | |[0.0,1.0,1.0,0.0]|0.0 | |[0.0,1.0,1.0,3.0]|0.0 | |[0.0,1.0,0.0,2.0]|0.0 | |(4,[1],[1.0]) |0.0 | |[0.0,1.0,0.0,3.0]|0.0 | |[0.0,1.0,2.0,2.0]|0.0 | |[0.0,1.0,2.0,1.0]|1.0 | |[0.0,1.0,5.0,1.0]|1.0 | |[0.0,1.0,5.0,3.0]|1.0 | |[0.0,1.0,3.0,2.0]|0.0 | |[0.0,4.0,1.0,0.0]|0.0 | |(4,[1],[4.0]) |1.0 | |[0.0,4.0,5.0,2.0]|1.0 | +-----------------+-----+ only showing top 20 rows
Train a Classification Model
Next, you need to train a Classification model using the training data. To do this, create an instance of the LogisticRegression algorithm you want to use and use its fit method to train a model based on the training DataFrame. In this project, you will use a Logistic Regression Classifier algorithm – though you can use the same technique for any of the regression algorithms supported in the spark.ml API
%scala import org.apache.spark.ml.classification.LogisticRegression val lr = new LogisticRegression().setLabelCol("label").setFeaturesCol("features").setMaxIter(10).setRegParam(0.3) val model = lr.fit(training) println ("Model trained!")
Prepare the Testing Data
Now that you have a trained model, you can test it using the testing data you reserved previously. First, you need to prepare the testing data in the same way as you did the training data by transforming the feature columns into a vector. This time you’ll rename the Gender_indexed column to trueLabel.
%scala val testing = assembler.transform(test).select($"features", $"Gender_indexed".alias("trueLabel")) testing.show(false) Output: +-----------------+---------+ |features |trueLabel| +-----------------+---------+ |[0.0,2.0,0.0,1.0]|0.0 | |[0.0,2.0,2.0,1.0]|1.0 | |[0.0,3.0,1.0,0.0]|1.0 | |[0.0,3.0,3.0,0.0]|1.0 | |[0.0,1.0,1.0,1.0]|0.0 | |(4,[2],[1.0]) |0.0 | |(4,[3],[3.0]) |1.0 | |[0.0,0.0,4.0,2.0]|0.0 | |(4,[2],[4.0]) |1.0 | |[0.0,0.0,3.0,2.0]|1.0 | |(4,[0],[2.0]) |1.0 | |[1.0,5.0,2.0,1.0]|1.0 | |[1.0,6.0,5.0,1.0]|0.0 | |[1.0,1.0,2.0,2.0]|0.0 | |[1.0,4.0,3.0,3.0]|1.0 | |[1.0,0.0,4.0,2.0]|1.0 | |[1.0,0.0,3.0,0.0]|0.0 | +-----------------+---------+
Test the Model
Now you’re ready to use the transform method of the model to generate some predictions. You can use this approach to predict the Class; but in this case, you are using the test data which includes a known true label value, so you can compare the Gender_indexed
%scala val prediction = model.transform(testing) val predicted = prediction.select("features", "prediction", "probability", "trueLabel") predicted.show(10) Output: +-----------------+----------+--------------------+---------+ | features|prediction| probability|trueLabel| +-----------------+----------+--------------------+---------+ |[0.0,2.0,0.0,1.0]| 1.0|[0.47829683206605...| 0.0| |[0.0,2.0,2.0,1.0]| 0.0|[0.51235808503214...| 1.0| |[0.0,3.0,1.0,0.0]| 1.0|[0.48559686229345...| 1.0| |[0.0,3.0,3.0,0.0]| 0.0|[0.5196601510649,...| 1.0| |[0.0,1.0,1.0,1.0]| 0.0|[0.51313294179282...| 0.0| | (4,[2],[1.0])| 0.0|[0.53895597011136...| 0.0| | (4,[3],[3.0])| 1.0|[0.49774123750921...| 1.0| |[0.0,0.0,4.0,2.0]| 0.0|[0.57344590678748...| 0.0| | (4,[2],[4.0])| 0.0|[0.58918683811116...| 1.0| |[0.0,0.0,3.0,2.0]| 0.0|[0.55669749160620...| 1.0| +-----------------+----------+--------------------+---------+