Depth First Search

Description

The goal of Depth First Search is to search as ‘deep’ into the graph as possible, which is opposed to Breadth First Search which is to search as ‘wide’ as possible. In DFS, edges are explored out of the most recently discovered vertex v that has unexplored edges out of it. When all of v’s edges have been explored, the search “backtracks” to explore other edges leaving the source vertex from which v was discovered. This process is continued until all the vertices reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source. This process is repeated until all vertices have been discovered.
Unlike BFS, where the predecessor subgraph forms a tree, the predecessor subgraph formed by a DFS may be composed of several trees to form a DFS forest. This is because the search may be repeated from multiple sources.

Implementation

As in BFS, vertices are colored during ths search to indicate their state. Each vertex is initially white, is grayed when it is discovered in the search and blackened when finished, i.e. when it’s adjacency list/neighbor set has been examined completely. This guarantees that each vertex ends up in exactly one depth-first tree so that these trees are disjoint.
Besides creating a depth-first forest, depth-first search also timestamps each vertex. Each vertex v has 2 timestamps: the 1st timestamp disc[v] records when v is first discovered and grayed, and the 2nd timestamp fin[v] records when the search finishes examining v’s adjacency list and blackens v.

Pseudocode

The pseudocode is as follows:

DFS(G)
1 for each vertex u in V[G]
2      do color[u] <--- WHITE
3           pred[u] <--- NULL
4 time <--- 0
5  for each vertex u in V[G]
6        do if color[u] == WHITE
7             then DFS-VISIT(u)

DFS-VISIT
1 color[u] <--- WHITE  // White vertex u has just been discovered.
2 time <--- time + 1
3 disc[u] <-- time
4 for each v in Adj[u]     // Explore edge (u,v)
5       do if color[v] == WHITE
6       then pred[v] <--- u
7               DFS-VISIT(v)
8 color[u] <-- BLACK     // Blacken u; it is finished
9 fin[u] <--- time <--- time +1

Analysis

Total running time is: θ(V+E). DFS runs linear in the size of the adjacency list representation of the graph G.

Various Machine Learning Links

ML Tutorials and Tips

In-depth introduction to machine learning in 15 hours of expert videos
Machine Learning Practical Advice – Scikit-Learn
Introduction to Sckit-Learn (Vanderplass)

Data Mining

R and Data Mining: Examples and Case Studies

Kaggle

Winning Kaggle, An introduction to Re-Ranking
Titanic: Machine Learning from Disaster

Titanic

Titanic Survival Prediction Using R
Titanic Survival Prediction Using R (Wehrley)
Titanic with Decision Trees
Kaggle – Titanic Machine Learning from Disaster
Data Science Learning from the Titanic in R
EECS 349 Titanic – Machine Learning From Disaster
The sinking of the Titanic – Binary Logistic Regression in R
CS229 Titanic – Machine Learning from Disaster

Supervised Learning

Scikit-Learn Supervised Learning
DataRobot – Classification with Sckit-Learn

Logistic Regression

Logistic Regression with sckit-learn
Kaggle — Photo quality prediction

Decision Trees

Classification with Decision Tree Induction
Scikit-Learn Decision Tree Regression

Support Vector Machines

Scikit-Learn Support Vector Machines

Unsupervised Learning

Principal Component Analysis

PCA in an image with scikit-learn and scikit-image
Scikit-Learn Faces Dataset Decomposition
PCA for Machine Learning (R)

Clustering

Scikit-Learn K-Means Clustering

Breadth-First Search

Description

Given a graph G=(V,E) and a source vertex s, BFS systematically explores the edges of E to disover every vertex that is reachable from s.
It computes the distance (smallest no. of edges) from s to each reachable vertex. It produces a BFS tree with root s that contains all reachable vertices.
For any vertex v reachable from s, the path in the BFS tree from s to v corr. to a shortest path from s to v in G, i.e. path containing the smallest number of edges. BFS discovers all vertices at distance k from s before discovering any vertices at distance k+1.

Implementation

The pseudocode below assumes that the input graph G = (V,E) is represented using adjacency lists. It maintains several additional data fields with each vertex in the graph.
The color of each vertex u in V is stored in color[u], and the predecessor of u is stored in prev[u]. If u has no predecessor, then prev[u] = NULL. The distance from the source s to vertex u is stored in dist[u] . The algorithm uses a FIFO queue Q to manage the set of gray vertices.

Pseudocode

BFS(G,s)
1   for each vertex u in V[G] - {s}
2     do color[u] <-- WHITE
3         dist[u] <-- INF
4         prev[u] <-- NULL
5   color[s] <-- GRAY
6   dist[s] <-- 0
7   prev[s] <-- NULL
8   Q <-- {}
9   ENQUEUE(Q, s)
10 while Q!={}
11    do u <-- DEQUEUE(Q)
12      foreach v in Adj[u]
13         do if color[v]=WHITE
14              then color[v] <-- GRAY
15                  dist[v] <-- d[u] +1
16                  prev[v] <-- u
17                  ENQUEUE(Q,v)
18      color[u] <-- BLACK

Analysis

Total running time is: O(V+E). BFS runs linear in the size of the adjacency list representation of the graph G.

Source code:

BFS.py

Reference :  Introduction to Algorithms by Corman, Leiserson & Rivest (MIT Press)

Binary Search Trees

Definition

A binary search tree is a binary tree whose keys satisfy the binary search tree property:
Let x be a node in the BST.
If y is a node in the left subtree of x, then key[y] <= key[x].
If y is a node in the right subtree of x then key[y] >= key[x].

