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 | SQL Lakehouse Platform for High-Performance BI
dremiohq
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:
GitHub - dremio/dremio-oss: Dremio - the missing link in modern data
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
Credit Card Fraud Detection
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:
1
/*
2
start with pulling Vegas-viz library jars from Maven repository, your machines need to connect to the internet
3
*/
4
import $ivy.`org.vegas-viz::vegas:0.3.11`
5
import $ivy.`org.vegas-viz::vegas-spark:0.3.11`
6
//You will see lots of downloads from running the above 2 lines
7
//Once done, you can import Vegas library for plotting
8
import vegas._
9
import vegas.render.WindowRenderer._
10
//Almond/Jupyter-scala does not integrated with Spark, so you will need to integrate it manually
11
//by download necessary jars from Maven, for the Spark libraries need to accomplish this demo
12
import $ivy.`org.jupyter-scala::spark:0.4.2`
13
import $ivy.`org.apache.spark::spark-sql:2.4.5`
14
//Again lots of downloads from above 2 lines, once download is done, you are ready to import
15
// Spark libs
16
import org.apache.spark.SparkContext._
17
import org.apache.spark.rdd._
18
import org.apache.spark.util.LongAccumulator
19
import org.apache.log4j._
20
import org.apache.spark.sql._
21
import org.apache.spark.sql.{Row, SparkSession}
22
import org.apache.spark.sql.types.{DoubleType, StringType, StructField, StructType}
23
//Create Spark session
24
Logger.getLogger(“org”).setLevel(Level.ERROR)
25
val spark = SparkSession
26
.builder
27
.appName(“Dremio-Vegas”)
28
.master(“local[*]”)
29
.config(“spark.sql.warehouse.dir”, “file:///tmp”)
30
.getOrCreate()
31
import spark.implicits._
32
import spark.sql
33
//and SparkContext sc
34
val sc = spark.sparkContext
35
val sqlContext = new SQLContext(sc)
36
import sqlContext.implicits._
37
//import java.nio.charset.Charset, set JDBC class path to point to jdbc jar file
38
import java.nio.file.{FileSystem, FileSystems, Files}
39
import ammonite.ops._
40
//val path = java.nio.file.FileSystems.getDefault().getPath(“/opt/spark/jars/dremio-jdbc-driver-4.1.8–202003120636020140–9c2a6b13.jar”)
41
val path = java.nio.file.FileSystems.getDefault().getPath(“/opt/hadoop/dremio/dremio-jdbc-driver-3.0.6–201812082352540436–1f684f9.jar”)
42
val x = ammonite.ops.Path(path)
43
println(x)
44
x.getClass
45
interp.load.cp(x)
46
//Load data via JDBC from Dremio to Spark dataframe
47
var jdbcDF = spark.read
48
.format(“jdbc”)
49
.option(“url”, “jdbc:dremio:direct=10.0.2.15:31010”)
50
.option(“dbtable”, “fraud.dremio.\”creditcard.csv\””)
51
.option(“header”,”true”)
52
.option(“user”, “george”)
53
.option(“password”, “<redacted>”)
54
.load()
55
//All of the feature and label columns are numeric, but in String type, need to correct to numeric
56
//datatype such as double and int for any ML code to process the data set
57
val df_with_datatype=jdbcDF.selectExpr(
58
“cast(V1 as double) V1”,
59
“cast(V2 as double) V2”,
60
“cast(V3 as double) V3”,
61
“cast(V4 as double) V4”,
62
“cast(V5 as double) V5”,
63
“cast(V6 as double) V6”,
64
“cast(V7 as double) V7”,
65
“cast(V8 as double) V8”,
66
“cast(V9 as double) V9”,
67
“cast(V10 as double) V10”,
68
“cast(V11 as double) V11”,
69
“cast(V12 as double) V12”,
70
“cast(V13 as double) V13”,
71
“cast(V14 as double) V14”,
72
“cast(V15 as double) V15”,
73
“cast(V16 as double) V16”,
74
“cast(V17 as double) V17”,
75
“cast(V18 as double) V18”,
76
“cast(V19 as double) V19”,
77
“cast(V20 as double) V20”,
78
“cast(V21 as double) V21”,
79
“cast(V22 as double) V22”,
80
“cast(V23 as double) V23”,
81
“cast(V24 as double) V24”,
82
“cast(V25 as double) V25”,
83
“cast(V26 as double) V26”,
84
“cast(V27 as double) V27”,
85
“cast(V28 as double) V28”,
86
“cast(Amount as double) Amount”,
87
“cast(Class as int) Label”
88
)
89
/*
90
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.
91
*/
92
import $ivy.`org.apache.spark::spark-mllib:2.4.5`
93
import org.apache.spark.ml.feature.VectorAssembler
94
val vectorAssembler = new VectorAssembler().setInputCols(Array(
95
“V1”,
96
“V2”,
97
“V3”,
98
“V4”,
99
“V5”,
100
“V6”,
101
“V7”,
102
“V8”,
103
“V9”,
104
“V10”,
105
“V11”,
106
“V12”,
107
“V13”,
108
“V14”,
109
“V15”,
110
“V16”,
111
“V17”,
112
“V18”,
113
“V19”,
114
“V20”,
115
“V21”,
116
“V22”,
117
“V23”,
118
“V24”,
119
“V25”,
120
“V26”,
121
“V27”,
122
“V28”,
123
“Amount”
124
)).setOutputCol(“features”)
125
var vector_df = vectorAssembler.setHandleInvalid(“skip”).transform(df_with_datatype)
126
vector_df.select(“features”,”Label”).show(5)
Copied!
1
/*
2
Replace any NaN value to 0
3
*/
4
vector_df = vector_df.select(“features”, “Label”).sort(“features”).na.fill(0)
5
/*
6
Split the dataset dataframe to 70% training and 30% testing
7
*/
8
val splits = vector_df.randomSplit(Array(0.7,0.3))
9
val train_df=splits(0)
10
val test_df = splits(1)
11
/*
12
Start logistic regression model training
13
*/
14
import org.apache.spark.ml.{Pipeline, PipelineStage}
15
import org.apache.spark.ml.classification.{LogisticRegression, LogisticRegressionModel}
16
import org.apache.spark.ml.feature.StringIndexer
17
import org.apache.spark.sql.{DataFrame, SparkSession}
18
import scala.collection.mutable
19
val maxIter=100
20
val lr = new LogisticRegression()
21
.setFeaturesCol(“features”)
22
.setLabelCol(“Label”)
23
.setMaxIter(maxIter)
24
val model_lr = lr.fit(train_df)
25
model_lr: LogisticRegressionModel = LogisticRegressionModel: uid = logreg_28c0c9529ab1, numClasses = 2, numFeatures = 29
26
val prediction_lr = model_lr.transform(test_df)
27
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator
28
val my_eval_aoc = new BinaryClassificationEvaluator()
29
.setLabelCol(“Label”)
30
.setRawPredictionCol(“prediction”).setMetricName(“areaUnderROC”)
31
my_eval_aoc.evaluate(prediction_lr)
32
my_eval_aoc: BinaryClassificationEvaluator = binEval_2f8b38d8b5fd
33
/*
34
Output:
35
res23_1: Double = 0.8005318699909603
36
*/
37
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
38
var my_mc_f1 = new MulticlassClassificationEvaluator().setPredictionCol(“prediction”).setLabelCol(“Label”).setMetricName(“f1”)
39
my_mc_f1.evaluate(prediction_lr)
40
my_mc_f1: MulticlassClassificationEvaluator = mcEval_085fc21c9811
41
/*
42
Output:
43
res25_2: Double = 0.9989954059928168
44
*/
45
val my_mc_accu = new MulticlassClassificationEvaluator().setPredictionCol(“prediction”).setLabelCol(“Label”).setMetricName(“accuracy”)
46
my_mc_accu.evaluate(prediction_lr)
47
my_mc_accu: MulticlassClassificationEvaluator = mcEval_d4e2e453c7fa
48
/*
49
Output:
50
res27_1: Double = 0.9990805293357697
51
*/
52
val train_fit_lr = prediction_lr.select(“Label”,”prediction”)
53
train_fit_lr.groupBy(“Label”,”prediction”).count().show()
Copied!
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:
GitHub - geyungjen/jentekllc: Apache Spark Application Development -- George Jen, Jen Tek LLC
GitHub
Last modified 1yr ago
Copy link