Showing posts with label Data Exploration. Show all posts
Showing posts with label Data Exploration. Show all posts

Saturday, October 19, 2024

Applying DFS to Analyze the Iris Dataset: A Practical Guide


Depth First Search (DFS) on Iris Dataset Using Python

Depth First Search (DFS) on the Iris Dataset Using Python

Graph traversal algorithms are among the most important concepts in computer science and machine learning. In this tutorial, we will combine graph theory with one of the most famous machine learning datasets: the Iris dataset.

Instead of treating the Iris dataset purely as a classification problem, we will represent each flower sample as a node in a graph and explore the dataset using a graph traversal algorithm called Depth-First Search (DFS).

This approach helps demonstrate:

  • Graph traversal concepts
  • Recursive algorithms
  • Dataset exploration techniques
  • Graph representation in Python
  • DFS path tracking

๐Ÿ’ก What You Will Learn

  • What the Iris dataset contains
  • How graphs are represented in Python
  • How DFS works internally
  • How recursion powers DFS
  • How datasets can be treated as graphs
  • How feature standardization works
  • How to track traversal paths
  • DFS mathematical complexity
  • Practical Python implementation

Table of Contents


1. Understanding the Iris Dataset

The Iris dataset is one of the most famous datasets in machine learning and statistics.

It contains measurements from three species of Iris flowers:

  • Setosa
  • Versicolor
  • Virginica

Features in the Dataset

Feature Description
Sepal Length Length of the flower sepal
Sepal Width Width of the flower sepal
Petal Length Length of the flower petal
Petal Width Width of the flower petal

Dataset Size

The dataset contains:

$$ 150 \ Samples $$

Each species contains:

$$ 50 \ Flowers $$

2. Representing the Dataset as a Graph

Normally, datasets are stored in rows and columns.

However, in this tutorial:

$$ Each \ Flower = Graph \ Node $$

Every node is connected to every other node.

Fully Connected Graph

If there are:

$$ n \ Nodes $$

Then total edges in a fully connected graph are:

$$ \frac{n(n-1)}{2} $$

For the Iris dataset:

$$ \frac{150(149)}{2} $$

Which equals:

$$ 11175 \ Edges $$

This creates a dense graph where every flower can reach every other flower.


3. What is Depth First Search (DFS)?

Depth First Search is a graph traversal algorithm.

DFS explores:

  • One branch deeply
  • Then backtracks
  • Then explores another branch

DFS Strategy

The traversal follows:

$$ Explore \rightarrow Deep \rightarrow Backtrack $$

Recursive Nature

DFS is commonly implemented recursively.

The recursive structure is:

$$ DFS(Node) \rightarrow DFS(Neighbor) $$

DFS Example


A → B → D
      ↑
      Backtrack

Why DFS is Important

  • Graph exploration
  • Path finding
  • Maze solving
  • Web crawling
  • Network analysis
  • AI search algorithms

4. Feature Standardization

Before exploring the dataset, we standardize the features.

Why?

Different features may have different ranges.

Example

Feature Possible Range
Sepal Length 4.3 - 7.9
Petal Width 0.1 - 2.5

Without standardization:

  • Larger values dominate calculations.
  • Features contribute unequally.

Standardization Formula

$$ z = \frac{x - \mu}{\sigma} $$

Where:

Symbol Meaning
\(x\) Original value
\(\mu\) Mean
\(\sigma\) Standard deviation

After scaling:

$$ Mean \approx 0 $$

And:

$$ StandardDeviation \approx 1 $$

5. Python DFS Implementation

Importing Libraries


from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler

Loading Dataset


iris = load_iris()

X = iris.data
y = iris.target

Standardizing Features


scaler = StandardScaler()

X_scaled = scaler.fit_transform(X)

Building Graph


graph = {}

for i in range(len(X_scaled)):
    graph[i] = [
        j for j in range(len(X_scaled))
        if j != i
    ]

Every node is connected to all others.


DFS Algorithm Implementation


visited = set()

