PythonforDataScienceM TechNS
PythonforDataScienceM TechNS
1
ISE, JSSATEB
Python for Data Science MCS104A
2
ISE, JSSATEB
Python for Data Science MCS104A
•Applications: Understanding the domain helps data scientists to frame the right
questions, interpret results accurately, and create solutions that are relevant and impactful.
[Link] Engineering:
•Foundation: Data Engineering focuses on the practical aspects of data management,
including the development, construction, and maintenance of scalable data pipelines and
infrastructure.
•Applications: It involves tasks like data warehousing, ETL (Extract, Transform, Load)
processes, and database management to ensure that data is clean, accessible, and ready for analysis.
[Link] Visualization:
•Foundation: Data Visualization is the art and science of representing data in visual formats like
graphs, charts, and dashboards to make the data understandable and actionable.
•Applications: Effective visualization helps in communicating complex data insights to
stakeholders clearly and concisely, facilitating better decision-making.
[Link] and Data Governance:
•Foundation: This discipline addresses the ethical implications of data use, ensuring that data
practices comply with legal and ethical standards.
•Applications: It involves data privacy, security, and governance policies that protect sensitive
information and ensure ethical use of [Link]
Datafication:
Datafication refers to the process of transforming various aspects of life and activities
intoquantifiable data. It involves the collection, storage, and analysis of data generated
fromeveryday activities, behaviors, and interactions, often through digital means. This
transformationallows for the extraction of insights and patterns from these data points that can
informdecision-making, enhance services, and drive innovation.
Key Features:
● Quantification: Almost any activity, whether physical or digital, can be quantified. For
example, social interactions on social media, purchasing behaviors, health metrics (likeheart rate),
and even environmental conditions can be turned into data.
● Collection: Datafication relies heavily on technology to collect data. This can involve sensors,
mobile devices, social media platforms, and other digital tools. ● Analysis: Once data is collected,
it can be analyzed to identify trends, correlations, and actionable insights. This analysis can be
used in various fields, including marketing, healthcare, urban planning, and more. ● Value
3
ISE, JSSATEB
Python for Data Science MCS104A
Creation: Datafication can lead to enhanced decision-making, improved customer experiences, and
the creation of new business models by leveraging data insights.
Examples:
● Social Media: Platforms like Facebook and Twitter collect data on user interactions, preferences,
and behaviors, allowing companies to target advertising more effectively.
● Smart Devices: IoT (Internet of Things) devices, such as fitness trackers, collect data on user
health and activity levels, enabling personalized health recommendations. ● Transportation:
Companies like Uber collect data on ride patterns, traffic conditions, and user preferences to
optimize services and pricing. ii) Statistical Modelling
Fitting a model refers to the process of training a statistical or machine learning model on a dataset
to learn the underlying patterns or relationships present in the data. This is a crucial step in
predictive modeling and data analysis, as it enables the model to make accurate predictions or
provide insights based on new, unseen data.
Key Components of Fitting a Model
1. Training Data:
4
ISE, JSSATEB
Python for Data Science MCS104A
○ The data used to fit the model is called the training dataset. It contains input features
(independent variables) and the corresponding target variable (dependent variable) that the model
aims to predict.
2. Model Selection:
○ Selecting an appropriate model is essential, as different algorithms may be suitedfor different
types of problems (e.g., linear regression for continuous outcomes, logistic regression for binary
outcomes, decision trees for classification, etc.).
3. Loss Function:
○ A loss function (or cost function) quantifies how well the model's predictions
match the actual data. The goal of fitting the model is to minimize this loss.
Common loss functions include:
■ Mean Squared Error (MSE) for regression tasks.
■ Cross-Entropy Loss for classification tasks.
4. Optimization Algorithm:
○ An optimization algorithm (like gradient descent) is used to minimize the loss function by
adjusting the model parameters (coefficients). This involves iteratively updating the model's
parameters based on the gradients of the loss
function.
5. Hyperparameters:
○ These are the settings that are not learned during training (e.g., learning rate, number of trees in
a random forest). Hyperparameter tuning is often performed to find the best set of hyperparameters
for optimal model performance.
6. Validation:
○ The fitted model is usually evaluated on a separate validation dataset to assess its performance
and generalization capability. Metrics like accuracy, precision, recall, F1-score, or R-squared may
be used, depending on the task.
Steps in Fitting a Model
1. Data Preprocessing:
○ Clean the data, handle missing values, and preprocess features (e.g., normalization, encoding
categorical variables).
2. Split the Data:
5
ISE, JSSATEB
Python for Data Science MCS104A
○ Divide the dataset into training, validation, and test sets (commonly in a 70/15/15or 80/10/10
split) to prevent overfitting and evaluate model performance.
3. Choose a Model:
○ Select an appropriate algorithm based on the problem type (regression, classification, clustering,
etc.).
4. Fit the Model:
○ Use the training data to train the model by fitting it using the selected
optimization algorithm to minimize the loss function.
5. Evaluate the Model:
○ Use the validation dataset to assess the model's performance and make
adjustments if necessary. This might involve tuning hyperparameters or trying different
algorithms. 6. Testing:
○ Finally, assess the model's performance on the test set to evaluate how well it generalizes to new
data.
i) Population
A population refers to the entire set of individuals or items that are of interest in a particular
study. It includes all possible observations that meet a certain criterion and can be finite (e.g., all
students in a university) or infinite (e.g., all possible rolls of a die).
Key Features:
● Comprehensive: The population encompasses all possible members of the group being studied.
● Parameters: Characteristics of a population are described by parameters, such as the population
mean (μ\muμ), population variance (σ2\sigma^2σ2), etc.
● Cost and Time: Studying the entire population may be impractical due to cost, time, or
accessibility constraints. Example: Suppose you are conducting research on the average height of
adult men in a city. Inthis case:
● Population: All adult men living in that city. This includes every man aged 18 and older
in the city.
6
ISE, JSSATEB
Python for Data Science MCS104A
ii) Sample
A sample is a subset of the population selected for analysis. Samples are used to make
inferencesabout the population without needing to collect data from every individual within the
population.
Key Features:
● Representative: Ideally, the sample should be representative of the population to ensure that
the findings can be generalized.
● Statistics: Characteristics of a sample are described by statistics, such as the sample mean,
sample variance
● Sampling Methods: There are various methods to select samples, including random sampling,
stratified sampling, systematic sampling, and convenience sampling. Example: Continuing with
the previous example:
● Sample: If you randomly select 100 adult men from different neighborhoods in the city to
measure their heights, that group of 100 men represents your sample. Comparison and Importance
● Scope: The population is the whole group, while a sample is a part of that group.
● Data Collection: Collecting data from a population can be time-consuming and
expensive, while sampling allows for quicker and less costly data collection.
● Inference: By analyzing the sample, researchers can make inferences about the
population.
Statistical techniques to estimate population parameters based on samples statistics:
Let’s consider a scenario to illustrate the concepts further. Scenario: A university wants to
determine the average GPA of all its students (population) but
finds it impractical to collect GPAs from every student due to time constraints. 1. Population: All
enrolled students at the university. ○ If there are 10,000 students, the population includes each one
of them. 2. Sample: The university decides to randomly select 500 students fromits list of
enrolledstudents to participate in the study. ○ The average GPA of these 500 students will be
calculated to estimate the averageGPA of all 10,000 students.
Histogram Program
import pandas as pd
import numpy as np
import [Link] as plt
from [Link] import fetch_california_housing
7
ISE, JSSATEB
Python for Data Science MCS104A
8
ISE, JSSATEB
Python for Data Science MCS104A
print(outliers[column])
print(f"{column}:")
print(f"Lower Bound: {lower_bound}, Upper Bound: {upper_bound}")
print(f"Number of outliers: {len(outliers[column])}")
print("---")
Module 2
Exploratory Data Analysis (EDA) is a critical step in the data analysis process, aimed at
summarizing the main characteristics of a dataset, often using visual methods. EDA helps
inunderstanding the underlying patterns, detecting anomalies, testing hypotheses, and
checkingassumptions, which can guide subsequent analysis and modeling.
EDA Process
The EDA process typically involves the following steps:
1. Data Collection:
○ Gather the data from various sources, which could be databases, CSVfiles, APIs, etc.
2. Data Cleaning:
○ Identify and handle missing values, outliers, and inconsistencies in the data. ○ Remove
duplicates and ensure that data types are correct.
3. Descriptive Statistics:
○ Calculate summary statistics (mean, median, mode, standard deviation, quartiles)
to understand the data distribution. ○ Use measures like skewness and kurtosis to analyze the shape
of the data
distribution.
4. Data Visualization:
○ Create visualizations to explore data patterns, trends, and relationships. ○ Common
visualizations include:
■ Histograms for distribution
■ Box plots for identifying outliers
9
ISE, JSSATEB
Python for Data Science MCS104A
import pandas as pd
# Load dataset
data = pd.read_csv('employee_data.csv')
10
ISE, JSSATEB
Python for Data Science MCS104A
data_types = [Link]
● Fill or drop missing values as necessary.
11
ISE, JSSATEB
Python for Data Science MCS104A
12
ISE, JSSATEB
Python for Data Science MCS104A
3. Distance Metric:
○ K-NN uses a distance metric to determine the 'closeness' of data points. Commondistance metrics
include:
■ Euclidean Distance: Most commonly used, calculates the straight-linedistance between two
points. ■ Manhattan Distance: The sum of the absolute differences of the
Cartesian coordinates. ■ Minkowski Distance: A generalization of both Euclidean and
Manhattandistances.
4. Finding Neighbors:
○ For a given test point, the algorithm calculates the distance between this point andall other points
in the training dataset. It then identifies the kkk points that areclosest to the test point.
5. Making Predictions:
○ Classification: The algorithm assigns the class that is most frequent amongthekkk nearest
neighbors to the test point. ○ Regression: The algorithm takes the average (or weighted average)
of the target
values of the kkk nearest neighbors to make a prediction. Example of K-NN Algorithm
K-NN algorithm with a simple example.
Imagine you have a dataset of fruits, characterized by their weight and color (in terms of
RGBvalues). You want to classify a new fruit based on its features.
13
ISE, JSSATEB
Python for Data Science MCS104A
14
ISE, JSSATEB
Python for Data Science MCS104A
15
ISE, JSSATEB
Python for Data Science MCS104A
16
ISE, JSSATEB
Python for Data Science MCS104A
Module 3
Bayes' Theorem
Bayes' Theorem is a statistical method used for classification tasks - spam classification.
Bayes' Theorem describes the probability of an event, based on prior knowledge of conditions
that might be related to the event. It is mathematically expressed as:
P(A∣B)=P(B∣A)⋅P(A) / P(B)
Where:
Class 1: Spam
1. Prior Probabilities: These are the probabilities of an email being spam or ham before
seeing any specific words in the email.
Assume 30% of emails are spam and 70% are not, the prior probabilities would be:
P(Spam)=0.30, P(Ham)=0.70
For instance, if the word "buy" is very common in spam emails but less common in ham
emails:
P(buy∣Spam)=0.8, P(buy∣Ham)=0.1
3. Evidence (Normalizing Constant): This is the probability of seeing the word "buy" in
any email, regardless of whether it's spam or ham. It will cancel out when comparing the
posterior probabilities for spam and ham, so no explicit calculation required.
17
ISE, JSSATEB
Python for Data Science MCS104A
Example Setup:
Consider a training dataset and consider classifying a test email based on certain words.
Assume Out of 100 emails, 40 are spam and 60 are not spam (ham).
Given some common words and their occurrences in spam and ham emails:
Test Email:
Classify the following test email:
Test Email: "Buy now and get a free discount offer!"
The words in this email are: "buy", "free", "discount", "offer".
1. Prior Probabilities:
P(Spam)=0.40, P(Ham)=0.60
2. Likelihoods:
P(buy∣Spam)=0.8 P(buy∣Ham)=0.1
P(free∣Spam)=0.6 P(free∣Ham)=0.1
P(discount∣Spam)=0.7 P(discount∣Ham)=0.2
P(offer∣Spam)=0.7 P(offer∣Ham)=0.2
3. Posterior Probabilities:
P(Spam∣email) ∝ P(buy∣Spam) ⋅ P(free∣Spam) ⋅ P(discount∣Spam) ⋅ P(offer∣Spam) ⋅
P(Spam)
P(Spam∣email) ∝ (0.8)⋅(0.6)⋅(0.7)⋅(0.7)⋅(0.40)
P(Spam∣email) ∝ 0.09408
For Ham:
P(Ham∣email) ∝ 0.00024
Result: Posterior probability for spam is higher, hence classify this email as Spam.
18
ISE, JSSATEB
Python for Data Science MCS104A
The K-Means algorithm is a popular unsupervised machine learning technique used for
clustering. It partitions a dataset into kkk distinct, non-overlapping clusters based on
featuresimilarity. The primary goal of K-Means is to minimize the variance within each cluster
whilemaximizing the variance between clusters.
1. Initialization:
○ Select kkk initial centroids (cluster centers). This can be done randomly or byusing techniques
like K-Means++ for better initialization.
2. Assignment Step:
○ Assign each data point to the nearest centroid based on a distance metric
(commonly Euclidean distance). This forms kkk clusters.
3. Update Step:
○ Calculate the new centroids for each cluster by taking the mean of all points
assigned to that cluster.
4. Repeat:
○ Repeat the Assignment and Update steps until the centroids do not change
significantly, indicating that the algorithm has converged, or until a specifiednumber of iterations
is reached. 5. Output:
○ The final clusters and their centroids.
Example of K-Means Algorithm
Let’s consider a simple example to illustrate how the K-Means algorithm works.
Suppose you have a dataset representing the scores of students in two subjects: Math andScience.
The goal is to cluster the students into groups based on their performance. Step 1: Prepare the Data
Let's say the dataset is as follows:
19
ISE, JSSATEB
Python for Data Science MCS104A
20
ISE, JSSATEB
Python for Data Science MCS104A
21
ISE, JSSATEB
Python for Data Science MCS104A
Module 4
Dimensionality Problem:
The dimensionality problem refers to a datasets that have a large number of features, making it
harder to process, analyze, and visualize. High-dimensional data can lead to overfitting, where the
model becomes too complex and performs poorly on new data. Dimensionality reduction
techniques like Singular Value Decomposition (SVD) and Principal Component Analysis (PCA)
reduce the number of features while retaining important information.
Singular Value Decomposition (SVD) Algorithm
Singular Value Decomposition (SVD) is a technique for reducing the dimensionality of data. It
decomposes a matrix X into three components:
X = U ⋅ S ⋅ VT
Where:
22
ISE, JSSATEB
Python for Data Science MCS104A
23
ISE, JSSATEB
Python for Data Science MCS104A
The transformed data shows that most of the variance lies along the first principal component,
meaning the second component can be discarded to reduce dimensionality.
24
ISE, JSSATEB
Python for Data Science MCS104A
Feature extraction is a crucial process in data preprocessing and machine learning, particularly in
the context of high-dimensional data. It involves transforming rawdata intoaset
of usable features that can effectively represent the underlying patterns in the data while
reducingits dimensionality. This process aims to simplify the data without losing important
information, making it easier for machine learning algorithms to learn from it.
Key Concepts of Feature Extraction
1. Dimensionality Reduction:
○ Feature extraction helps in reducing the number of input variables (features) inadataset. This can
improve model performance, reduce computation time, andmitigate overfitting.
2. Feature Selection vs. Feature Extraction:
○ Feature Selection involves selecting a subset of relevant features fromthe original
dataset without transforming the data. ○ Feature Extraction, on the other hand, involves creating
new features by
transforming or combining the original features.
3. Representation:
○ The goal is to represent the data in a way that highlights the most important
aspects or patterns that are relevant to the problem being solved.
25
ISE, JSSATEB
Python for Data Science MCS104A
using convolutional neural networks (CNNs) which automatically learn featuresfrom images.
4. Signal Processing:
○ For time-series or audio data, features like frequency components, wavelet
transforms, or statistical measures (mean, variance) can be extracted.
Example of Feature Extraction: Image Classification
Consider a scenario where you want to classify images of cats and dogs. The rawpixel dataof
the images can be high-dimensional (especially for large images), making it difficult for a model
to learn effectively.
26
ISE, JSSATEB
Python for Data Science MCS104A
classification and regression tasks. It models decisions and their possible consequences as a tree
like structure, where each internal node represents a feature (attribute), each branch represents
decision rule, and each leaf node represents an outcome (label or value).
27
ISE, JSSATEB
Python for Data Science MCS104A
28
ISE, JSSATEB
Python for Data Science MCS104A
29
ISE, JSSATEB
Python for Data Science MCS104A
• Decision Trees are classification algorithms that break down complex decisions into a series of
simple yes/no (binary) questions. They mimic human decision-making, making them highly
interpretable.
• In the Chasing Dragons example, a decision tree can predict whether a user will return to the
game next month based on various factors like: Number of dragons slain, Age of the player and
Total hours spent playing.
• At each step, the model selects the most informative feature—the one that provides the most
separation between classes. This selection process is similar to playing "20 Questions," where you
try to ask the most effective question first.
• The tree is constructed using a mathematical approach, often based on entropy and information
gain. The goal is to reduce uncertainty at each step, ensuring that each decision node helps separate
the data efficiently.
• However, a major downside of decision trees is overfitting—they tend to memorize data rather
than generalize well to unseen examples.
30
ISE, JSSATEB
Python for Data Science MCS104A
Random Forests
Random Forests solve the overfitting problem by using bagging (bootstrap aggregating) to create
multiple decision trees and averaging their predictions. This increases accuracy but reduces
interpretability.
The process works as follows:
• Bootstrapping: Each tree is trained on a random subset of the training data, often 80% of the
total dataset, with some points appearing multiple times.
• Random Feature Selection: At each split, only a subset of the total features is considered (e.g.,
selecting 5 out of 100 features).
• Decision Tree Construction: Each tree grows independently, following the same entropy-
information gain method.
• Final Prediction: The predictions from all trees are combined, usually by majority voting for
classification tasks.
Unlike decision trees, random forests do not require pruning. They can capture complex patterns
and reduce the risk of overfitting by averaging out noise from individual trees. However, their
complexity makes them harder to interpret.
Random Forest is an ensemble learning method primarily used for classification andregression
tasks. It builds multiple decision trees during training and merges their outputs toimprove the
accuracy and robustness of the predictions. The underlying idea is to combine thepredictions of
several models (in this case, decision trees) to achieve better performance thananyindividual
model.
31
ISE, JSSATEB
Python for Data Science MCS104A
4. Voting Mechanism: For classification tasks, the final prediction is made by majorityvoting
among all the trees. For regression tasks, the average of all tree predictions is
taken.
Working of the Random Forest Algorithm
1. Data Preparation:
○ Start with a training dataset.
2. Bootstrap Sampling:
○ Create multiple bootstrap samples (subsets) from the original dataset. Eachsubset
will be used to train a different decision tree.
3. Tree Building:
○ For each bootstrap sample, build a decision tree:
■ At each internal node, randomly select a subset of features. ■ Choose the best feature among the
selected subset to split the data at that
node. ■ Repeat this process recursively until a stopping criterion is met (e.g., maximum tree depth
or minimum samples per leaf).
4. Aggregation:
○ For classification tasks, predict the class label based on majority voting fromall
the trees. For regression tasks, average the predictions from all trees.
5. Final Prediction:
○ The aggregated output from all the trees is the final prediction of the randomforest model.
Example of Random Forest Algorithm
Let’s implement a Random Forest classifier using the scikit-learn library with the Iris dataset.
import pandas as pd
import numpy as np
from [Link] import load_iris
32
ISE, JSSATEB
Python for Data Science MCS104A
# Split the dataset into training and testing sets (70% train, 30% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
33
ISE, JSSATEB
Python for Data Science MCS104A
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')
# Display classification report
print(classification_report(y_test, y_pred, target_names=iris.target_names))
Nearest Neighbor algorithm and the problems with Nearest Neighbor in Recommendation
System.
The Nearest Neighbor (k-NN) algorithm is a simple and intuitive instance-based learning method
used for classification and regression tasks. The idea is to predict the label of a data point based
on the majority label or average of its closest neighbors.
k-NN Working:
1) Choose the number of neighbors (k): Select the number of nearest neighbors, k, that will be
used to make the prediction. A common value for k is 3, but it can vary based on the data.
2) Calculate distance: Measure the distance between the input point and all other points in the
dataset.
Common distance metrics include:
• Euclidean distance for continuous data
• Manhattan distance for grid-like data
34
ISE, JSSATEB
Python for Data Science MCS104A
35
ISE, JSSATEB
Python for Data Science MCS104A
first month based on their activities during that period. By identifying patterns and key behaviors
associated with retention, the app can take proactive steps to encourage users to stay longer.
Feature generation plays a critical role in this process. In the feature generation phase, the team
brainstorms a wide range of potential features that might influence retention. For example, features
like the number of days the user visited, the time between visits, total points earned, or whether
the user completed their profile could all provide valuable insights. Domain expertise from game
designers, software engineers, statisticians, and marketers help to ensure that a comprehensive set
of features is generated, making the model more effective. Redundancies and correlations between
features are acceptable at this stage as they can later be addressed during feature selection.
Brainstorming and the Role of Domain Expertise in Feature Generation
• Domain expertise plays a critical role in feature generation by guiding which features are most
likely to impact the outcome.
• Understanding Data Context: Domain experts can provide insight into what aspects of the data
are most relevant, which helps in selecting the right features that align with business goals.
• Identifying Hidden Patterns: Experts can recognize patterns or relationships in the data that
may not be obvious to non-experts, such as correlations between user behavior and retention.
• Creating Derivative Features: Experts help brainstorm new features, like transforming raw data
into more useful forms (e.g., aggregating activity over time, segmenting users by behavior, etc.).
• Prioritizing Features: They can prioritize features based on their importance, guiding the
machine learning process towards the most impactful data for predictions.
By collaborating with domain experts during feature brainstorming, data scientists can better tailor
their models to the problem domain, improving both the relevance and effectiveness of their
machine learning solutions.
36
ISE, JSSATEB
Python for Data Science MCS104A
combinations of features, and this can lead to overfitting, especially when dealing with large
datasets.
The key challenge with wrappers is the exponential growth in the number of possible feature
subsets as the size of the feature set increases. Despite the computational expense, wrappers can
often find better feature subsets since they take into account the interactions between features.
37
ISE, JSSATEB
Python for Data Science MCS104A
where H(X) is the entropy of a random variable X, and P(xi) is the probability of each outcome xi.
• Measures the uncertainty or disorder in a target variable, with lower entropy indicating more
certainty.
• Commonly used in decision trees to identify the most informative features by maximizing
information gain.
• Limitation: May not capture feature interactions effectively on its own.
38
ISE, JSSATEB
Python for Data Science MCS104A
Module 5
Types of Social networks as graphs and methods of discovery of communities in grapshs.
a) Betweenness to find communities with its variant.
b) Betweenness with Algorithm.
Types of Social Networks as Graphs
• Telephone Networks: Nodes represent phone numbers; edges indicate communication within a
fixed period. Communities form from frequent communicators.
• Email Networks: Nodes are email addresses; edges represent exchanged emails. Strong or weak
edges show the communication direction. Communities form based on frequent interactions.
• Collaboration Networks: Nodes are authors of research papers. Edges connect co-authors.
Communities form based on shared topics.
• Wikipedia Editing Networks: Nodes are editors or articles. Edges indicate common editing.
39
ISE, JSSATEB
Python for Data Science MCS104A
40
ISE, JSSATEB
Python for Data Science MCS104A
41
ISE, JSSATEB
Python for Data Science MCS104A
Neighborhood properties of a graph describe the relationships between a node and its immediate
neighbors. These properties help us understand how nodes interact with one another, and they are
fundamental for many graph-based algorithms.
1) Degree of a Node:
The degree of a node is the number of edges incident to it, representing the number of direct
connections the node has. Nodes with high degrees tend to be more central in the graph and may
play important roles in the structure of communities.
2) Local Clustering Coefficient:
The clustering coefficient measures the tendency of nodes to form clusters, i.e., whether their
neighbors are also connected to each other. A high clustering coefficient indicates a dense
subgraph of interconnected nodes, which often suggests a tightly-knit community.
3) Neighborhood Overlap:
This property quantifies the number of common neighbors shared by two nodes. Nodes with high
neighborhood overlap are likely to be part of the same community, as they share many connections.
4) Eccentricity:
The eccentricity of a node is the greatest distance from that node to any other node in the graph. A
low eccentricity means the node is close to many other nodes, making it a potential hub or central
node in the network.
42
ISE, JSSATEB