Basic operations on a binary search tree (BST) take time proportional to the height of the tree. For a complete binary tree with n nodes, such operations run in
O(lg n) worst-case time.
If the tree is a linear chain of n nodes, the same operations take O(n) worst case time. The expected height of a randomly built BST is O(lg n), so that basic dynamic set operations on such a tree take θ(lg n) time on average. There are variations of BSTs whose worst-case performance can be guaranteed to be good – red-black and B-trees are 2 such examples.

Basic operations on BSTs include:
SEARCH, MINIMUM, MAXIMUM, PREDECESSOR, SUCCESSOR, INSERT & DELETE.

The BST property allows us to print out all the keys in 3 different ways:

  1. InOrder Tree Walk – the key of the root of a subtree is printed between the values in its left subtree and those in its right subtree – LPR
  2. PreOrder Tree walk – root is printed before values in either subtree
  3. PostOrder Treee walk – root is printed after values in its subtrees.

It takes θ(n) time to walk an n -node binary tree.

Querying a binary search tree

Searching

We wishto search for a node with a given key in a BST. Given a pointer to the root of the tree and a key k, TREE_SEARCH returns a pointer to a node with key k if one exists, else it returns NULL. The search begins at the root and moves downward in the tree. For each node x it encounters, it compares the key k with key[x]. if the 2 keys are equal, the search terminates. If k < key[x] the search continues in the left subtree, else it continues in the right subtree. The running time of TREE_SEARCH is O(h), where h is the height of the tree.

TREE_SEARCH(x,k)
1 if x==NULL or k=key[x]
2    then return x
3 if k < key[x]
4    then return TREE_SEARCH(left[x],k)
5    else return TREE_SEARCH(right[x],k)

ITERATIVE_TREE_SEARCH(x,k)
1 while x!=NULL && k != key[x]
2   do if k < key[x]
3      then x <-- left[x]
4      else x <-- right[x]
5 return x

Maximum and Minimum

A minimum can always be found by following left child pointers down from the rroot until a NULL is reached :

TREE_MINIMUM(x)
1 while left[x] != NULL
2  do x <--- left[x]
3 return x

The pseudo-code for TREE_MAXIMUM is symmetric:

TREE_MAXIMUM(x)
1 while right[x] != NULL
2  do x <--- right[x]
3 return x

Both of these procedures run in O(h) time.

SuCcessor and predecessoR

It is sometimes important to be able to find the successor to a node in the sorted order determined by an inorder tree walk. There are 2 cases:

  1. If the right subtree of node x is nonempty, then the successor of x is the leftmost node in the right subtree, given by TREE_MINIMUM(right[x]).
  2. If the right subtree of x is empty, and x has a successor y, then y is the lowest ancestor of x whose left child is also an ancestor of x.
TREE_SUCCESSOR(x)
1 if right[x] != NULL
2   then return TREE_MINIMUM(right[x])
3 y <-- p[x]
4 while y!=NULL && x=right[y]
5      do x <--- y
6         y <--- p[y]
7 return y

TREE_PREDECESSOR is symmetric to TREE_SUCCESSOR and both run in time O(h),

Insertion and Deletion

Insertion

The TREE_INSERT procedure works as follows – walk down the tree from the root, choosing the left or right child until we find an appropriate leaf node from which to hang the new node. Hence if our new node is z, for each node x if key[z] < key [x], we know that z must hang somewhere off the left subtree of x, and set x as left[x] and as right[x] if NOT.
When we reach a leaf node we have found the node y to hang off and we assign this node y as parent[z]. We then determine if key[z] < key[y]. If so, then z becomes left[y] and if not, it becomes right[y].

TREE_INSERT(T,z)
1 y <--- NULL
2 x <--- root[T]
3 while x !=NULL
4  do y <-- x
5     if key[z] < key[x]
6     then x <--- left[x]
7     else x <--- right[x]
8 parent[z] <--- y        //At this point y=parent[x] from loop above
9 if y == NULL
10   then root[T] <--- z
11   else if key[z] < key[y]
12        then left[y] <--- z
13        else right[y] <--- z

Deletion

There are 3 cases to consider when deleting a node z from a BST.

  1. Node z is a leaf node and has no children In this case we modify parent[z] to replace z as its child with NULL.
  2. Node z has only 1 child. In this case we “splice out” z by making a new link between child[z] and parent[z].
  3. Node z has 2 children. In this case we splice out z ‘s successor y, which has no left child (else it wouldn’t be the successor) and replace z ‘s key and satellite data with y ‘s key and satellite data.
TREE_DELETE(T,z)
1 if left[z]==NULL or right[z]==NULL // Cases 1 && 2
2     then y <--- z                     // Cases 1 && 2
3     else y <--- TREE_SUCCESSOR(z)     // Case 3
4 if left[y] != NULL                    // Lines 4-6 set x to non-NULL child of y, or NULL
5     then x <--- left[y]               // if y has no children 
6     else x <--- right[y]
7 if x != NULL                          // Line 7-13 splice out y
8    then parent[x] <--- parent[y]
9 if parent[y]==NULL                    // y is root,splice it out and set its child as
10   then root[T] <--- x                // root
11   else if y==left[parent[y]]          // If y is the left child of its parent, 
12         then left[parent[y]]  <--- x // splice it out and replace it with it's child x
13         else right[parent[y]] <--- x // else replace the right child of y's parent  
14 if y != z                             // In lines 14-16, if the successor of z y was the
15    then key[z] <--- key[y]           // node spliced out, replace z's key and data with
16       copy y's satellite data into z // that of y
17 return y 

Both insertion and deletion procedures run in O(h) time on a tree of height h.
References :
http://algs4.cs.princeton.edu/32bst