Search

Fundamentals of Apache Spark

IntroductionBefore getting into the fundamentals of Apache Spark, let’s understand What really is ‘Apache Spark’ is? Following is the authentic one-liner definition.Apache Spark is a fast and general-purpose, cluster computing system.One would find multiple definitions when you search the term Apache Spark. All of those give similar gist, just different words. Let’s understand these special keywords which describe Apache Spark. Fast: As spark uses in-memory computing it’s fast. It can run queries 100x faster. We will get to details of architecture later to understand this aspect better little later in the article. One would find the keywords ‘Fast’ and/or ‘In-memory’ in all the definitions. General Purpose: Apache spark is a unified framework. It provides one execution model for all tasks and hence very easy for developers to learn and they can work with multiple APIs easily. Spark offers over 80 high-level operators that make it easy to build parallel apps and one can use it interactively from the Scala, Python, R, and SQL shells.Spark powers a stack of libraries including SQL and DataFrames, MLlib for machine learning, GraphX, and Spark Streaming. You can combine these libraries seamlessly in the same application.Cluster Computing: Efficient processing of data on Set of computers (Refer commodity hardware here) or distributed systems. It’s also called a Parallel Data processing Engine in a few definitions. Spark is utilized for Big data analytics and related processing. One more important keyword associated with Spark is Open Source. It was open-sourced in 2010 under a   BSD license.Spark (and its RDD) was developed(earliest version as it’s seen today), in 2012, in response to limitations in the   MapReduce cluster computing paradigm. Spark is commonly seen as an in-memory replacement of MapReduce.Since its release, Apache Spark has seen rapid adoption due to its characteristics briefly discussed above.Who should go for Apache SparkBefore trying to find out whether Apache spark is for me? Or whether I have the right skill set, It's important to focus on the generality characteristic in further depth.Apache Spark consists of Spark Core and a set of libraries. The core is the distributed execution engine and the Java, Scala, and Python APIs offer a platform for distributed ETL application development. Additional libraries, built atop the core, allow diverse workloads for streaming, SQL, and machine learning.As Spark provides these multiple components, it’s evident that Spark is developed and widely utilized for big data and analytics.  Professionals who should learn Apache SparkIf one is aspiring to be landed into the following professions or anyone who has an interest in data and insights, Knowledge of spark will prove useful:Data ScientistsData EngineersPrerequisites of learning Apache SparkMost of the students looking for big data training, Apache spark is number one framework in big data. So most of the knowledge seekers looking for spark training, it is important to note that there are few prerequisites to learn apache spark.Before getting into Big data, you must have minimum knowledge on:Anyone of the programming languages >> Core   Python or Scala.Spark installations can be done on any platform but its framework is similar to Hadoop and hence having knowledge of HDFS and YARN is highly recommended. Having knowledge of Hive is an added advantage but is not mandatory.Basic knowledge of SQL. In SQL mainly select * from, joins and group by these three commands highly recommended.Optionally, knowing any cloud technology like AWS. Recommended for those who want to work with production-like environments.System requirements of Apache SparkOfficial site for  Apache Spark gives following recommendation (Traverse link for further details)Storage System: There are few ways to set this up as follows: Spark can run on the same node as HDFS. Spark standalone node cluster can be installed on the same nodes and configure Spark and Hadoop memory and CPU usage accordingly to avoid any interference.Or,1. Hadoop and Spark can execute on common Resource Manager ( Ex. Yarn etc)Or,2. Spark will be executing in same Local Area Network as HDFS but on separate nodes.Or3. If a requirement is a quick response and low latency from data stores then execute compute jobs on separate nodes than that of storage nodes.Local Disks: Typically 4-8 disks per node, configured without RAID.If underline OS is Linux then mount the disk with noatime option and in Spark environment configure spark.local.dir variable to be a comma-separated list of local disks.Note: For HDFS, it can be the same disk as HDFS.Memory: Minimum 8GB - 100s of GBs of memory per machine.A recommendation is the allocation of 75% of the memory to Spark.Network: 10GB or faster speed network.CPU cores: 8-16 Cores per machineHowever, for Training and Learning purpose and just to taste Spark, following are two available options: Run it locally Use AWS EMR (Or any cloud computing service)For learning purposes, minimum 4gb ram system with minimum 30gb disk may prove enough.History of Apache SparkSpark was primarily developed to Overcome the Limitations of MapReduce.Versioning: Spark initial version was version 0, version 1.6 is assumed to be a stable version and is being used in multiple commercial corporate projects. Version 2.3 is the latest available version. MapReduce is cluster computing  paradigm, which forces a particular linear  data flow structure on distributed programs: MapReduce programs read input data from disk,  map a function across the data,  reduce the results of the map, and store reduction results on disk. Due to multiple copies of data and multiple I/O as described, MapReduce takes lots of time to process the volume of data. MapReduce can do only batch time processing and is unsuitable for real-time data processingIt is unsuitable for trivial join like transformations. It’s unfit for large data on a network and also with OLTP data.Also, not suitable for graphics and interactive data.Spark overcomes all these limitations and able to do faster processing too on the local disk as well.Why Apache Spark?Numerous advantages of Spark have made its a market favorite.Let’s discuss one by one.Speed: Extends MapReduce Model to support computations like stream processing and interactive queries.Single Combination for processes and multiple tools:  Covers multiple workloads ( in a traditional system, it used to require different distributed systems), which makes combining different processing types and ease of tool management.Unification: Developers have to learn only one platform unlike multiple languages and tools in a traditional system.Support to different Resource Managers: Spark supports Hadoop HDFS system, and YARN for resource management but it’s not the only resource manager it supports. It works on MESOS and on any standalone scheduler like spark resource manager.Support for cutting-edge Innovation: Spark provides capabilities and support for an array of new-age technologies ranging from built-in machine learning libraries,   visualization tools, support for near processing (which was in a way the biggest challenge pre- spark era) and supports seamless integration with other deep learning frameworks like TensorFlow. This enables Spark to provide an innovative solution for new age use-cases.Spark can access diverse data sources and make sense of them all and hence it’s trending in the market over any other cluster computing software available. Who uses Apache SparkListing a few use cases of Apache spark below :1. Analytics - Spark can be very useful when building real-time analytics from a stream of incoming data.2. E-commerce - Information about the real-time transaction can be passed to streaming clustering algorithms like alternating least squares or K-means clustering algorithm. The results can be combined with data from other sources like social media profiles, product reviews on forums, customer comments, etc. to enhance the recommendations to customers based on new trends.Shopify: At Shopify, we underwrite credit card transactions, exposing us to the risk of losing money. We need to respond to risky events as they happen, and a traditional ETL pipeline just isn’t fast enough. Spark Streaming is an incredibly powerful real-time data processing framework based on Apache Spark. It allows you to process real-time streams like Apache Kafka using Python with incredible simplicity.Alibaba: Alibaba Taobao operates one of the world’s largest e-commerce platforms. We collect hundreds of petabytes of data on this platform and use Apache Spark to analyze these enormous amounts of data.3. Healthcare Industry –Healthcare has multiple use-cases of unstructured data to be processed in real-time. It has data ranging from image formats like scans etc to specific medical industry standards and wearable tracking devices. Many healthcare providers are keen on using spark for patient’s records to build 360 degrees view of the patient to do accurate diagnosis.MyFitnessPal: MyFitnessPal needed to deliver a new feature called “Verified Foods.” The feature demanded a faster pipeline to execute a number of highly sophisticated algorithms. Their legacy non-distributed Java-based data pipeline was slow, did not scale, and lacked flexibility.Here are a few other examples from industry leaders:Regeneron: Future of Drug Discovery with Genomics at Scale powered by SparkZeiss: Using Spark Structured Streaming for Predictive MaintenanceDevon Energy: Scaling Geographic Analytics with Spark GraphXYou can also learn more about use cases of Apache Spark  here.Career Benefits:Career Benefits of Spark for you as an individual:Apache Spark developers earn the highest average salary among all other programmers. According to its  2015 Data Science Salary Survey, O’Reilly found strong correlations between those who used Apache Spark and those who were paid more money. In one of its models, using Spark added more than $11,000 to the median salary.If you’re considering switching to this extremely in-demand career then taking up the  Apache Spark training will be an added advantage. Learning Spark will give you a steep competitive edge and can land you up in market best-paying jobs with top companies. Spark has gained enough adherents over the years to place it high on the list of fastest-growing skills; data scientists and sysadmins have evaluated the technology and clearly seen what they liked.  April’s Dice Report explored the fastest-growing technology skills, based on an analysis of job postings and data from Dice’s annual salary survey. The results are below; percentages are based on year-over-year growth in job postings:Benefits of Spark implementing Spark in your organization:Apache spark is now a decade older but still going strong. Due to lightning-fast processing and numerous other advantages discussed so far, Spark is still the first choice of many organizations.Spark is considered to be the most popular open-source project on the planet, with more than 1,000 contributors from 250-plus organizations, according to Databricks.ConclusionTo sum up, Spark helps to simplify the computationally intensive task of processing high volumes of real-time or batch data. It can seamlessly integrate with complex capabilities such as machine learning and graph algorithms. In short, Spark brings exclusive Big Data processing (which earlier was only for giant companies like Google) to the masses.Do let us know how your learning experience was, through comments below.Happy Learning!!!