def dfs(node, path=[]):

    visited.add(node)

    path.append(node)

    print("Node:", node)
    print("Features:", X_scaled[node])
    print("Species:", y[node])
    print("Path Length:", len(path))
    print("-" * 40)

    for neighbor in graph[node]:

        if neighbor not in visited:
            dfs(neighbor, path)

    path.pop()

Starting DFS


dfs(0)

6. DFS Mathematics and Complexity

Time Complexity

DFS complexity is:

$$ O(V + E) $$

Where:

  • \(V\) = Number of vertices
  • \(E\) = Number of edges

For our graph:

$$ V = 150 $$

And:

$$ E = 11175 $$

Thus:

$$ O(150 + 11175) $$

Space Complexity

DFS recursion stack:

$$ O(V) $$

Worst case:

$$ O(150) $$

7. Understanding the DFS Traversal Process

DFS explores deeply before backtracking.

Traversal Pattern


Node 0
  ↓
Node 1
  ↓
Node 2
  ↓
Node 3

When no unvisited neighbors remain:

$$ Backtrack $$

Then continue exploring.

Visited Set

DFS uses:

$$ Visited = \{Nodes\ Already\ Explored\} $$

This prevents infinite loops.


8. CLI Output Examples

Running the Program


python iris_dfs.py

CLI Output


Node: 0
Features:
[-0.90  1.01 -1.34 -1.31]

Species: 0

Path Length: 1
--------------------------------

Another Output Example


Node: 25
Features:
[-0.05  0.78 -1.14 -1.05]

Species: 0

Path Length: 26
--------------------------------

DFS Progress


Visited Nodes: 150
Traversal Complete

9. Advanced Concepts

Why Use DFS on Datasets?

Although unusual, representing datasets as graphs enables:

  • Similarity analysis
  • Cluster exploration
  • Relationship discovery
  • Graph-based machine learning

Graph Machine Learning

Modern AI systems often use:

  • Graph Neural Networks
  • Knowledge Graphs
  • Social Network Graphs
  • Recommendation Graphs

Recursive Depth

DFS recursion depth can become large:

$$ Depth \rightarrow V $$

Large graphs may require iterative DFS implementations.

Iterative DFS Alternative

Instead of recursion, DFS can use a stack:

$$ Stack = LIFO $$

This avoids recursion depth limitations.


10. Real World Applications of DFS

Search Engines

Web crawlers explore pages using traversal algorithms.

Social Networks

DFS helps analyze relationships between users.

Maps and Navigation

Graph traversal assists route exploration.

Artificial Intelligence

Game trees use DFS extensively.

Bioinformatics

Protein interaction networks use graph traversal.


Key Insights from This Project

  • Datasets can be modeled as graphs.
  • DFS explores deeply before backtracking.
  • Feature scaling improves consistency.
  • Graphs enable relational exploration.
  • Recursion powers DFS traversal.
  • Complexity depends on vertices and edges.
  • Machine learning and graph theory can combine effectively.

11. Conclusion

In this tutorial, we explored a creative way of using Depth First Search (DFS) on the Iris dataset.

Instead of treating the dataset traditionally, we transformed each flower into a graph node and explored the dataset using graph traversal.

We covered:

  • Graph representation
  • Feature scaling
  • Recursive DFS algorithms
  • Traversal path tracking
  • Graph mathematics
  • Computational complexity

Although this example is educational, it demonstrates how graph theory and machine learning concepts can intersect in powerful ways.

Understanding DFS provides a strong foundation for advanced topics like:

  • Graph databases
  • Network science
  • Graph neural networks
  • AI search algorithms
  • Knowledge graphs

๐ŸŽฏ Final Takeaways

  • DFS is a fundamental graph traversal algorithm.
  • Datasets can be represented as connected graphs.
  • Standardization improves feature consistency.
  • Recursion is central to DFS.
  • Graph theory plays a major role in AI and ML.
  • The Iris dataset remains a powerful educational tool.

Thursday, August 22, 2024

