Apache Spark Machine Learning with Dremio Data Lake Engine

Define data lake!

According to Wikipedia:

A data lake is a system or repository of data stored in its natural/raw format, usually object blobs or files. A data lake is usually a single store of all enterprise data including raw copies of source system data and transformed data used for tasks such as reporting, visualization, advanced analytics and machine learning. A data lake can include structured data from relational databases (rows and columns), semi-structured data (CSV, logs, XML, JSON), unstructured data (emails, documents, PDFs) and binary data (images, audio, video).

In simple term, data lake is like a giant melting pot (like the United States) of data of all formats, structured such as RDBMS tables, non-structured such as NoSQL entities, of any kind, you grab whatever you want to see from the pot.

I have explored a software product, "data lake engine", called Dremio:

Dremio’s query engine is built on Apache Arrow, which is an in memory columnar data structure. Its SQL engine allows you to use SQL to query structured data such as relational database tables or non-structure such as key value pairs entities such as JSON, it is a distributed/clustered and in memory columnar query engine, that can run on one node or many nodes.

While there is commercial version available, there is also an open source version of Dremio that can be gotten from GitHub:

My experiments on Dremio starts from cloning from Dremio’s GitHub repo, the open source version on a CentOS7 Linux VM.

Dremio is written in Java, so JDK 8 and Maven 3.3.9 or better are pre-requisites. After git clone the Dremio, simply run below mvn command to build, make sure your mvn version must be 3.3.9 or better to build successfully. If you do not have mvn 3.3.9 or better, there is a mvnw that comes from GitHub repo.

mvn clean install -DskipTests

or

mvnw clean install -DskipTests

Additionally, it is better to build and run Dremio in its own OS user account, not to share user account that run other software, to avoid any issue down the road.

I initially build Dremio using existing Linux user that owns and run Hadoop, HIVE and Spark, but I run into issue when starting Dremio, got messages resulted from

SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/opt/hadoop/hive/lib/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/opt/hadoop/share/hadoop/common/lib/slf4j-log4j12–1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]

Dremio instance did not start. While it is fixable by excluding unwanted SLF4J from classpath, but it would be easier and cleaner to build and run Dremio from OS user called dremio, instead of hadoop OS user.

Dremio has its own zookeeper service, but can use external one if there is one already running and listening to port 2181. Because I have Kafka running on the same VM, which has zookeeper, therefore, need to enable using external zookeeper, disable embedded zookeeper in Dremio configuration.

services.coordinator.master.embedded-zookeeper.enabled: false zookeeper: “10.0.2.15:2181,localhost:2181”

By default, Dremio server listens to address localhost, I made it to listen to all network interfaces including localhost by specifying IP address 0.0.0.0

registration.publish-host: 0.0.0.0

Once Dremio is built and started, I can log into Dremio UI by

http://<hostname>:9047

I can also add variety of data sources from Dremio to catalog them:

I can query, using SQL against JSON (nested) records:

After download JDBC driver from Dremio, I can connect JDBC client, I use SQLWorkbench, which is open source client to connect to Dremio and run queries

Once Dremio is up and running, JDBC connectivity is setup, my next task is to integrate Apache Spark with Dremio, using Dremio as repository, which can connect to hundreds of enterprise data sources in the data lake.

First task I want to play with is to run Apache Spark Machine Learning model on dataset stored on Hadoop, that is connected to Dremio as data source, that Dremio is going to supply to Apache Spark via JDBC connectivity.

To start, I need a dataset. Found one on Kaggle, called creditcardfraud

Here is the description from Kaggle:

Context

It is important that credit card companies are able to recognize fraudulent credit card transactions so that customers are not charged for items that they did not purchase.

Content

The datasets contain transactions made by credit cards in September 2013 by European cardholders.

This dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions. The dataset is highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.

It contains only numerical input variables which are the result of a PCA transformation. Unfortunately, due to confidentiality issues, we cannot provide the original features and more background information about the data. Features V1, V2, … V28 are the principal components obtained with PCA, the only features which have not been transformed with PCA are 'Time' and 'Amount'. Feature 'Time' contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature 'Amount' is the transaction Amount, this feature can be used for example-dependent cost-sensitive learning. Feature 'Class' is the response variable and it takes value 1 in case of fraud and 0 otherwise.

I downloaded the data file creditcard.csv and place it in an HDFS file system:

hdfs dfs -ls /dremio/

Found 2 items -rw-r — r — 3 hadoop supergroup 150828753 2020–03–14 16:20 /dremio/creditcard.csv

Load the Hadoop HDFS source /dremio/creditcard.csv into Dremio:

Once the link in Dremio that points to HDFS /dremio/creditcard.csv, I can start the work on Apache Spark:

I use logistic regression for the modeling, given this is binary classifier (fraud or no fraud).

Launch jupyter-notebook and start a Jupyter-Scala kernel, following is the code:

/*
start with pulling Vegas-viz library jars from Maven repository, your machines need to connect to the internet
*/
import $ivy.`org.vegas-viz::vegas:0.3.11`
import $ivy.`org.vegas-viz::vegas-spark:0.3.11`
//You will see lots of downloads from running the above 2 lines
//Once done, you can import Vegas library for plotting
import vegas._
import vegas.render.WindowRenderer._
//Almond/Jupyter-scala does not integrated with Spark, so you will need to integrate it manually
//by download necessary jars from Maven, for the Spark libraries need to accomplish this demo
import $ivy.`org.jupyter-scala::spark:0.4.2`
import $ivy.`org.apache.spark::spark-sql:2.4.5`
//Again lots of downloads from above 2 lines, once download is done, you are ready to import
// Spark libs
import org.apache.spark.SparkContext._
import org.apache.spark.rdd._
import org.apache.spark.util.LongAccumulator
import org.apache.log4j._
import org.apache.spark.sql._
import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{DoubleType, StringType, StructField, StructType}
//Create Spark session
Logger.getLogger(“org”).setLevel(Level.ERROR)
val spark = SparkSession
.builder
.appName(“Dremio-Vegas”)
.master(“local[*]”)
.config(“spark.sql.warehouse.dir”, “file:///tmp”)
.getOrCreate()
import spark.implicits._
import spark.sql
//and SparkContext sc
val sc = spark.sparkContext
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._
//import java.nio.charset.Charset, set JDBC class path to point to jdbc jar file
import java.nio.file.{FileSystem, FileSystems, Files}
import ammonite.ops._
//val path = java.nio.file.FileSystems.getDefault().getPath(“/opt/spark/jars/dremio-jdbc-driver-4.1.8–202003120636020140–9c2a6b13.jar”)
val path = java.nio.file.FileSystems.getDefault().getPath(“/opt/hadoop/dremio/dremio-jdbc-driver-3.0.6–201812082352540436–1f684f9.jar”)
val x = ammonite.ops.Path(path)
println(x)
x.getClass
interp.load.cp(x)
//Load data via JDBC from Dremio to Spark dataframe
var jdbcDF = spark.read
.format(“jdbc”)
.option(“url”, “jdbc:dremio:direct=10.0.2.15:31010”)
.option(“dbtable”, “fraud.dremio.\”creditcard.csv\””)
.option(“header”,”true”)
.option(“user”, “george”)
.option(“password”, “<redacted>”)
.load()
//All of the feature and label columns are numeric, but in String type, need to correct to numeric
//datatype such as double and int for any ML code to process the data set
val df_with_datatype=jdbcDF.selectExpr(
“cast(V1 as double) V1”,
“cast(V2 as double) V2”,
“cast(V3 as double) V3”,
“cast(V4 as double) V4”,
“cast(V5 as double) V5”,
“cast(V6 as double) V6”,
“cast(V7 as double) V7”,
“cast(V8 as double) V8”,
“cast(V9 as double) V9”,
“cast(V10 as double) V10”,
“cast(V11 as double) V11”,
“cast(V12 as double) V12”,
“cast(V13 as double) V13”,
“cast(V14 as double) V14”,
“cast(V15 as double) V15”,
“cast(V16 as double) V16”,
“cast(V17 as double) V17”,
“cast(V18 as double) V18”,
“cast(V19 as double) V19”,
“cast(V20 as double) V20”,
“cast(V21 as double) V21”,
“cast(V22 as double) V22”,
“cast(V23 as double) V23”,
“cast(V24 as double) V24”,
“cast(V25 as double) V25”,
“cast(V26 as double) V26”,
“cast(V27 as double) V27”,
“cast(V28 as double) V28”,
“cast(Amount as double) Amount”,
“cast(Class as int) Label”
)
/*
Spark ML requires training and testing data set in vector format, the dataframe needs to have 2 columns, “features” and “label”, “features” is a vector that has all the variables, label is the prediction target.
*/
import $ivy.`org.apache.spark::spark-mllib:2.4.5`
import org.apache.spark.ml.feature.VectorAssembler
val vectorAssembler = new VectorAssembler().setInputCols(Array(
“V1”,
“V2”,
“V3”,
“V4”,
“V5”,
“V6”,
“V7”,
“V8”,
“V9”,
“V10”,
“V11”,
“V12”,
“V13”,
“V14”,
“V15”,
“V16”,
“V17”,
“V18”,
“V19”,
“V20”,
“V21”,
“V22”,
“V23”,
“V24”,
“V25”,
“V26”,
“V27”,
“V28”,
“Amount”
)).setOutputCol(“features”)
var vector_df = vectorAssembler.setHandleInvalid(“skip”).transform(df_with_datatype)
vector_df.select(“features”,”Label”).show(5)
/*
Replace any NaN value to 0
*/
vector_df = vector_df.select(“features”, “Label”).sort(“features”).na.fill(0)
/*
Split the dataset dataframe to 70% training and 30% testing
*/
val splits = vector_df.randomSplit(Array(0.7,0.3))
val train_df=splits(0)
val test_df = splits(1)
/*
Start logistic regression model training
*/
import org.apache.spark.ml.{Pipeline, PipelineStage}
import org.apache.spark.ml.classification.{LogisticRegression, LogisticRegressionModel}
import org.apache.spark.ml.feature.StringIndexer
import org.apache.spark.sql.{DataFrame, SparkSession}
import scala.collection.mutable
val maxIter=100
val lr = new LogisticRegression()
.setFeaturesCol(“features”)
.setLabelCol(“Label”)
.setMaxIter(maxIter)
val model_lr = lr.fit(train_df)
model_lr: LogisticRegressionModel = LogisticRegressionModel: uid = logreg_28c0c9529ab1, numClasses = 2, numFeatures = 29
val prediction_lr = model_lr.transform(test_df)
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator
val my_eval_aoc = new BinaryClassificationEvaluator()
.setLabelCol(“Label”)
.setRawPredictionCol(“prediction”).setMetricName(“areaUnderROC”)
my_eval_aoc.evaluate(prediction_lr)
my_eval_aoc: BinaryClassificationEvaluator = binEval_2f8b38d8b5fd
/*
Output:
res23_1: Double = 0.8005318699909603
*/
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
var my_mc_f1 = new MulticlassClassificationEvaluator().setPredictionCol(“prediction”).setLabelCol(“Label”).setMetricName(“f1”)
my_mc_f1.evaluate(prediction_lr)
my_mc_f1: MulticlassClassificationEvaluator = mcEval_085fc21c9811
/*
Output:
res25_2: Double = 0.9989954059928168
*/
val my_mc_accu = new MulticlassClassificationEvaluator().setPredictionCol(“prediction”).setLabelCol(“Label”).setMetricName(“accuracy”)
my_mc_accu.evaluate(prediction_lr)
my_mc_accu: MulticlassClassificationEvaluator = mcEval_d4e2e453c7fa
/*
Output:
res27_1: Double = 0.9990805293357697
*/
val train_fit_lr = prediction_lr.select(“Label”,”prediction”)
train_fit_lr.groupBy(“Label”,”prediction”).count().show()

As the provider of this dataset said:

The dataset is highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.

I am not surprised the 0.999 prediction accuracy, which is too good to be true. But my goal in this exercise is to demonstrate that data scientists and data engineers can leverage Dremio as an end point access to vast data lake to supply data sources to applications running on Apache Spark, including, but not limiting to, machine learning with Apache Spark.

This, has served my purpose for this exercise.

As always, code used in this writing is in my GitHub repo:

Last updated