Fundamentals of Apache Spark

10K
Fundamentals of Apache Spark

Introduction

Before getting into the fundamentals of Apache Spark, let’s understand What really is ‘Apache Spark’ is? Following is the authentic one-liner definition.

Apache Spark is a fast and general-purpose, cluster computing system.

One would find multiple definitions when you search the term Apache Spark. All of those give similar gist, just different words. Let’s understand these special keywords which describe Apache Spark. 

Fast: As spark uses in-memory computing it’s fast. It can run queries 100x faster. We will get to details of architecture later to understand this aspect better little later in the article. One would find the keywords ‘Fast’ and/or ‘In-memory’ in all the definitions. 

General Purpose: Apache spark is a unified framework. It provides one execution model for all tasks and hence very easy for developers to learn and they can work with multiple APIs easily. Spark offers over 80 high-level operators that make it easy to build parallel apps and one can use it interactively from the Scala, Python, R, and SQL shells.

Spark powers a stack of libraries including SQL and DataFrames, MLlib for machine learning, GraphX, and Spark Streaming. You can combine these libraries seamlessly in the same application.

Cluster Computing: Efficient processing of data on Set of computers (Refer commodity hardware here) or distributed systems. It’s also called a Parallel Data processing Engine in a few definitions. Spark is utilized for Big data analytics and related processing. 

One more important keyword associated with Spark is Open Source. It was open-sourced in 2010 under a   BSD license.

Spark (and its RDD) was developed(earliest version as it’s seen today), in 2012, in response to limitations in the   MapReduce cluster computing paradigm. Spark is commonly seen as an in-memory replacement of MapReduce.

Since its release, Apache Spark has seen rapid adoption due to its characteristics briefly discussed above.

Who should go for Apache Spark

Before trying to find out whether Apache spark is for me? Or whether I have the right skill set, It's important to focus on the generality characteristic in further depth.

Apache Spark consists of Spark Core and a set of libraries. The core is the distributed execution engine and the Java, Scala, and Python APIs offer a platform for distributed ETL application development. Additional libraries, built atop the core, allow diverse workloads for streaming, SQL, and machine learning.

Who should go for Apache Spark

As Spark provides these multiple components, it’s evident that Spark is developed and widely utilized for big data and analytics.  

Professionals who should learn Apache Spark

If one is aspiring to be landed into the following professions or anyone who has an interest in data and insights, Knowledge of spark will prove useful:

  • Data Scientists
  • Data Engineers

Prerequisites of learning Apache Spark

Most of the students looking for big data training, Apache spark is number one framework in big data. So most of the knowledge seekers looking for spark training, it is important to note that there are few prerequisites to learn apache spark.

Before getting into Big data, you must have minimum knowledge on:

  • Anyone of the programming languages >> Core   Python or Scala.
  • Spark installations can be done on any platform but its framework is similar to Hadoop and hence having knowledge of HDFS and YARN is highly recommended. Having knowledge of Hive is an added advantage but is not mandatory.
  • Basic knowledge of SQL. In SQL mainly select * from, joins and group by these three commands highly recommended.
  • Optionally, knowing any cloud technology like AWS. Recommended for those who want to work with production-like environments.

System requirements of Apache Spark

Official site for  Apache Spark gives following recommendation (Traverse link for further details)

Storage System: There are few ways to set this up as follows: 

Spark can run on the same node as HDFS. Spark standalone node cluster can be installed on the same nodes and configure Spark and Hadoop memory and CPU usage accordingly to avoid any interference.
Or,
1. Hadoop and Spark can execute on common Resource Manager ( Ex. Yarn etc)
Or,
2. Spark will be executing in same Local Area Network as HDFS but on separate nodes.
Or
3. If a requirement is a quick response and low latency from data stores then execute compute jobs on separate nodes than that of storage nodes.

Local Disks: Typically 4-8 disks per node, configured without RAID.
If underline OS is Linux then mount the disk with noatime option and in Spark environment configure spark.local.dir variable to be a comma-separated list of local disks.
Note: For HDFS, it can be the same disk as HDFS.

Memory: Minimum 8GB - 100s of GBs of memory per machine.
A recommendation is the allocation of 75% of the memory to Spark.

Network: 10GB or faster speed network.

CPU cores: 8-16 Cores per machine

However, for Training and Learning purpose and just to taste Spark, following are two available options: 

  1. Run it locally 
  2. Use AWS EMR (Or any cloud computing service)

For learning purposes, minimum 4gb ram system with minimum 30gb disk may prove enough.

History of Apache Spark

History of Apache Spark

Spark was primarily developed to Overcome the Limitations of MapReduce.

Versioning: Spark initial version was version 0, version 1.6 is assumed to be a stable version and is being used in multiple commercial corporate projects. Version 2.3 is the latest available version. 

MapReduce is cluster computing  paradigm, which forces a particular linear  data flow structure on distributed programs: MapReduce programs read input data from disk,  map a function across the data,  reduce the results of the map, and store reduction results on disk. 

  1. Due to multiple copies of data and multiple I/O as described, MapReduce takes lots of time to process the volume of data. 
  2. MapReduce can do only batch time processing and is unsuitable for real-time data processing
  3. It is unsuitable for trivial join like transformations. 
  4. It’s unfit for large data on a network and also with OLTP data.
  5. Also, not suitable for graphics and interactive data.

Spark overcomes all these limitations and able to do faster processing too on the local disk as well.

Why Apache Spark?

Numerous advantages of Spark have made its a market favorite.

Let’s discuss one by one.

  1. Speed: Extends MapReduce Model to support computations like stream processing and interactive queries.
  2. Single Combination for processes and multiple tools:  Covers multiple workloads ( in a traditional system, it used to require different distributed systems), which makes combining different processing types and ease of tool management.
  3. Unification: Developers have to learn only one platform unlike multiple languages and tools in a traditional system.
  4. Support to different Resource Managers: Spark supports Hadoop HDFS system, and YARN for resource management but it’s not the only resource manager it supports. It works on MESOS and on any standalone scheduler like spark resource manager.
  5. Support for cutting-edge Innovation: Spark provides capabilities and support for an array of new-age technologies ranging from built-in machine learning libraries,   visualization tools, support for near processing (which was in a way the biggest challenge pre- spark era) and supports seamless integration with other deep learning frameworks like TensorFlow. This enables Spark to provide an innovative solution for new age use-cases.

Spark can access diverse data sources and make sense of them all and hence it’s trending in the market over any other cluster computing software available. 

Who uses Apache Spark

Who uses Apache Spark

Listing a few use cases of Apache spark below :

1. Analytics - Spark can be very useful when building real-time analytics from a stream of incoming data.

2. E-commerce - Information about the real-time transaction can be passed to streaming clustering algorithms like alternating least squares or K-means clustering algorithm. The results can be combined with data from other sources like social media profiles, product reviews on forums, customer comments, etc. to enhance the recommendations to customers based on new trends.

Shopify: At Shopify, we underwrite credit card transactions, exposing us to the risk of losing money. We need to respond to risky events as they happen, and a traditional ETL pipeline just isn’t fast enough. Spark Streaming is an incredibly powerful real-time data processing framework based on Apache Spark. It allows you to process real-time streams like Apache Kafka using Python with incredible simplicity.

Alibaba: Alibaba Taobao operates one of the world’s largest e-commerce platforms. We collect hundreds of petabytes of data on this platform and use Apache Spark to analyze these enormous amounts of data.

3. Healthcare Industry –
Healthcare has multiple use-cases of unstructured data to be processed in real-time. It has data ranging from image formats like scans etc to specific medical industry standards and wearable tracking devices. Many healthcare providers are keen on using spark for patient’s records to build 360 degrees view of the patient to do accurate diagnosis.

MyFitnessPal: MyFitnessPal needed to deliver a new feature called “Verified Foods.” The feature demanded a faster pipeline to execute a number of highly sophisticated algorithms. Their legacy non-distributed Java-based data pipeline was slow, did not scale, and lacked flexibility.

Here are a few other examples from industry leaders:

You can also learn more about use cases of Apache Spark  here.

Career Benefits:

Career Benefits of Spark for you as an individual:

Apache Spark developers earn the highest average salary among all other programmers. According to its  2015 Data Science Salary Survey, O’Reilly found strong correlations between those who used Apache Spark and those who were paid more money. In one of its models, using Spark added more than $11,000 to the median salary.

If you’re considering switching to this extremely in-demand career then taking up the  Apache Spark training will be an added advantage. Learning Spark will give you a steep competitive edge and can land you up in market best-paying jobs with top companies. Spark has gained enough adherents over the years to place it high on the list of fastest-growing skills; data scientists and sysadmins have evaluated the technology and clearly seen what they liked.  April’s Dice Report explored the fastest-growing technology skills, based on an analysis of job postings and data from Dice’s annual salary survey. The results are below; percentages are based on year-over-year growth in job postings:

Career Benefits of Apache Spark

Benefits of Spark implementing Spark in your organization:

Apache spark is now a decade older but still going strong. Due to lightning-fast processing and numerous other advantages discussed so far, Spark is still the first choice of many organizations.
Spark is considered to be the most popular open-source project on the planet, with more than 1,000 contributors from 250-plus organizations, according to Databricks.

Conclusion

To sum up, Spark helps to simplify the computationally intensive task of processing high volumes of real-time or batch data. It can seamlessly integrate with complex capabilities such as machine learning and graph algorithms. In short, Spark brings exclusive Big Data processing (which earlier was only for giant companies like Google) to the masses.

Do let us know how your learning experience was, through comments below.
Happy Learning!!!

Shruti

Shruti Deshpande

Blog Author

10+ years of data-rich experience in the IT industry. It started with data warehousing technologies into data modelling to BI application Architect and solution architect.


Big Data enthusiast and data analytics is my personal interest. I do believe it has endless opportunities and potential to make the world a sustainable place. Happy to ride on this tide.


*Disclaimer* - Expressed views are the personal views of the author and are not to be mistaken for the employer or any other organization’s views.

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

Overview of Deploying Machine Learning Models

Machine Learning is no longer just the latest buzzword. In fact, it has permeated every facet of our everyday lives. Most of the applications across the world are built using Machine Learning and their applications extend further when they are combined with other cutting-edge technologies like Deep Learning and Artificial Intelligence. These latest technologies are a boon to mankind, as they simplify tasks, helping to complete work in lesser time. They boost the growth and profitability of industries and organizations across sectors, which in turn helps in the growth of the economy and generates jobs.What are the fields that machine learning extends into?Machine Learning now finds applications across sectors and industries including fields like Healthcare, defense, insurance, government sectors, automobile, manufacturing, retail and more. ML gives great insights to businesses in gaining and retaining customer loyalty, enhances efficiency, minimizes the time consumption, optimizes resource allocation and decreases the cost of labor for a specific task.What is Model Deployment?It’s well established that ML has a lot of applications in the real world. But how exactly do these models work to solve our problems? And how can it be made available for a large user base? The answer is that we have to deploy the trained machine learning model into the web, so that it can be available for many users.When a model is deployed, it is fully equipped with training and it knows what are the inputs to be taken by the model and what are the outputs given out in return. This strategy is used to advantage in real world applications. Deployment is a tricky task and is the last stage of our ML project.Generally, the deployment will take place on a web server or a cloud for further use, and we can modify the content based on the user requirements and update the model. Deployment makes it easier to interact with the applications and share the benefits to the applications with others.With the process of Model Deployment, we can overcome problems like Portability, which means shifting of software from one machine to the other and Scalability, which is the capacity to be changed on a scale and the ability of the computation process to be used in a wide range of capabilities.Installing Flask on your MachineFlask is a web application framework in Python. It is a lightweight Web Server Gateway Interface (WSGI) web framework. It consists of many modules, and contains different types of tools and libraries which helps a web developer to write and implement many useful web applications.Installing Flask on our machine is simple. But before that, please ensure you have installed Python in your system because Flask runs using Python.In Windows: Open command prompt and write the following code:a) Initially make the virtual environment using pip -- pip install virtualenv And then write mkvirtualenv HelloWorldb) Connect to the project – Create a folder dev, then mkdir Helloworld for creating a directory; then type in cd HelloWorld to go the file location.c) Set Project Directory – Use setprojectdir in order to connect our virtual environment to the current working directory. Now further when we activate the environment, we will directly move into this directory.d) Deactivate – On using the command called deactivate, the virtual environment of hello world present in parenthesis will disappear, and we can activate our process directly in later steps.e) Workon – When we have some work to do with the project, we write the command  “workon HelloWorld” to activate the virtual environment directly in the command prompt.The above is the set of Virtual Environment commands for running our programs in Flask. This virtual environment helps and makes the work easier as it doesn’t disturb the normal environment of the system. The actions we perform will reside in the created virtual environment and facilitate the users with better features.f) Flask Installation – Now you install flask on the virtual environment using command pip install flaskUnderstanding the Problem StatementFor example, let us try a Face Recognition problem using opencv. Here, we work on haarcascades dataset. Our goal is to detect the eyes and face using opencv. We have an xml file that contains the values of face and eyes that were stored. This xml file will help us to identify the face and eyes when we look into the camera.The xml data for face recognition is available online, and we can try this project on our own after reading this blog. For every problem that we solve using Machine Learning, we require a dataset, which is the basic building block for the Model development in ML. You can generate interesting outcomes at the end like detecting the face and eyes with a bounding rectangular box. Machine learning beginners can use these examples and create a mini project which will help them to know much about the core of ML and other technologies associated with it.Workflow of the ProjectModel Building: We build a Machine Learning model to detect the face of the human present in front of the camera. We use the technology of Opencv to perform this action which is the library of Computer Vision.Here our focus is to understand how the model is working and how it is deployed on server using Flask. Accuracy is not the main objective, but we will learn how the developed ML model is deployed.Face app: We will create a face app that detects your face and implements the model application. This establishes the connection between Python script and the webpage template.Camera.py: This is the Python script file where we import the necessary libraries and datasets required for our model and we write the actual logic for the model to exhibit its functionality.Webpage Template: Here, we will design a user interface where the user can experience live detection of his face and eyes in the camera. We provide a button on a webpage, to experience the results.Getting the output screen: when the user clicks the button, the camera will open directly and we can get the result of the machine learning model deployed on the server. In the output screen you can see your face. Storage: This section is totally optional for users, and it is based on the users’ choice of storing and maintaining the data. After getting the outputs on the webpage screen, you can store the outputs in a folder on your computer. This helps us to see how the images are captured and stored locally in our system. You can add a file path in the code, that can store the images locally on your system if necessary.This application can be further extended to a major project of “Attendance taking using Face Recognition Technique”, which can be used in colleges and schools, and can potentially replace normal handwritten Attendance logs. This is an example of a smart application that can be used to make our work simple.Diagrammatic Representation of the steps for the projectBuilding our Machine Learning ModelWe have the XML data for recognizing face and eyes respectively. Now we will write the machine learning code, that implements the technique of face and eyes detection using opencv. Before that, we import some necessary libraries required for our project, in the file named camera.py # import cv2 # import numpy as np # import scipy.ndimage # import pyzbar.pyzbar as pyzbar # from PIL import Image Now, we load the dataset into some variables in order to access them further. Haarcascades is the file name where all the xml files containing the values of face, eye, nose etc are stored. # defining face detector# face_cascade = cv2.CascadeClassifier("haarcascades/haarcascade_frontalface_default.xml") # eye_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_eye.xml')The xml data required for our project is represented as shown below, and mostly consists of numbers.Now we write the code for opening the camera, and releasing of camera in a class file. The “def” keyword is the name of the function in Python. The functions in Python are declared using the keyword “def”.The function named “def __init__” initiates the task of opening camera for live streaming of the video. The “def __del__” function closes the camera upon termination of the window.# class VideoCamera(object):#    def __init__(self):        # capturing video#       self.video = cv2.VideoCapture(0) #  def __del__(self):#        # releasing camera#        self.video.release()Next, we build up the actual logic for face and eyes detect using opencv in Python script as follows. This function is a part of class named videocamera.# class VideoCamera(object):#    def __init__(self):#        # capturing video#        self.video = cv2.VideoCapture(0)#    def __del__(self):#        # releasing camera#        self.video.release()#    def face_eyes_detect(self):#        ret, frame = self.video.read()#        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)#        faces = face_cascade.detectMultiScale(gray, 1.3, 5)#        c=0#        for (x,y,w,h) in faces:#            cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 2)#            roi_gray = gray[y:y+h, x:x+w]#            roi_color = frame[y:y+h, x:x+w]#            eyes = eye_cascade.detectMultiScale(roi_gray)#            for (ex,ey,ew,eh) in eyes:#                cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)#            while True:#                k = cv2.waitKey(1000) & 0xFF#                print("Image "+str(c)+" saved")#                file = 'C:/Users/user/dev/HelloWorld/images/'+str(c)+'.jpg'#                cv2.imwrite(file, frame)#                c += 1            # encode Opencv raw frame to jpg and display it#        ret, jpeg = cv2.imencode('.jpg', frame)#        return jpeg.tobytes()The first line in the function “ret, frame” reads the data of live streaming video. The ret takes the value “1”, when the camera is open, else it takes “0” as input. The frame captures the live streaming video from time to time. In the 2nd line, we are changing the color of image from RGB to Grayscale, i.e., we are changing the values of pixels. And then we are applying some inbuilt functions to detect faces. The for loop, illustrates that it is having some fixed dimensions to draw a bounding rectangular box around the face and eyes, when it is detected. If you want to store the captured images after detecting face and eyes, we can add the code of while loop, and we can give the location to store the captured images. When an image is captured, it is saved as Image 1, Image 2 saved, etc., for confirmation.All the images will be saved in jpg format. We can mention the type of format in which the images should be stored. The method named cv2.imwrite stores the frame in a particular file location.Finally, after capturing the detected picture of face and eyes, it displays the result at the user end. Creating a WebpageWe will create a webpage, in order to implement the functionality of the developed machine learning model after deployment using Flask. Here is the design of our webpage.The above picture represents a small webpage demonstrating “Video Streaming Demonstration” and a link “face-eyes-detect”. When we click the button on the screen, the camera gets opened and the functionality will be displayed to the users who are facing the camera.The code for creating a webpage is as follows:If the project contains only one single html file, it should be necessarily saved with the name of index. The above code should be saved as “index.html” in a folder named “templates” in the project folder named “HelloWorld”, that we have created in the virtual environment earlier. This is the actual format we need to follow while designing a webpage using Flask framework.Connecting Webpage to our ModelTill now we have developed two separate files, one for developing the machine learning model for the problem statement and the other for creating a webpage, where we can access the functionality of the model. Now we will try to see how we can connect both of them.This is the Python script with the file name saved as “app.py”. Initially we import the necessary libraries to it, and create a variable that stores the Flask app. We then guide the code to which location it needs to be redirected, when the Python scripts are executed in our system. The redirection is done through “@app.route” followed by a function named “home”. Then we include the functionality of model named “face_eyes_detect” to the camera followed by the function definition named “gen”. After adding the functionality, we display the response of the deployed model on to the web browser. The outcome of the functionality is the detection of face and eyes in the live streaming camera and the frames are stored in the folder named images. We put the debug mode to False. # from flask import Flask, render_template, Response,url_for, redirect, request.# from flask import Flask, render_template, Response,url_for, redirect, request  # from camera import VideoCamera  # import cv2  # import time  # app = Flask(__name__)  # @app.route("/")  # def home():  #     # rendering web page  #     return render_template('index.html')  # def gen(camera):  #     while True:  #         # get camera frame  #         frame = camera.face_eyes_detect()  #         yield(b'--frame\r\n'  #                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')  # @app.route("/video_feed")  # def video_feed():  #     return Response(gen(VideoCamera()),  #           mimetype='multipart/x-mixed-replace; boundary=frame')  # if __name__ == '__main__':  #     # defining server ip address and port  #     app.run(debug=False)Before running the Python scripts, we need to install the libraries like opencv, flask, scipy, numpy, PIL, pyzbar etc., using the command prompt with the command named “pip install library_name” like “pip install opencv-python”, ”pip install flask”, “pip install scipy” etc.When you have installed all the libraries in your system, now open the python script “app.py” and run it using the command “f5”. The output is as follows:Image: Output obtained when we run app.py fileNow we need to copy the server address http://127.0.0.1:5000/ and paste it on the web browser, and we will get the output screen as follows:Now when we click the link “face-eyes-detect”, we will get the functionality of detecting the face and eyes of a user, and it is seen as follows:Without SpectaclesWith SpectaclesOne eye closed by handone eye closedWhen these detected frames are generated, they are similarly stored in a specified location of folder named “images”. And in the Python shell we can observe, the sequence of images is saved in the folder, and looks as follows:In the above format, we get the outcomes of images stored in our folder.Now we will see how the images were stored in the previously created folder named “images” present in the project folder of “HelloWorld.”Now we can use the deployed model in real time. With the help of this application, we can try some other new applications of Opencv and we can deploy it in the flask server accordingly.  You can find all the above code with the files in the following github repository, and you can make further changes to extend this project application to some other level.Github Link.ConclusionIn this blog, we learnt how to deploy a model using flask server and how to connect the Machine Learning Model with the Webpage using Flask. The example project of face-eyes detection using opencv is a pretty common application in the present world. Deployment using flask is easy and simple.  We can use the Flask Framework for deployment of ML models as it is a light weight framework. In the real-world scenario, Flask may not be the most suitable framework for bigger applications as it is a minimalist framework and works well only for lighter applications.
3292
Overview of Deploying Machine Learning Models

Machine Learning is no longer just the latest buzz... Read More

How Big Data Can Solve Enterprise Problems

Many professionals in the digital world have become familiar with the hype cycle. A new technology enters the tech world amid great expectations. Undoubtedly, dismay sets in and retrenchment stage starts, practice and process catch up to assumptions and the new value is untied. Currently, there is apparently no topic more hyped than big data and there is already no deficit of self-proclaimed pundits. Yet nearly 55% of big data projects fail and there is an increasing divide between enterprises that are benefiting from its use and those who are not. However, qualified data scientists, great integration across departments, and the ability to manage expectations all play a part in making big data work for your organization. It is often said that an organization’s future is dependent on the decisions it takes. Since most of the business decisions are backed by data available at hand. The accurate the information, the better they are for the business. Gone are the days when data was only used as an aid in better decision making. But now, with big data, it has actually become a part of all business decisions. For quite some time now, big data has been changing the way business operations are managed, how they collect data and turn it into useful and accurate information in real-time. Today, let’s take a look at solving real-life enterprise problems with big data. Predictive Analysis Let’s assume that you have a solid knowledge of the emerging trends and technologies in the market or when your infrastructure needs good maintenance. With huge amounts of data, you can easily predict trends and your future needs for the business. This sort of knowledge gives you an edge over your peers in this competitive world. Enhancing Market Research Regardless of the business vertical, market research is an essential part of business operations. With the ever-changing needs and aspirations of your customers, businesses need to find ways to get into the mind of customers with better and improved products and services. In such scenarios, having large volumes of data in hand will let you carry out detailed market research and thus enhancing your products and services. Streamlining Business Process For any enterprise, streamlining the business process is a crucial link to keeping the business sustainable and lucrative. Some effective modifications here and there can benefit you in the long run by cutting down the operational costs. Big data can be utilized to overhaul your whole business process right from raw material procurement to maintaining the supply chain. Data Access Centralization It is an inevitable fact that the decentralized data has its own advantages and one of the main restrictions arises from the fact that it can build data silos. Large enterprises with global presence frequently encounter such challenges. Centralizing conventional data often posed a challenge and blocked the complete enterprise from working as one team. But big data has entirely solved this problem, offering visibility of the data throughout the organization. How are you navigating the implications of all that data within your enterprise? Have you deployed big data in your enterprise and solved real-life enterprise problems? Then we would love to know your experiences. Do let us by commenting in the section below.
15000
How Big Data Can Solve Enterprise Problems

Many professionals in the digital world have becom... Read More

Analysis Of Big Data Using Spark And Scala

The use of Big Data over a network cluster has become a major application in multiple industries. The wide use of MapReduce and Hadoop technologies is proof of this evolving technology, along with the recent rise of Apache Spark, a data processing engine written in Scala programming language. Introduction to Scala Scala is a general purpose object-oriented programming language, similar to Java programming. Scala is an acronym for “Scalable language” meaning its capabilities can grow along the lines of your requirements & also there are more technologies built on scala. The capabilities of Scala programming can range from a simple scripting language to the preferred language for mission-critical applications. Scala has the following capabilities: Support for functional programming, with features including currying, type interference, immutability, lazy evaluation, and pattern matching. An advanced type system including algebraic data types and anonymous types. Features that are not available in Java, like operator overloading, named parameters, raw strings, and no checked exceptions. Scala can run seamlessly on a Java Virtual Machine (JVM), and Scala and Java classes can be freely interchanged or can refer to each other. Scala also supports cluster computing, with the most popular framework solution, Spark, which was written using Scala. Introduction to Apache Spark Apache Spark is an open-source Big Data processing framework that provides an interface for programming data clusters using data parallelism and fault tolerance. Apache Spark is widely used for fast processing of large datasets. Apache Spark is an open-source platform, built by a wide set of software developers from over 200 companies. Since 2009, more than 1000 developers have contributed to Apache Spark. Apache Spark provides better capabilities for Big Data applications, as compared to other Big Data technologies such as Hadoop or MapReduce. Listed below are some features of Apache Spark: 1. Comprehensive framework Spark provides a comprehensive and unified framework to manage Big Data processing, and supports a diverse range of data sets including text data, graphical data, batch data, and real-time streaming data. 2. Speed Spark can run programs up to 100 times faster than Hadoop clusters in memory, and 10 times faster when running on disk. Spark has an advanced DAG (directed acrylic graph) execution engine that provides support for cyclic data flow and in-memory data sharing across DAGs to execute different jobs with the same data. 3. Easy to use With a built-in set of over 80 high-level operators, Spark allows programmers to write Java, Scala, or Python applications in quick time. 4. Enhanced support In addition to Map and Reduce operations, Spark provides support for SQL queries, streaming data, machine learning, and graphic data processing. 5. Can be run on any platform Apache Spark applications can be run on a standalone cluster mode or in the cloud. Spark provides access to diverse data structures including HDFS, Cassandra, HBase, Hive, Tachyon, and any Hadoop data source. Spark can be deployed as a standalone server or on a distributed framework such as Mesos or YARN. 6. Flexibility In addition to Scala programming language, programmers can use Java, Python, Clojure, and R to build applications using Spark. Comprehensive library support As a Spark programmer, you can combine additional libraries within the same application, and provide Big Data analytical and Machine learning capabilities. The supported libraries include: Spark Streaming, used for processing of real-time streaming data. Spark SQL, used for exposing Spark datasets over JDBC APIs and for executing SQL-like queries on Spark datasets. Spark MLib, which is the machine learning library, consisting of common algorithms and utilities. Spark GraphX, which is the Spark API for graphs and graphical computation . BlinkDB, a query engine library used for running interactive SQL queries on large data volumes. Tachyon, which is a memory-centric distributed file system to enable file sharing across cluster frameworks. Spark Cassandra Connector and Spark R, which are integration adapters. With Cassandra Connector, Spark can access data from the Cassandra database and perform data analytics. Compatibility with Hadoop and MapReduce Apache Spark can be much faster as compared to other Big Data technologies. Apache Spark can run on an existing Hadoop Distributed File System (HDFS) to provide compatibility along with enhanced functionality. It is easy to deploy Spark applications on existing Hadoop v1 and v2 cluster. Spark uses the HDFS for data storage, and can work with Hadoop-compatible data sources including HBase and Cassandra. Apache Spark is compatible with MapReduce and enhances its capabilities with features such as in-memory data storage and real-time processing. Conclusion The standard API set of Apache Spark framework makes it the right choice for Big Data processing and data analytics. For client installation setups of MapReduce implementation with Hadoop, Spark and MapReduce can be used together for better results. Apache Spark is the right alternative to MapReduce for installations that involve large amounts of data that require low latency processing
26756
Analysis Of Big Data Using Spark And Scala

The use of Big Data over a network cluster has bec... Read More