Treemap Visualization of Titanic Dataset: Exploring Hierarchical Relationships and Survival Outcomes

You are working with the Titanic dataset and want to visualize the relationships among various categorical variables in a hierarchical structure. Specifically, you aim to display how passengers are distributed based on their class, gender, the town they embarked from, and whether they survived. You also want to represent the survival status using a color scale to easily distinguish between those who survived and those who did not.

To address this, you would create a sunburst chart, which is a type of visualization that displays hierarchical data as a series of nested rings. Each level of the hierarchy is represented by a ring, with the innermost ring representing the top level of the hierarchy.

1. **Data Preparation**: 
   - You begin by loading the Titanic dataset, which contains information about the passengers on the Titanic, including variables like passenger class, sex, embarkation town, and survival status.
   - To ensure accurate analysis, you drop any rows in the dataset that have missing values for the variables of interest (class, sex, embarkation town, and survival status).

2. **Hierarchy Definition**:
   - You define a hierarchy for the sunburst chart where the data is organized first by passenger class, then by gender, followed by the embarkation town, and finally by survival status. This means that the chart will first split the data by class, then within each class by gender, and so on.

3. **Color Encoding**:
   - You use the survival status to determine the color of each section of the sunburst chart. A color scale is applied where different shades represent whether a passenger survived or not, making it easy to visually distinguish the outcomes.

4. **Visualization**:
   - The sunburst chart is then created using a library that supports interactive plotting. This visualization allows you to explore how different categories are related and see the proportions of passengers in each category who survived or did not survive.

Finally, the sunburst chart is displayed, providing a comprehensive view of the hierarchical relationships in the Titanic dataset and the survival outcomes of passengers based on class, gender, and embarkation town.

Wednesday, August 21, 2024

Using groupby and describe in Pandas for Effective Data Analysis

### Scenario

Imagine you have a small dataset of students' test scores from three different classes: A, B, and C. You want to analyze how the test scores vary across these classes.

### Data


import pandas as pd

# Sample DataFrame
data = {
    'Class': ['A', 'A', 'B', 'B', 'C', 'C', 'C'],
    'Score': [85, 78, 90, 88, 92, 85, 80]
}

df = pd.DataFrame(data)


This is what the data looks like:

| Class | Score |
|-------|-------|
| A | 85 |
| A | 78 |
| B | 90 |
| B | 88 |
| C | 92 |
| C | 85 |
| C | 80 |

### Using `groupby` and `describe`

Now, you want to quickly summarize the test scores by class. Instead of calculating each statistic (like the mean or standard deviation) manually, you can use `groupby` and `describe` together:


# Group by 'Class' and describe the 'Score' data
grouped_summary = df.groupby('Class')['Score'].describe()

print(grouped_summary)


### Output

       count mean std min 25% 50% 75% max
Class                                                     
A 2.0 81.5 4.949747 78.0 79.75 81.5 83.25 85.0
B 2.0 89.0 1.414214 88.0 88.50 89.0 89.50 90.0
C 3.0 85.7 6.110101 80.0 82.50 85.0 88.50 92.0


### Why This is Effective

1. **Instant Summary**: In one step, you get a full statistical summary for each class, including the count of students, mean score, standard deviation, and the range (min to max).

2. **Comparison Across Groups**: You can immediately compare the average score, variability (standard deviation), and score distribution (min, 25%, 50%, 75%, max) across different classes. For example:
   - **Class A** has an average score of 81.5 with some variability (std = 4.95).
   - **Class B** has a higher average (89) with very low variability (std = 1.41).
   - **Class C** has the highest average (85.7) but also the widest range of scores.

3. **Identify Insights Quickly**: You might notice that Class B is more consistent in scoring, while Class C has a wider spread. This kind of insight helps you understand the differences between groups at a glance, which would take much longer if you calculated each statistic separately.

In summary, the `groupby` and `describe` combination is effective because it allows you to efficiently summarize and compare grouped data, making it easier to identify trends, patterns, or outliers within your dataset.

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts