The Wayback Machine - https://web.archive.org/web/20241119024707/https://www.geeksforgeeks.org/model-building-for-data-analytics/
Open In App

Model Building for Data Analytics

Last Updated : 29 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite – Life Cycle Phases of Data Analytics

After formulating the problem and preprocessing the data accordingly. We select the type of model we should build for our model. Like if our problem requires our result to have higher explainability then we use models like Linear regression or decision tree but if our model requires to have higher accuracy then we build models like XGBOOST or Deep Neural Network. 

Model Building In Data Analytics

Model building is an essential part of data analytics and is used to extract insights and knowledge from the data to make business decisions and strategies. In this phase of the project data science team needs to develop data sets for training, testing, and production purposes. These data sets enable data scientists to develop an analytical method and train it while holding aside some of the data for testing the model. Model building in data analytics is aimed at achieving not only high accuracy on the training data but also the ability to generalize and perform well on new, unseen data. Therefore, the focus is on creating a model that can capture the underlying patterns and relationships in the data, rather than simply memorizing the training data.

To do this we divide our dataset into two parts

  1. Training dataset 
  2. Test dataset 

Note: Based on the dataset quality and quantity of the data one may choose to divide his dataset into three parts training and testing and validation data.

Dividing The Dataset For Model Building 

To divide the dataset we will use the Python sklearn library which helps us in dividing the dataset into training and testing datasets. Here we will choose the ratio by which we want to divide the dataset by default it 3:1 for training and testing.     

Python code for creating and dividing the dataset 

We will first create a random array of dimensions having 2 columns and 100 rows and convert it into a dataframe using pandas. After that, we will use the sklearn package to divide the dataframe into test and train datasets and also we will separate our dataset into dependent and independent variables. 

Python3




from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
data = np.random.randint(low=10, high=100,
                         size=2000).reshape(1000, 2)
data = pd.DataFrame(data, columns=('x', 'y'))
X = data[['x', 'y']]
y = np.random.rand(1000)
train_data_x, test_data_x, train_data_y, test_data_y = \
    train_test_split(data, y, test_size=0.25)


Scaling The Dataset 

Sacling the dataset is an important preprocessing step before feeding the to the outliers. there are several benefits of scaling the data theses are as:

  • It prevents features with different scales from dominating the model like example suppose column A has data ranging from 1 to 1000 and column B has data ranging from 0 to 1 in that case column A can influence our model decision even if it is not an important feature. But after scaling all our columns comes in the similar range  
  • It speeds up our model convergence. Many optimization algorithms such as gradient descent are very sensitive to the scale of the data. By scaling data between 0 to 1 these algorithm converges faster.
Effect of scaling on Gradient Descent

Effect of scaling on Gradient Descent 

  • Scaling the dataset makes our model more robust to the outliers. 
  • Some algorithms like K-nearest neighbors (KNN), use the distance between data points to make predictions in this case if the columns have different scales then the distance can go higher. 

Python code for scaling the columns 

We will use StandardScaler object from the sklearn library to scale our independent features of the dataset. 

Python3




from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
train_data_x_scaled = scaler.fit_transform(train_data_x.to_numpy())
test_data_x = scaler.transform(test_data_x.to_numpy())


Modeling The Data 

After scaling and splitting the data it has now become ready for fitting to the model. The choice of choosing model totally depends on our problem formulation. There are a variety of models present that we can choose from. However, before choosing the model first, we should identify these points in the data 

  1. Whether our problem is a regression problem or a classification problem 
  2. Whether we want a model which is more explainable or we want a model which has a higher accuracy 

Python code for modeling the data 

Since our target value is continuous so here we will consider it as a regression problem. For making it simple and explainable we will use the decision tree model. 

Python3




from sklearn.tree import DecisionTreeRegressor,plot_tree
reg = DecisionTreeRegressor(min_samples_split=4,
                            max_leaf_nodes=10)
reg.fit(train_data_x_scaled,train_data_y)
y_pred = reg.predict(test_data_x)


After making the model we evaluate the model on the evaluation matrix. In our case, we will mean square error for computing the accuracy of our model.

Python code for evaluation 

Python3




from sklearn.metrics import mean_squared_error
print(mean_squared_error(y_pred,test_data_y))


Output:

0.109

Since our dataset was randomly generated mean square error of 661 is not bad. One good thing about the decision tree is that we can also see the decision that was made to model the data. 

Plotting The Decision Graph 

We can use the plot_tree function from the sklearn library to visualize on what basis the decision is made. 

Python3




fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(4,4), dpi=800)
plot_tree(reg, filled=True, ax=axes, fontsize=2)
plt.show()


Output:

Decision tree diagram for The model



Similar Reads

Difference Between Data Analytics and Predictive Analytics
Data Analytics: It is the process of deducing the logical sets and patterns by filtering and applying required transformations and models on raw data. The following steps can be followed to explore the behavioral pattern of data and draw the necessary conclusions. The top tools available for data analytics in the market are R Programming, Python, S
2 min read
Data Preprocessing, Analysis, and Visualization for building a Machine learning model
In this article, we are going to see the concept of Data Preprocessing, Analysis, and Visualization for building a Machine learning model. Business owners and organizations use Machine Learning models to predict their Business growth. But before applying machine learning models, the dataset needs to be preprocessed. So, let's import the data and st
5 min read
Building a Machine Learning Model Using J48 Classifier
What is the J48 Classifier? J48 is a machine learning decision tree classification algorithm based on Iterative Dichotomiser 3. It is very helpful in examine the data categorically and continuously. Note: To build our J48 machine learning model we’ll use the weka tool. What is Weka? Weka is an open-source tool developed by the University of Waikato
3 min read
Building Your First Machine Learning Model
Today, we're exploring a comprehensive guide to building a wine quality prediction model using some of the most powerful tools and libraries available in Python. Whether you're a beginner looking to understand the basics or an experienced data scientist aiming to refine your skills, this guide has something for everyone. In this tutorial, we'll wal
5 min read
How to Track Progress While Building Model with the Caret Package
Building predictive models is an iterative process that involves multiple steps, such as data preprocessing, feature selection, model training, and evaluation. During this process, it is essential to track the progress to ensure that the model is performing as expected and to make necessary adjustments. The caret package in R provides several tools
5 min read
Building a Simple Language Translation Tool Using a Pre-Trained Translation Model
Translation is common among the applications of Natural Language Processing and machine learning. Though due to advancements in technology mainly in the pre-trained models, and transformers, it becomes easier to create a suitable language translation tool. Here in this article, we will create the language translation application from the pre-traine
7 min read
Learning Model Building in Scikit-learn
Scikit-learn has emerged as a powerful and user-friendly Python library. Its simplicity and versatility make it a better choice for both beginners and seasoned data scientists to build and implement machine learning models. In this article, we will explore about Sklearn. Table of Content What is Scikit-learn?Installation of Scikit- learn Features o
9 min read
Building Predictive Model in KNIME
Building your first predictive model in KNIME involves several key steps, from data preparation to model deployment. This article will guide you through the process, providing insights into the KNIME Analytics Platform's capabilities and how you can leverage them to create effective predictive models. Table of Content Predictive Modeling with KNIME
5 min read
Building a Model to Distinguish Apple Inc. from Apple Fruit in Tweets
When people talk about "Apple," they might be referring to two very different things: Apple Inc. (the tech company) or apples (the fruit). This can create confusion, especially when analyzing tweets or social media posts. To solve this, we can build a machine learning model that helps us distinguish between tweets about Apple Inc. and tweets about
4 min read
Building a Basic Neural ODE Model
[Tex]\frac{d h(t)}{dt} = f(h(t), t, \theta) [/Tex]Neural Ordinary Differential Equations (Neural ODEs) represent a significant advancement in the field of machine learning, offering a continuous-time approach to modeling the dynamics of systems. Unlike traditional neural networks that rely on discrete layers, Neural ODEs parameterize the derivative
8 min read
Building Scalable Data Pipelines: Tools and Techniques for Modern Data Engineering
In today’s data-driven world, scalable data pipelines are crucial for organizations aiming to harness the full potential of their data assets. Data pipelines are responsible for collecting, transforming, and delivering data from disparate sources to various target systems. With the increasing volume, velocity, and variety of data, building scalable
8 min read
Why Data Visualization Matters in Data Analytics?
What if you wanted to know the number of movies produced in the world per year in different countries? You could always read this data in the form of a black and white text written on multiple pages. Or you could have a colorful bar chart that would immediately tell you which countries are producing more movies and if the total movies per year are
7 min read
Difference Between Data Visualization and Data Analytics
Data Visualization: Data visualization is the graphical representation of information and data in a pictorial or graphical format(Example: charts, graphs, and maps). Data visualization tools provide an accessible way to see and understand trends, patterns in data and outliers. Data visualization tools and technologies are essential to analyze massi
3 min read
7 Best Data Analytics Certifications For Data Analyst
As, we all know in Today’s world, how much data is crucial and important for everyone, whether it’s someone’s personal data, any company data, or any type of data used, so, it is also important at the same time to manage the data properly. Nowadays, data becomes so much more important as day by day when we are moving towards the advancement in tech
8 min read
Role of Data Science in Big Data Analytics
In today's data-driven world, the role of data science in big data analytics is becoming increasingly vital. With the vast amounts of data being generated every day, organizations are turning to data science to make sense of it all and extract valuable insights. Data science involves collecting, analyzing, and interpreting large volumes of data to
8 min read
Roles of Data Engineering and Data Science in Modern Analytics
In the rapidly evolving landscape of data analytics, two key players stand out: data engineering and data science. While distinct in their focus and responsibilities, these fields are deeply interconnected, forming the backbone of modern data-driven decision-making. In this article, we'll delve into the intricate relationship between data engineeri
5 min read
Data Science vs Data Analytics
In this article, we will discuss the differences between the two most demanded fields in Artificial intelligence that is data science, and data analytics. What is Data Science Data Science is a field that deals with extracting meaningful information and insights by applying various algorithms preprocessing and scientific methods on structured and u
3 min read
Problem solving on Boolean Model and Vector Space Model
Boolean Model: It is a simple retrieval model based on set theory and boolean algebra. Queries are designed as boolean expressions which have precise semantics. Retrieval strategy is based on binary decision criterion. Boolean model considers that index terms are present or absent in a document. Problem Solving: Consider 5 documents with a vocabula
4 min read
What Is the Difference Between Model Hyperparameters and Model Parameters?
Answer: Model hyperparameters are set before training and control the learning process, while model parameters are learned during training and define the mapping from input to output.Here's a comparison of the difference between model hyperparameters and model parameters in tabular format: AspectModel HyperparametersModel ParametersDefinitionSettin
1 min read
Differences between Model-free and Model-based Reinforcement Learning
Reinforcement learning (RL) is a type of machine learning where an agent learns to make decisions by performing actions in an environment to maximize some notion of cumulative reward. Two primary approaches in RL are model-free and model-based reinforcement learning. This article explores the distinctions between these two methodologies. Overview o
7 min read
How to Resolve "r glmer Warnings: Model Fails to Converge and Model is Nearly Unidentifiable"?
When using the glmer function from the lme4 package in R to fit generalized linear mixed models (GLMMs), you might encounter warnings such as "Model failed to converge" or "Model is nearly unidentifiable." These warnings indicate issues with the model fitting process, often due to problems with the data or the model specification. Here are some ste
4 min read
Document Retrieval using Boolean Model and Vector Space Model
Boolean ModelIt is a simple retrieval model based on set theory and boolean algebra. Queries are designed as boolean expressions which have precise semantics. The retrieval strategy is based on binary decision criterion. The boolean model considers that index terms are present or absent in a document. Problem: Consider 5 documents with a vocabulary
14 min read
Difference between Keras model.save() and model.save_weights()?
When working with Keras, a popular deep learning library, two commonly used methods for saving models are model.save() and model.save_weights(). Both serve different purposes, and understanding their differences is crucial for efficiently managing your models. model.save()The model.save() method saves the entire model, which includes: Architecture/
3 min read
Difference between Keras model.evaluate() and model.predict()?
When working with machine learning models in Keras, two commonly used functions are model.evaluate() and model.predict(). These functions serve different purposes, and understanding the distinction between them is essential for properly assessing and utilizing your model. Understanding model.evaluate()Purpose: model.evaluate() is used to evaluate t
3 min read
How to Extract the Model Equation from Model Object in R?
Extracting the model equation from a model object in R allows you to understand the relationship between the dependent variable and the independent variables. This process is particularly useful when interpreting results from linear, logistic regression, or other statistical models. R provides functions and methods to extract and visualize model eq
3 min read
Building your Data Science blog with pelican
First step in order to get a job in Data Science is building a solid profile. Aspiring Data Scientist often do research and study regarding this field, however fail to take the right steps in the right direction. But experts advises to aspiring Data Scientists to write a blog or make video tutorial in order to show their knowledge in data science f
3 min read
Popular tools for data analytics
Data Analytics is an important aspect of many organizations nowadays. Real-time data analytics is essential for the success of a major organization and helps drive decision making. This article will help you gain knowledge about the various data analytic tools that are in use and how they differ. There are myriads of data analytics tools that help
6 min read
How Do Companies Use Big Data Analytics in Real World?
The most valuable item for any company in modern times is data! Companies can work much more efficiently by analyzing large amounts of data and making business decisions on that basis. This means that Big Data Analytics is the current path to profit! So is it any surprise that more and more companies are gradually turning towards a data-based busin
6 min read
Difference between Cloud Computing and Big Data Analytics
Cloud Computing: It is an on-demand delivery of resources like servers, databases, networking, software, analytics, applications and computational power over the Internet to promote speed and flexibility as well as the economy of scale. It helps in lowering operational costs and is much more reliable. Vast amounts of computing resources can be deli
2 min read
Difference Between Cloud Computing and Data Analytics
Cloud Computing: Cloud Computing is a technique in which a network of remote servers is hosted on the Internet. These servers primarily store the data, manage the data, and process the data. But this is not done by a local server or a personal computer. In short, data here is gathered on the internet. Thus, eliminating the use of a physical server.
2 min read
three90RightbarBannerImg