📔
Data Science with Apache Spark
  • Preface
  • Contents
  • Basic Prerequisite Skills
  • Computer needed for this course
  • Spark Environment Setup
  • Dev environment setup, task list
  • JDK setup
  • Download and install Anaconda Python and create virtual environment with Python 3.6
  • Download and install Spark
  • Eclipse, the Scala IDE
  • Install findspark, add spylon-kernel for scala
  • ssh and scp client
  • Summary
  • Development environment on MacOS
  • Production Spark Environment Setup
  • VirtualBox VM
  • VirtualBox only shows 32bit on AMD CPU
  • Configure VirtualBox NAT as Network Adapter on Guest VM and Allow putty ssh Through Port Forwarding
  • Docker deployment of Spark Cluster
  • Create customized Apache Spark Docker container
  • Dockerfile
  • docker-compose and docker-compose.yml
  • Launch custom built Docker container with docker-compose
  • Entering Docker Container
  • Setup Hadoop, Hive and Spark on Linux without docker
  • Hadoop Preparation
  • Hadoop setup
  • Configure $HADOOP_HOME/etc/hadoop
  • HDFS
  • Start and stop Hadoop
  • Work with Hadoop and HDFS file system
  • Connect to Hadoop web interface port 50070 and 8088
  • Install Hive
  • hive home
  • Initialize hive schema
  • Start hive metastore service.
  • hive-site.xml
  • Hive client
  • Setup Apache Spark
  • Spark Home
  • Jupyter-notebook server
  • Python 3 Warm Up
  • Basics
  • Iterables/Collections
  • Strings
  • List
  • Tuple
  • Dictionary
  • Set
  • Conditional statement
  • for loop
  • while loop
  • Functions and methods
  • map and filter
  • map and filter takes function as input
  • lambda
  • Python Class
  • Input and if statement
  • Input from a file
  • Output to a file
  • try except
  • Python coding exercise
  • Scala Warm Up
  • Start Spylon-kernel on Jupyter-notebook
  • Type of Variable: Mutable or immutable
  • Block statement
  • Scala Data Type
  • Array in Scala
  • Methods
  • Functions
  • Anonymous function
  • Scala map and filter methods
  • Class
  • Objects
  • Trait
  • Tuple in Scala
  • List/Seq
  • Set in Scala
  • Scala Map
  • Scala if statement
  • Scala for loop
  • Scala While Loop
  • Scala Exceptions + try catch finally
  • Scala coding exercise
  • Run a program to estimate pi
  • Common Spark command line
  • Run Scala code with spark-submit
  • Python with Apache Spark using Jupyter notebook
  • Spark Core Introduction
  • Spark and Scala Version
  • Basic Spark Package
  • Resilient Distributed Datasets (RDDs)
  • RDD Operations
  • Passing Function to Spark
  • Printing elements of an RDD
  • Working with key value pair
  • RDD Transformation Functions
  • RDD Action Functions
  • SPARK SQL
  • SQL
  • Datasets and DataFrames
  • SparkSession
  • Creating DataFrames
  • Running SQL Queries Programmatically
  • Issue from running Cartesian Join Query
  • Creating Datasets
  • Interoperating with RDD
  • Untyped User-Defined Aggregate Functions
  • Generic Load/Save Functions
  • Manually specify file option
  • Run SQL on files directly
  • Save Mode
  • Saving to Persistent Tables
  • Bucketing, Sorting and Partitioning
  • Apache Arrow
  • Install Python Arrow Module PyArrow
  • Issue might happen import PyArrow
  • Enabling for Conversion to/from Pandas in Python
  • Connect to any data source the same consistent way
  • Spark SQL Implementation Example in Scala
  • Run scala code in Eclipse IDE
  • Hive Integration, run SQL or HiveQL queries on existing warehouses.
  • Example: Enrich JSON
  • Integrate Tableau Data Visualization with Hive Data Warehouse and Apache Spark SQL
  • Connect Tableau to Spark SQL running in VM with VirtualBox with NAT
  • Issues with connecting from Tableau to Spark SQL
  • SPARK Streaming
  • Discretized Streams (DStreams)
  • Transformations on DStreams
  • map(func)
  • filter(func)
  • repartition(numPartitions)
  • union(otherStream)
  • reduce(func)
  • count()
  • countByValue()
  • reduceByKey(func, [numTasks])
  • join(otherStream, [numTasks])
  • cogroup(otherStream, [numTasks])
  • transform(func)
  • updateStateByKey(func)
  • Scala Tips for updateStateByKey
  • repartition(numPartitions)
  • DStream Window Operations
  • DStream Window Transformation
  • countByWindow(windowLength, slideInterval)
  • reduceByWindow(func, windowLength, slideInterval)
  • reduceByKeyAndWindow(func, windowLength, slideInterval, [numTasks])
  • reduceByKeyAndWindow(func, invFunc, windowLength, slideInterval, [numTasks])
  • countByValueAndWindow(windowLength, slideInterval, [numTasks])
  • window(windowLength, slideInterval)
  • Window DStream print(n)
  • saveAsTextFiles(prefix, [suffix])
  • saveAsObjectFiles(prefix, [suffix])
  • saveAsHadoopFiles(prefix, [suffix])
  • foreachRDD(func)
  • Build Twitter Scala API Library for Spark Streaming using sbt
  • Spark Streaming with Twitter, you can get public tweets by using Twitter API.
  • Spark streaming use case with Python
  • Spark Graph Computing
  • Spark Graph Computing Continue
  • Graphx
  • Package org.apache.spark.graphx
  • Edge Class
  • EdgeContext Class
  • EdgeDirection Class
  • EdgeRDD Class
  • EdgeTriplet Class
  • Graph Class
  • GraphLoader Object
  • GraphOps Class
  • GraphXUtils Object
  • PartitionStrategy Trait
  • Pregel Object
  • TripletFields Class
  • VertexRDD Class
  • Package org.apache.spark.graphx.impl
  • AggregatingEdgeContext Class
  • EdgeRDDImpl Class
  • Class GraphImpl<VD,ED>
  • Class VertexRDDImpl<VD>
  • Package org.apache.spark.graphx.lib
  • Class ConnectedComponents
  • Class LabelPropagation
  • Class PageRank
  • Class ShortestPaths
  • Class StronglyConnectedComponents
  • Class SVDPlusPlus
  • Class SVDPlusPlus.Conf
  • Class TriangleCount
  • Package org.apache.spark.graphx.util
  • Class BytecodeUtils
  • Class GraphGenerators
  • Graphx Example 1
  • Graphx Example 2
  • Graphx Example 3
  • Spark Graphx Describes Organization Chart Easy and Fast
  • Page Rank with Apache Spark Graphx
  • bulk synchronous parallel with Google Pregel Graphx Implementation Use Cases
  • Tree and Graph Traversal with and without Spark Graphx
  • Graphx Graph Traversal with Pregel Explained
  • Spark Machine Learning
  • Binary Classification
  • Multiclass Classification
  • Regression
  • Correlation
  • Image Data Source
  • ML DataFrame is SQL DataFrame
  • ML Transformer
  • ML Estimator
  • ML Pipeline
  • Transformer/Estimator Parameters
  • Extracting, transforming and selecting features
  • TF-IDF
  • Word2Vec
  • FeatureHasher
  • Tokenizer
  • CountVectorizer
  • StopWordRemover
  • n-gram
  • Binarizer
  • PCA
  • PolynomialExpansion
  • StringIndexer
  • Discrete Cosine Transform (DCT)
  • One-hot encoding
  • StandardScaler
  • IndexToString
  • VectorIndexer
  • Interaction
  • Normalizer
  • MinMaxScaler
  • MaxAbScaler
  • Bucketizer
  • ElementwiseProduct
  • SQLTransformer
  • VectorAssembler
  • VectorSizeHint
  • QuantileDiscretizer
  • Imputer
  • VectorSlicer
  • RFormula
  • ChiSqSelector
  • Locality Sensitive Hashing
  • MinHash for Jaccard Distance
  • Classification and Regression
  • LogisticRegression
  • OneVsRest
  • Naive Bayes classifiers
  • Decision trees
  • Random forests
  • Gradient-boosted trees (GBTs)
  • Multilayer perceptron classifier
  • Linear Support Vector Machine
  • Linear Regression
  • Generalized linear regression
  • Isotonic regression
  • Decision Tree Regression
  • Random Forest Regression
  • Gradient-boosted tree regression
  • Survival regression
  • Clustering
  • k-means
  • Latent Dirichlet allocation or LDA
  • Bisecting k-means
  • A Gaussian Mixture Model
  • Collaborative filtering
  • Frequent Pattern Mining
  • FP-Growth
  • PrefixSpan
  • ML Tuning: model selection and hyperparameter tuning
  • Model selection (a.k.a. hyperparameter tuning)
  • Cross-Validation
  • Train-Validation Split
  • Spark Machine Learning Applications
  • Apache Spark SQL & Machine Learning on Genetic Variant Classifications
  • Data Visualization with Vegas Viz and Scala with Spark ML
  • Apache Spark Machine Learning with Dremio Data Lake Engine
  • Dremio Data Lake Engine Apache Arrow Flight Connector with Spark Machine Learning
  • Neural Network with Apache Spark Machine Learning Multilayer Perceptron Classifier
  • Setup TensorFlow, Keras, Theano, Pytorch/torchvision on the CentOS VM
  • Virus Xray Image Classification with Tensorflow Keras Python and Apache Spark Scala
  • Appendix -- Video Presentations
  • References
Powered by GitBook
On this page

Was this helpful?

Apache Spark Machine Learning with Dremio Data Lake Engine

PreviousData Visualization with Vegas Viz and Scala with Spark MLNextDremio Data Lake Engine Apache Arrow Flight Connector with Spark Machine Learning

Last updated 5 years ago

Was this helpful?

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:

LogoGitHub - geyungjen/jentekllc: Apache Spark Application Development -- George Jen, Jen Tek LLCGitHub
LogoCredit Card Fraud Detection
LogoDremio | SQL Data Lakehouse Platform for High-Performance BIDremio
LogoGitHub - dremio/dremio-oss: Dremio - the missing link in modern dataGitHub