Putting Things Away
local graph
Chapter 8 — Putting Things Away
Section titled “Chapter 8 — Putting Things Away”Imagine that you have to get to Grandma’s house, which, according to legend, is over the hills and through the woods, and two states away. That would be two countries away if you live in Europe. To plan your trip, you can start in one of two ways. Ignoring the fact that Google has taken away most map reading and navigation skills from today’s youth, you would get out a map and do one of the following:
- Start at your house and try to find the roads that are closest to a straight line to Grandma’s house
- Start at Grandma’s house and try to find roads leading to your home
From either direction, you will find that the road or path you seek forks, intersects, changes, meanders, and may even come to a dead end. Also, all roads are not created equally – some are bigger, with higher speed limits, and some are smaller, with more stop signs. In the end, you pick your route by the combination of decisions that results in the lowest cost. This cost may be in terms of time – how long to get there. It may be in terms of distance – how many miles to cover. Or it may be in monetary terms – there is a toll road that charges an extra fee.
In this chapter, we will be discussing several ways to solve problems involving choosing a chain of multiple decisions where there is some metric – such as cost – to help us select which combination is somehow the best. There is a lot of information here that is widely used in robotics, and we will be expanding our horizons a bit beyond our toy-grabbing robot to look at robot path planning and decision-making in general. These are critical skills for any robotics practitioner, so they are included here. This chapter covers the basics of decision-making processes for artificial intelligence (AI) where the problem can be described in terms of either a classification problem (determining whether this situation belongs to one or more groups of similar situations) or a regression problem (fitting or approximating a function that can be a curve or a path). Finally, we will be applying two approaches to our robot problem – an expert system and random forests.
This chapter will cover the following topics:
- Decision trees and random forests
- Path planning, grid searches, and the A* (A-star) algorithm
- Dynamic planning with the D* (D-star) technique
- Expert systems and knowledge bases
At first glance, the concepts we will cover in this section – namely, path planning, decision trees, random forests, grid searches, and GPS route finders – don’t have much in common, other than all being part of computer algorithms used in AI. From my point of view, they are all basically the same concept and approach problems in the same way.
Technical requirements
Section titled “Technical requirements”The one tool we use for this chapter, you should have already installed from earlier chapters – scikit-learn (http://scikit-learn.org/stable/developers/advanced_installation.html).
Or, if you have the pip installer in Python, you can install it using the following command:
pip install –U scikit-learnYou’ll find the code for this chapter at https://github.com/PacktPublishing/Artificial-Intelligence-for-Robotics-2e.
Task analysis
Section titled “Task analysis”Our task in this chapter is one that you may have been waiting for if you have been keeping score since Chapter 3, where we discussed our storyboards. We need to navigate around the room on our wheels and find a path to our destination, whether that is picking up a toy or driving to a toybox.
To achieve this, we will be using decision trees, classification (a type of unsupervised learning), fishbone diagrams, which are good for troubleshooting, and finally, path planning.
Introducing decision trees
Section titled “Introducing decision trees”The concept of a decision tree is fairly simple. You are walking down the sidewalk and come to a corner. Here, you can go right, turn left, or go straight ahead. That is your decision. After making the decision – to turn left – you now have different decisions ahead of you than if you turned right. Each decision creates paths that lead to other decisions.
As we are walking down the sidewalk, we have a goal in mind. We are not just wandering around aimlessly; we are trying to get to some goal. One or more combinations of decisions will get us to the goal. Let’s say the goal is to get to the grocery store to buy bread. There may be four or five paths down sidewalks that will get you to the store, but each path may be different in length or may have different paths. If one path goes up a hill, that may be harder than taking the level path. Another path may have you wait at a traffic light, which costs time. We assign a value to each of these attributes and generally want to pick the path with the lowest cost, or the highest reward, depending on the problem.
In the following decision tree, we can break down the actions of the robot in order to pick up a toy. We start by looking at the toy aspect ratio (the length versus width of the bounding box we detected in Chapter 4). We adjust the wrist of the robot arm based on the narrowest part of the toy. Then, we try to pick up the toy with that wrist position. If we are successful, we lift the toy off the ground and carry it to the toybox. If we fail, we try another position. After trying all of the positions, we go on to the next toy and try to come back to this toy later, hopefully from a different angle. You can see the utility of breaking down our actions this way, and it ends up that decision trees are useful for a lot of things, as we will see in this chapter:

Figure 8.1 – A simple decision tree on how to pick up toys
The general problem with decision tree-type problems is one of exponential growth. Let’s consider a chess game, a favorite problem set for AI. We have 20 choices for an opening move (8 pawns and 2 knights, each with 2 possible moves). Each of these 20 moves has 20 possible next moves, and so on. So the first move has 20 choices, and the second move has 400 choices. The third move has 197,281 choices! We soon have a very, very large decision tree as we try to plan ahead. We can say that each of these possible decisions is a branch, the state we are in after making the decision is a leaf, and the entire conceptual structure is a decision tree.
Note
The secret to working with decision trees is to ruthlessly prune the branches so you consider as few decisions as possible.
There are two ways to deal with a decision tree (actually, there are three – see if you can guess the third before I explain it):
- The first way is to start at the beginning and work outward towards your goal. You may come to a dead end, which means back-tracking or possibly starting over. We are going to call this forward chaining (chain, as we are making a path of links from leaf to leaf in the tree).
- The other way is to start with the goal and work up the tree toward the start. This is backward chaining. The cool thing about backward chaining is that there are a lot fewer branches to traverse. You can guess that a major problem with backward chaining is you have to know what all the leaves are in advance before you can use them. In many problems, such as a grid search or a path planner, this is possible. It does not work in chess, with an exponentially massive tree.
- The third technique? No one says we can’t do both – we could combine both forward and backward chaining and meet somewhere in the middle.
The choice of decision tree shapes, chaining techniques, and construction is based on the following:
- What data is available?
- What information is known or unknown? How is the path scored or graded?
There are also different kinds of solutions for path planning using decision trees. If you were given unlimited resources, the biggest computer, perfect knowledge in advance, and are willing to wait, then you can generate an optimal path or solution.
One of my lessons learned from years of developing practical AI-based robots and unmanned vehicles is that any solution that meets all of the criteria or goals is an acceptable and usable solution, and you don’t have to wait and continue to compute the perfect or optimal solution. Often then, a good enough solution is found in 1/10 or even 1/100 the time of an optimal solution, because an optimal solution requires an exhaustive search that may have to consider all possible paths and combinations.
So, how do we approach making our decision trees work faster, or more efficiently? We do what any good gardener would do – start pruning our trees.
What do we mean by pruning?
Section titled “What do we mean by pruning?”Sometimes in the computer business, we have to make metaphors to help explain to people how something works. You may remember the desktop metaphor that Apple, and later, Windows, adopted to help explain graphical operating systems. Sometimes, we just run those metaphors into the ground, such as the trash can to delete files, or Clippy, the paper clip assistant.
You may feel that I’ve gone off the metaphorical deep end when I discuss pruning your decision trees. What’s next, fertilizer and tree spikes? Actually, pruning is a critical concept in decision tree-type systems. Each branch in your tree can lead to hundreds or thousands of sub-branches. If you can decide early that a branch is not useful, you can cut it out and you don’t have to process any of the branches or leaves in that branch. The sooner you can discover that a path is not getting you to your goal, the quicker you can reduce the time and effort involved in creating a solution, which is a real-time system such as a robot, a self-driving car, or an autonomous aircraft; this can spell the difference between usable and worthless.
Let’s run through a quick example in which we use the pruning method. One great use for a decision tree process is Fault Detection, Isolation, and Recovery (FDIR). This is a typical function of a robot. Let’s make a decision tree for FDIR in the case of our Tinman robot not moving. What automated steps could we take to detect the fault, isolate the problem, and then recover? One technique we can use is root cause analysis, where we try to figure out our problem by systematically listing and then eliminating (pruning) causing factors and seeing whether the symptoms match. One way to approach root cause analysis is to use a special form of decision tree called a fishbone diagram, or Ishikawa diagram. This diagram is named after its inventor, Professor Kaoru Ishikawa from the University of Tokyo. In his 1968 paper, Guide to Quality Control, the fishbone diagram is named because of its shape, which has a central spine and ribs jutting off on either side. I know, the metaphors are getting deep when we have a decision tree in the shape of a fish.
Now, we begin to have a problem. Remember that in a robot, a problem is a symptom, not a cause. Our problem is the robot is not moving. What can cause this problem? Let’s make a list:
- The drive system
- The software
- The communication system
- The battery and wiring
- The sensors
- Operator error
Now, for each of these, we subdivide our branches into smaller branches. What parts of the drive system can cause the robot to not be able to move? The wheels could be stuck. The motors could not be getting power. The gears could be jammed. The motor driver could have overheated. Here is my fishbone diagram to illustrate the problem of the robot not moving:

Figure 8.2 – A fishbone, or Ishikawa, diagram is commonly used for troubleshooting
For each of these factors, you can consider what would be the symptoms of that problem being the cause. If the gears in the motors are jammed, then the motors can’t turn and the wheels can’t turn. If we can check any of these factors off, we can prune or eliminate the gears from our diagram or decision tree. We check the gears, and the wheels and motors turn by hand, so the gears are not the cause. We prune that branch. If we have an automated way of doing testing, we can automatically prune branches, which we will be able to do in the later examples in this chapter.
How about the battery? The battery could need charging (dead battery), the battery could be disconnected, or a power wire could be loose. We check the battery voltage – that is OK, so prune that leaf off the tree. We check the wiring – nothing loose. The battery branch gets pruned.
And so we go on until we have something that either matches all our symptoms or is the last one left. Let’s say the last branch was communications. Now what? We ask, “What things in communications would cause us not to move?” Our first answer is that motor command messages are not getting through to our robot over the network. We check the log and see, indeed, no motor messages are present (cmd_vel, in our case). There is our problem, but what caused the problem? The network could be broken (checked – no, the network is OK), or the IP address could be wrong (no, that’s OK). We look to see whether any recent changes were made to the control software, and indeed, there were. We revert to the previous version and see the robot move. There is our problem and we used a decision tree to find it.
So, in this case, we solved our problem almost entirely by pruning branches and leaves off our tree until only one path was left, or we arrived at our goal.
How can we prune branches in software? We can look for dead ends. Dead ends are leaves – parts of the tree that end and have no future branches. When we reach a dead end, we can not only prune that leaf but also the parts of the path that exclusively lead to that branch. This would be a backward-chaining approach to pruning, as we start at the end and work backward.
We can also see sections of the tree that are unused, or never referenced or called. We can remove entire sections in this manner. This is forward chaining because we are traversing the tree in the forward direction, from the front to the back.
Up to this point, we, the humans in the story, have been making these decision trees by hand. We have not even discussed how we write a program to allow the robot to use trees to make decisions. Wouldn’t it be a lot nicer if the computer was doing all the hard work of making the tree, deciding the branches, and labeling the nodes instead of us? That is exactly what we will discuss in the next section.
Creating self-classifying decision trees
Section titled “Creating self-classifying decision trees”Let’s consider the problem of classifying toys. We may want to come up with a more efficient robot, which sorts toys in some manner instead of just dumping them in a box. In an ideal world, out of a population of 20 toys, we would have some characteristics that divided the group evenly in half – 10 and 10. Let’s say it is length – half of the toys are under six inches long and half are over. Then, it would also be ideal if some other characteristic divided each of those groups of 10 in half – into four groups of five.
Let’s say it’s color – we have five red toys, five blue toys, five green toys, and five yellow toys. You may recognize that we are doing what biologists do in classifying new species – we are creating a taxonomy. Now, we pick another attribute that separates the toys into even smaller groups – it might be what kind of toy it is or what size wheels it has. I think you get the picture. Let’s look at an example.
Now, what would be great is if we could list all the toys and all the attributes in a table, and let the computer figure out how many groups and what kinds there are. We could create a table like this one:
| Type | Length | Width | Weight | Color | Number of wheels | Noise | Soft | Material | Eyes | Toy Name |
|---|---|---|---|---|---|---|---|---|---|---|
| car | 3 | 1 | 35 | red | 4 | 0 | hard | metal | 0 | hotwheels |
| car | 3 | 1 | 35 | orange | 4 | 0 | hard | metal | 0 | hotwheels |
| car | 3 | 1 | 35 | blue | 4 | 0 | hard | metal | 0 | hotwheels |
| car | 3 | 1 | 35 | blue | 4 | 0 | hard | metal | 0 | hotwheels |
| car | 3 | 1 | 35 | white | 4 | 0 | hard | metal | 0 | hotwheels |
| stuffed | 5 | 5 | 50 | white | 0 | 0 | verysoft | fur | 2 | plush |
| stuffed | 7 | 5 | 55 | brown | 0 | 0 | verysoft | fur | 3 | plush |
| action | 2 | 4 | 80 | gray | 0 | 0 | hard | metal | 0 | slinky |
| build | 2 | 2 | 125 | wood | 0 | 0 | hard | wood | 0 | wood block 2x2 |
| build | 2 | 2 | 75 | wood | 0 | 0 | hard | wood | 0 | wood block triangle |
| build | 4 | 2 | 250 | wood | 0 | 0 | hard | wood | 0 | wood block 4x2 |
| dish | 3 | 3 | 79 | blue | 0 | 0 | hard | ceramic | 0 | teapot |
| aircraft | 7 | 5 | 65 | white | 4 | 1 | hard | plastic | 0 | space shuttle |
| aircraft | 13 | 7 | 500 | green | 8 | 1 | hard | plastic | 0 | Thunderbird 2 |
| car | 5 | 1 | 333 | yellow | 6 | 1 | hard | metal | 0 | school bus |
| music | 12 | 4 | 130 | wood | 0 | 2 | hard | wood | 0 | toy guitar |
| music | 5 | 2 | 100 | yellow | 0 | 1 | hard | plastic | 0 | play microphone |
| music | 4 | 4 | 189 | white | 0 | 2 | hard | wood | 0 | toy drum |
Table 8.1 – A table of attributes for a group of toys used for classification
We now have a problem we have to solve. We will be using a decision tree classifier that is provided with the scikit-learn Python package called DecisionTreeClassifier. This program cannot use strings as input data. We will have to convert all of our string data into some sort of numeric figure. Fortunately, the scikit-learn library provides us with a function just for this purpose. It provides several encoding functions that convert strings into numbers. The function we will use is called LabelEncoder. This function takes an array of strings and converts it into an enumerated set of integers.
We can take our first column, which has the type of toy. My nomenclature is toy = toy car, stuffed = stuffed animal, aircraft = toy aircraft, and music = toy musical instrument. We also have action for action toy, and build for building toy (that is, blocks, LEGO™, and so on). We’ll have to turn these into some sort of numbers.
LabelEncoder will convert a column in our data table that is populated with strings. The type column from the data is shown in the following code:
['car' 'car' 'car' 'car' 'car' 'stuffed' 'stuffed' 'action' 'build' 'build' 'build' 'dish' 'aircraft' 'aircraft' 'car' 'music' ' music' 'music']
It converts it to the label-encoded toy type:
[3 3 3 3 3 6 6 0 2 2 2 4 1 1 3 5 5 5]
You can see that everywhere where it said car, we now have the number 3. You can also see that 6 = stuffed, 0 = action, and so on. Why the odd numbering? The encoder first sorts the strings in alphabetical order.
We are going to just dive right in from here to create a classification program:
- Here is our decision tree
# decision tree classifier# author: Francis X Govers III ## example from book "Artificial Intelligence for Robotics" #
- We first import the libraries we will be using. There is an extra library called
graphvizthat is useful for drawing pictures of decision trees. You can install it withpip install graphviz - We are going to be using the
pandaspackage, which provides a lot of datafrom sklearn import treeimport numpy as npimport pandas as pdimport sklearn.preprocessing as preprocimport graphviz - Our first step is to read in our data. I created my table in Microsoft Excel and exported it as a comma-separated values (CSV) format. This allows us to read in the data file directly with the column headers. I print out the shape and size of the data file for reference. My version of the file has 18 rows and 11 columns. The last column is just a note to myself on the actual name of each toy. We will not be using the last column for anything. We are building a classifier that will separate the toys
toyData = pd.read_csv("toy_classifier_tree.csv")print ("Data length ",len(toyData))print ("Data Shape ",toyData.shape)
- Now, we can start building our decision tree classifier. We first build an instantiation of the
DecisionTreeClassiferobject. There are two different types of decision tree classification (DTC) algorithms to choose from:- Gini coefficient: The Gini coefficient was developed in 1912 by the Italian statistician Corrado Gini in his paper, Variabilita e Mutabilita. This coefficient, or index, measures the amount of inequality in a group of numbers. A zero value means all the members of the group are the same.
- Entropy method: Entropy, when we are talking about AI, refers to the amount of uncertainty in a set of data. This concept comes from information theory, in which it measures the amount of uncertainty in a random variable. The concept was introduced by Claude Shannon in the 1940s. To create a decision tree, the algorithm tries to decrease entropy (reduce uncertainty) by splitting the group at a point where each child node is more homogenous than its parent.
- Gini coefficient: The Gini coefficient was developed in 1912 by the Italian statistician Corrado Gini in his paper, Variabilita e Mutabilita. This coefficient, or index, measures the amount of inequality in a group of numbers. A zero value means all the members of the group are the same.
Here, we are going to use the Gini coefficient. If we had a group of toy cars that were all the same size and all red, then the Gini coefficient of the group would be 0. If the members of the group are all different, then the Gini coefficient is closer to 1. The Gini coefficient is given by the following equation:
G(S) = 1− ∑ i=1 n p i 2
We have 4 toy cars out of 18 toys, so the probability of a toy car being in a group is 4/18 or 0.222. The decision tree will continue to subdivide classes until the Gini coefficient of the group is 0:
dTree = tree.DecisionTreeClassifier(criterion ="gini")- We need to separate out the values in our data table. The data in the first column, which is called column
0in Python, are our classification labels. We need to pull those out separately, as they are used to separate the toys into classes. From our previous work with neural networks, these would be our outputs or the label data we have used in other machine learning processes. We will be training our classifier to predict the class of the toy based on the attributes in the table (size, weight, color, and so on). We use slicing to pull the data out of the pandas table. Our pandas data table is calledtoyData. If we want the entries in the table, we need to ask fortoyData.values, which will be returned as adataValues=toyData.values[:,1:10]classValues = toyData.values[:,0]
If you are not familiar with slicing notation in Python, the statement toyData.values[:,1:10] returns just the columns in our table from 1 to 10 – it leaves column 0 out. We actually have 11 columns in our table, but since Python starts numbering them at 0, we end up needing 1 to 10. You will probably guess that the other notation just grabs the data in the first column.
- This is the label encoder that we talked about – it will convert the strings in our data into numbers. For example, colors such as red, green, and blue will be converted to numbers such as 0, 1, and 2. The first item to be encoded is the list of class values that we use to label the data. We use the
LabelEncoder.fit()function to come up with the formula for converting strings to numbers, and then theLabelEncoder.transform()function to apply it. Note thatfit()does not produce an output. - Finally, we need to make the string text and the list of encoded numbers match up. What
LabelEncoderwill do is sort the strings alphabetically and start numbering them from A, ignoring any duplicates. If we put incar, car, car, block, stuffed, airplane, we will get2,2,2,1,3,0as the encoding, and we will have to know thatairplane=0,block=1,car=2, andstuffed=3. We need to generate a decoder ring to match up the numbers and text descriptions that look likeairplane, block, car, stuffed. We duplicate theLabelEncoderfunction by using two functions on our list of string-formatted class names:- We use the
set()function to eliminate duplicates- We use the
sorted()function to sort in the correct order
- We use the
- We use the
Now, our class name table and the enumerations generated by LabelEncoder match. We’ll need this later:
lencoder = preproc.LabelEncoder() lencoder.fit(classValues)classes = lencoder.transform(classValues)classValues = list(sorted(set(classValues)))- To make it easy on ourselves, I created a function to automatically find out which columns in our data are composed of strings and to convert those columns into numbers. We start by building an empty list to hold our data. We will iterate through the columns in our data and look to see whether the first data value is a string. If it is, we will convert that whole column into numbers using the label encoder object (
lencoder) we created. The label encoding process has two parts. We calllencoder.fit()to see how many unique strings we have in our column and to create a number for each one. Then, we uselencoder.transposeto insert those numbers intonewData = []for ii in range(len(dataValues[0]))line = dataValues[:,ii]if type(line[0])==str:lencoder.fit(line)line = lencoder.transform(line) - Now, we put all of the data back into the
newDatalist, but there is a problem – we have turned all our columns into rows! We use thetransposefunction fromnumpyto correct this problem. But wait! We don’t have an array anymore, as we turned it into a list so we could take it apart and put it back together again (you can’t do that with anumpyarray – believe me, I tried):newData.append(line)newDataArray = np.asarray(newData)newDataArray = np.transpose(newDataArray) - Now, all of our preprocessing is done, so we can finally call the real
DecisionTreeClassifer. It takes two arguments:- The array of our data values
- The array of class types that we want the decision tree to divide our groups into
- The array of our data values
DecisionTreeClassifier will determine what specific data from the table is useful for predicting what class one of our toys fits into:
dTree = dTree.fit(newDataArray,classes)That’s it – one line. But wait – we want to see the results. If we just try and print out the decision tree, we get the following:
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None, max_features=None, max_leaf_nodes=None,min_impurity_split=1e-07, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, presort=False, random_state=None, splitter='best')That does not tell us anything; that is a description of the DecisionTreeClassifier object (it does show us all of the parameters we can set, which is why I put it here).
- So, we use a package called
graphviz, which is very good at printing decision trees. We can even pass our column names and class names into the graph. The final two lines output the graph as a.pdffile and store it on thec_data=tree.export_graphviz(dTree,out_file=None,feature_names=toyData.colum ns, class_names=classValues, filled = True, rounded=True,special_characters=True)graph = graphviz.Source(c_data)graph.render("toy_graph_gini")
And here is the result. I will warn you, this is addictive:

Figure 8.3 – The output of the decision tree using the Gini index method
We can quickly check our solution by looking at our input table and seeing whether the numbers line up. We should see the following:
- Five toy cars
- Three building blocks
- One dish
- One action toy
- Two stuffed animals
- Three musical instruments
- Two toy airplanes
And that is indeed the case.
The other number to look at is the Gini index. As shown in Figure 8*.3*, the top-level box shows that the index for the entire group has an overall value of 0.8166, which is close to 1 and shows a high degree of heterogeneity. As we progress down the tree, the Gini numbers get smaller and smaller until reaching 0 at each of the identified groups, which shows that the items in those groups share all of the same attributes.
What does this graph tell us? First of all, we can separate the toy cars by only one attribute – width. Only the toy cars are less than 1.5 inches wide (38 mm). We don’t need to look at color, weight, or anything other than width to separate all the toy cars from everything else. We see we have 5 toy cars out of our 18 toys, so we have 13 left to classify. Our next division comes in length. We have 7 toys less than 4.5 inches long (11 cm) and 5 that are longer. Of the group of five, two have eyes and three do not. The toys with eyes are the two stuffed animals. If you follow the tree, the branches that lead to the toy music instruments are width > 1.5 inches, length > 4.5 inches, and no eyes, and they are indeed larger than the other toys in length and width, and don’t have eyes.
None of the other bits matter in terms of classifying. That means that an attribute such as color is a poor predictor of what class a toy belongs to – which makes sense. Our other useful criteria are the number of wheels, the weight, and the length. That data is sufficient to classify all our toys into groups. You can see that the Gini index of each leaf node is indeed 0. I added some additional labeling to the graph to make the illustration clearer, as the program uses the class number rather than the class name in the graph.
So, that exercise was satisfactory – we were able to create an automatic decision tree from our toy data that classified our toys. We can even use that data to classify a new toy and predict which class it might belong to. If we found that that new toy violated the classification somehow, then we would need to re-rerun the classification process and make a new decision table.
There is another type of process for creating decision trees and subdividing data into categories. That is called the entropy model, or information gain. Let’s discuss this next.
Understanding entropy
Section titled “Understanding entropy”Entropy is a measurement of the amount of disorder in the sample of data provided. We can also call this process information gain since we are measuring how much each criterion contributed to our knowledge of which class it belongs to.
The formula for entropy is a negative log base 2 function that is still primarily looking at the probability of a class belonging to a population, which is just the number of individuals belonging to each class divided by the total number in the sample:
Entropy = -p*log2(p) – p_i*log2(p_i)
To substitute entropy as our group criteria in our program, we only have to change one line:
dTree = tree.DecisionTreeClassifier(criterion ="entropy")The results are shown in the following diagram:

Figure 8.4 – Output of the decision tree using entropy (information gain)
You can note that entropy starts at 2.55 for our whole group, and decreases to 0 at the leaf nodes (ends of the branches). We can check that we have seven classifications, but you can see that the entropy method selected different criteria from the Gini method. For example, the Gini classifier started with Length, and the entropy classifier started with Material. The entropy method also chose Noise (whether the toy makes a noise or not) and correctly selected that the only toys that make a noise were the toy musical instruments and the toy airplanes, which have electronic sound boxes that make airplane sounds.
There is one item that causes some concern, however. There are two blocks that show Material, dividing the toy’s values in material less than 2.5. Material is a discrete value. We can generate a list of materials and run this through our sorted(set(list)) process to get the unique values in sorted order:
['ceramic', 'fur', 'metal', ' plastic', 'wood']
So, a Material value of 2.5 or less would be either ceramic or fur. Fur and ceramic have nothing in common, other than where they are found in the alphabet. This is a rather troubling relationship, which is an artifact of how we encoded our data as a sequential set of numbers. This implies relationships and grouping that don’t really exist. How can we correct this?
As a matter of fact, there is a process for handling just this sort of problem. This technique is widely used in AI programs and is a must-have tool for working with classification, either here in the decision tree section or with neural networks. This tool has the strange name of one-hot encoding.
Implementing one-hot encoding
Section titled “Implementing one-hot encoding”The concept for one-hot encoding is pretty simple. Instead of replacing a category with an enumeration, we add one column to our data for each possible value and set it to be a 1 or 0 based on that value. The name comes from the fact that only one column in the set is hot or selected.
We can apply this principle to our example. We can replace the one column, Material, with five columns for each material type in our database: ceramic, fur, metal, plastic, and wood:
| Material | ceramic | fur | metal | plastic | wood |
|---|---|---|---|---|---|
| metal | 0 | 0 | 1 | 0 | 0 |
| metal | 0 | 0 | 1 | 0 | 0 |
| metal | 0 | 0 | 1 | 0 | 0 |
| metal | 0 | 0 | 1 | 0 | 0 |
| metal | 0 | 0 | 1 | 0 | 0 |
| fur | 0 | 1 | 0 | 0 | 0 |
| fur | 0 | 1 | 0 | 0 | 0 |
| metal | 0 | 0 | 1 | 0 | 0 |
| wood | 0 | 0 | 0 | 0 | 1 |
| wood | 0 | 0 | 0 | 0 | 1 |
| wood | 0 | 0 | 0 | 0 | 1 |
| ceramic | 1 | 0 | 0 | 0 | 0 |
| plastic | 0 | 0 | 0 | 1 | 0 |
| plastic | 0 | 0 | 0 | 1 | 0 |
| metal | 0 | 0 | 1 | 0 | 0 |
| wood | 0 | 0 | 0 | 0 | 1 |
| plastic | 0 | 0 | 0 | 1 | 0 |
| wood | 0 | 0 | 0 | 0 | 1 |
Table 8.2 – One-hot encoding data structure for the Material category
This does cause some structural complications to our program. We must insert columns for each of our types, which replaces 3 columns with 14 new columns.
I’ve found two functions that we can use to convert text categories into one-hot encoded multiple columns:
- One is
OneHotEncoder, which is part ofscikit-learn. It is used likeLabelEncoder– in fact, you must use both functions at the same time. You have to convert the string data to numeric form withLabelEncoderand then applyOneHotEncoderto convert that to the one-bit-per-value form that we want. - The simpler way is with a pandas function called
get_dummies(). The name is apparently because we are creating dummy values to replace a string with numbers. It does perform the same function. The steps involved are quite a bit simpler than using theOneHotEncoderprocess, so that will be the one in our example.
Let’s look at the steps we need to follow to implement this:
- The top header section is the same as before – we have the
# decision tree classifier# with One Hot Encoding and Gini criteria ## Author: Francis X Govers III ## Example from book "Artificial Intelligence for Robotics" #from sklearn import treeimport numpy as npimport pandas as pdimport sklearn.preprocessing as preprocimport graphviz
- We will begin by reading in our table as before. I added an extra column at my end called
Toy Nameso I could keep track of which toy is which. We don’t need this column for the decision tree, so we can take it out with the pandasdelfunction by specifying the name of the columntoyData = pd.read_csv("toy_classifier_tree.csv")del toyData["Toy Name"] # we don't need this for now - Now, we are going to create a list of the columns we are going to remove and replace from the pandas
dataTable. These are theColor,Soft, andMaterialcolumns. I used the term Soft to identify toys that were soft and squished easily (as compared to hard plastic or metal) because that is a separate criterion we may need for using our robot hand. We generate the dummy values and replace the 3 columns with 18 new columns. pandas automatically names the columns with a combination of the old column name and the value. For example, the singleColorcolumn is replaced byColor_white,Color_blue,Color_green, and so on:textCols = ['Color','Soft','Material']toyData = pd.get_dummies(toyData,columns=textCols) - I put a
printstatement here just to check that everything got assembled correctly. It is optional. I’ve been really impressed with pandas for data tables – there is a lot of capability there to do database-type functions andprint toyData - Now, we are ready to generate our decision tree. We instantiate the object and call it
dTree, setting the classification criteria to Gini. We then extract the data values from ourtoyDatadataframe, and put the class values in the first (0th) column into theclassValuesvariable, using arraydTree = tree.DecisionTreeClassifier(criterion ="gini")dataValues=toyData.values[:,1:]classValues = toyData.values[:,0] - We still need to convert the class names into an enumerated type using
LabelEncoder, just as we did in the previous two examples. We don’t need to one-hot encode. Each class represents an end state for our classification example – the leaves on our decision tree. If we were doing a neural network classifier, these would be our output neurons. One big difference is that when using a decision tree, the computer tells you what the criteria were that it used to classify and segregate items. With a neural network, it will do the classification but you have no way of knowing what criterialencoder = preproc.LabelEncoder()lencoder.fit(classValues)classes = lencoder.transform(classValues) - As we said, to use the class value names in the final output, we have to eliminate any duplicate names and sort them alphabetically. This pair of nested functions
classValues = list(sorted(set(classValues)))
- This is the conclusion of our program. Actually creating the decision tree only takes one line of code, now that we have set up all the data. We use the same steps as before, and then create the graphic with
graphvizand save the image as a PDF. That was not hard at all – now that we have had all that practice settingprint ""dTree = dTree.fit(dataValues,classes)c_data=tree.export_graphviz(dTree,out_file=None,feature_names=toyData.columns,class_names=classValues, filled = True, rounded=True,special_characters=True)graph = graphviz.Source(c_data) graph.render("toy_decision_tree_graph_oneHot_gini")
The result is the flowchart shown in the following figure. This output with one-hot encoding is a bit easier to read than Figure 8*.4* because we can see the numbers in each category. You’ll note that each leaf (end node) has only one category with a count (two stuffed animals and three musical instruments):

Figure 8.5 – The output of the decision tree using one-hot encoding is much easier to read
Since we’ve been able to describe and make all sorts of decision trees, what would we have if we used a whole bunch of them? A forest! Let’s explore what this might look like.
Random forests
Section titled “Random forests”I really wanted to add this section on random forest classifiers, but not just because the name sounds so cool. While I may have been accused of stretching metaphors to the breaking point, this time, the name may have inspired the name of this type of decision tree process. We have learned how to make decision trees, and we have learned that they have some weak points. It is best if the data really belongs to distinct and differentiated groups. They are not very tolerant of noise in the data. And they really gets unwieldy if you want to scale them up – you can imagine how big a graph would get with 200 classes rather than the 6 or 7 we were dealing with.
If you want to take advantage of the simplicity and utility of decision trees but want to handle more data, more uncertainty, and more classes, you can use a random forest, which, just as the name indicates, is just a whole batch of randomly generated decision trees. Let’s step through the process:
- We collect our database of information but, instead of 18 rows in our database, we have 10,000 records or 1 million records. We subdivide this data into random sets – we generate 100 sets of data each randomly chosen from all of our data – and we put them in random order. We also pull out one set of data to use as a test set, just as we did for the neural networks.
- Now, for each set of random data, we make a decision tree using the same process we have already learned.
- Now, we have this collection of 100 classification engines, each generated from a different, randomly generated subset of data. We now test our random forest by taking data from the test set and running through all 100 of the trees in our forest. Each tree will provide an estimate of the classification of the data in our test record. If we are still classifying toys, then one of the trees would estimate that we are describing a toy car. Another may think it’s a musical instrument. We take each estimate and treat it as a vote. Then, the majority rules – the class that the majority of the trees selected is the winner. And that is all there is to it.
The setup and program are just the same as what we did before, but you can’t draw a decision tree from a random forest, or just create a tree as an end in itself because that is not what a random forest does – if you just need a decision tree, you know how to do that. What you can do is to use a random forest like a neural network, as either a classification engine (to what class does this data belong?) or a regression engine that approximates a non-linear curve.
At this point, you can conclude with me that decision trees are really useful for a lot of things. But did you know you can navigate with them? The next section covers path planning for robots – using a different type of decision tree.
Introducing robot path planning
Section titled “Introducing robot path planning”In this section, we will be applying decision tree techniques to perform robot navigation. Some people like to refer to these as graph-based solutions, but any sort of navigation problem ends up being a decision tree. Consider as you drive your car, can you divide your navigation problems into a set of decisions – turn right, turn left, or go straight?
We are going to take what we have learned so far and press on to a problem related to classification, and that is grid searching and path finding. We will be learning about the famous and widely used A* (pronounced A-star) algorithm. This will start with grid navigation methods, topological path finding, such as GPS route finding, and finally, expert systems. You will see that these are all versions and variations on the topic of decision trees that we have already learned.
Some problems and datasets, particularly in robotics, lend themselves to a grid-based solution as a simplification of the navigation problem. It makes a lot of sense that, if we were trying to plot a path around a house or through a field for a robot, we would divide the ground into some sort of checkerboard grid and use that to plot coordinates that the robot can drive to. We could use latitude and longitude, or we could pick some reference point as zero – such as our starting position – and measure off some rectangular grid relative to the robot. The grid serves the same purpose in chess, limiting the number of positions under consideration for potential future movement and limiting and delineating our possible paths through the space.
While this section deals with gridded path finding, regardless of whether maps are involved or not, there are robot navigation paradigms that don’t use maps and even some that don’t use grids, or use grids with uneven spacing. I’ve designed robot navigation systems with multiple-layer maps where some layers were mutable – changeable – and some were not. This is a rich and fertile ground for imagination and experimentation, and I recommend further research if you find this topic interesting. For now, let’s start with a description of the coordinate system we’ll be using.
Understanding the coordinate system
Section titled “Understanding the coordinate system”Let’s get back to the topic at hand. We have a robot and room that is roughly rectangular, and within that rectangle are also some roughly rectangular obstacles in the form of furniture, chairs, bookcases, a fireplace, and so on. It is a simple concept to consider that we mark off a grid to represent this space and create an array of numbers that matches the physical room with a virtual room. We set our grid spacing at 1 cm – each grid square is 1 cm x 1 cm, giving us a grid with 580 x 490 squares or 284,200 squares. We represent each square by an unsigned integer in a 2D array in the robot’s memory.
Now, we are going to need some other data. We have a starting location and a goal location, specified as grid coordinates. We’ll put 0,0 for the grid in the nearest and leftmost corner of the room so that all our directions and angles will be positive. In the way I’ve drawn the room map for you in Figure 8*.6*, that corner will always be the lower-left corner of our map. In standard right-hand rule notation, left turns are positive angles and right turns are negative. The x direction is horizontal and the y direction is vertical on the page. For the robot, the x axis is out the right side and the y axis is the direction of motion.
You may think it odd that I’m giving these details, but setting up the proper coordinate system is the first step in doing grid searches and path planning. We are using Cartesian coordinates indoors. We would use different rules outdoors with latitude and longitude. There, we might want to use north-east-down (north is positive, south is negative, east is positive, west is negative, the z axis is down, and the x axis is aligned on the robot with the direction of travel):

Figure 8.6 – Coordinate frames for Earth navigation and indoor navigation
We will be looking at this room map in more detail later.
So, we have our grid and a coordinate system that we agree upon, or at least agree that we both understand. We also have a starting location and an ending location. Our objective is to determine the best path for the robot from the start to the finish point. And in between, we have to plan a path around any obstacles that may be in the way.
Next, we have to talk about knowledge.
Developing a map based on our knowledge
Section titled “Developing a map based on our knowledge”There are basically two kinds of grid search and path finding routines:
- A priori knowledge, where you know where everything is on the map
- A posteriori knowledge, where you don’t know where the obstacles are
We will start in the easier position where we can do our path planning with perfect knowledge of the layout of the room – we have a map.
We really have three goals we are trying to achieve simultaneously with path planning:
- Reach our goal
- Avoid obstacles
- Take the shortest path
We can talk about how we might go about this. We can start with our pencil at the start point and draw an imaginary line from our start to the goal. If there are no obstacles in the way, we are done. But wait – our pencil is a tiny line on paper. Our robot is somewhat chubbier – it has a significant width as it drives around. How do we judge whether the robot is going down some narrow passage that it won’t fit into? We need to modify our map!
We have our grid, or a piece of paper that represents the grid. We can draw on that grid the outlines of all the obstacles, to scale. We have two chairs, two tables, a fireplace, two ottomans, and four bookcases. We color in all the obstacles in the darkest black we can. Now, we get a lighter colored pencil – say a blue color – and draw an outline around all of the furniture that is half the width of the robot. Our robot is 32 cm wide, so half of that is 16 cm, a nice even number. Our grid is 1 cm per square, so we make a 16-square border around everything. It looks like this:

Figure 8.7 – Adding safety boundaries to obstacles helps prevent collisions
So, now our map has two colors – obstacles and a keep-out border. We are going to keep the center of the robot out of the keep-out zone, and then we will not hit anything. This should make sense. As for judging passages and doorways, if the keep-out zones touch on either side (so if there are no white squares left in the middle), then the robot is too big to pass. You can see this around the ottoman in the upper-left corner of the illustration.
We look at our line now. We need a way to write a computer algorithm that determines the white squares that the robot can pass through that gets us from the start point to the finish point.
Since we have the goal in Cartesian coordinates and we have our start spot, we can express the distance in a straight line from the start to the finish. If the start point is x1, y1 and the finish point is x2, y2, then the distance is the square root of the sums of the difference between the points:
*distance = sqrt(x2-x1)^2 + (*y2-y1)^2)
One approach for developing a path planning algorithm is to use a wavefront method. We know where the start is. We go out in every direction to the eight squares adjacent to the start point. If any of those hit an obstacle or keep-out zone, we throw it out as a possible path. We keep track of how we got to each square, which, in my illustration (Figure 8*.8*), is indicated by the arrows. We use the information on how we got to the square because we don’t yet know where we are going next. Now, we take all the new squares and do the same thing again – grabbing one square, seeing which of its eight neighbors is a legal move, and then putting an arrow (or a pointer to the location of the previous square) in it to keep track of how we got there. We continue to do this until we get to our goal. We keep a record of the order of the squares we examined and follow the arrows backward to our starting point.
If more than one square has a path leading to the current square, then we take the closest one, which is to say the shortest path. We follow these predecessors all the way back to the starting point, and that is our path:

Figure 8.8 – The wavefront approach to path planning has very little math involved. Each figure is a step in the process, starting at the upper left and going across, then down
You will notice in this example that I allowed the robot to make diagonal turns to get from one square to another. I could have also specified that only right-angle turns are allowed, but that is not very efficient and is hard on the robot’s drive system. Only allowing right-angle turns simplifies the processing somewhat, since you only have to consider four neighbors around a square instead of eight.
Another approach for developing a path planning algorithm that would look promising is the Greedy Best-First approach. Instead of keeping a record and checking all of the grid points as we did in the wavefront method, we just keep the single best path square out of the eight we just tested. The measure we use to decide which square to keep is the one that is closest to our straight-line path. Another way of saying this is to say it’s the square that is closest to the goal. We remove squares that are blocked by obstacles, of course. The net result is we are considering a lot (really a lot!) fewer squares than the wavefront method of path planning:

Figure 8.9 – The aptly named “Greedy Best-First” algorithm is fast, but can get stuck
Does the greedy technique work for all cases? Not really.
Why not? That seems a simple algorithm, and we are only considering legal moves. The problem is it can’t deal with a local minima. What is a local minima? It is a place on the map where the robot would have to go backward to find a good path. The easiest type of minima to visualize is a U-shaped area where the robot can get in but not back out. The Greedy Best-First algorithm is also not trying to find the shortest path, just a valid path:

Figure 8.10 – A “local minima” can occur when no straight path exists, and the robot will have to back up or reverse direction
If we want to find the shortest path, we need to do some more math.
A more systematic and mathematical way to approach finding the shortest path around obstacles for a grid search problem is the A* algorithm, first developed for Shakey the Robot.
Introducing the A* algorithm
Section titled “Introducing the A* algorithm”Honestly, you can’t really write a book about robotics without mentioning the A* algorithm. A* has its origins with Shakey the Robot at Stanford University back in 1968. This was one of the first map-navigating robots. Nils Nilsson and his team were trying to find a method to navigate Shakey around the hallways at Stanford and started trying different algorithms. The first was called A1, the second A2, and so forth. After several iterations, the team decided that a combination of techniques worked best. In computer science, A* means the letter A followed by anything else, and thus the A-star was named.
The concept of the A-star process is very much like what we have already been doing with our other path planners. Like the wavefront planner, we start by considering the neighbors around our starting location. We will compute an estimate for each square based on two factors: the distance from the starting location and the distance in a straight line to the goal. We are going to use these factors to find the path with the lowest cumulative cost. We calculate that cost by adding up the value for each grid square that is part of the path. The formula is as follows:
F(n) = g(n) + h(n)
Here, F(n) refers to the contribution of this square to the path cost, g(n) represents the distance from this square from the start position along the path chosen (that is, the sum of the path cost), and h(n) is the straight line distance from this square to the goal, which is a heuristic or estimate of the distance remaining to the goal. Since we don’t know what other obstacles we have to go around later, we use this guess as a measuring stick to compare paths.
This value represents the cost or contribution of this square if it were a part of the final path. We will select the square to be part of the path that has the lowest combined cost. As with the wavefront planner, we keep track of the predecessor square or the square that was traversed before this one to reconstruct our path:

Figure 8.11 – The A-star computation uses the distance to start (G) and the distance to the goal (H)
The preceding diagram illustrates the A* algorithm. Each square is evaluated based on the sum of the distance along a path back to the start (G), and an estimate of the remaining distance to the goal (H). The yellow squares represent the path selected so far.
Let’s illustrate how the A* algorithm works:
- We keep a set of all the grid squares on the map we have computed values for. We’ll call this
exploredMap. Our map grid square object looks# globalsmapLength = 1280mapWidth = 1200mapSize = mapLength*mapWidthmap = [] - Now, we will fill in our map with zeros to initialize everything. We will define the
mapGridSquarefunction later in the code – it creates ourfor ii in range(0, mapWidth):for jj in range(0,mapLength):mapSq = mapGridSquare()#defined latermapSq.position = [ii,jj]mapSq.sType =EMPTY - The next section creates all of the obstacles on the map. We put the location of which grid squares to fill-in or
# create obstaclesobstacles = [[1,1],[1,2],[1,3],[45,18],[32,15] …..[1000,233]]# iterate through obstacles and mark on the mapfor pos in obstacles:map[pos]. sType = OBSTACLEpathGrid = []
- Now, we declare our starting and
START = [322, 128]GOAL = [938,523]exploredMap = []A_Star_navigation(start, goal, exploredMap, map)
- In this section, we are creating our data structures to keep track of all of the computations we make. The
Gvalue is the computed distance from the start, and theHvalue is the estimated distance to the goal.Fis just the sum of these two. We also create a function to computedef mapGridSquare():def __init__(self):self.F_value = 0.0 #total of G and Hself.G_value = 0.0 # distance to startself.H_value = 0.0 # distance to goalself.position=[0,0] # grid location x and yself. predecessor =None # pointer to previous squareself.sType = PATHdef compute(self, goal, start):self.G_value = distance(goal.position,self.position)self.H_value = distance(start.position,self.positionself.F_value = self.G_value + self.H_valuereturn self.F_value - We need a function to trace the path from the goal back to the start once we’ve completed the map computations. This function is
reconstructPathdef reconstructPath(current):totalPath=[current]done=Falsewhile not done:a_square = current.predecessorif a_square == None: # at start position?done = TruetotalPath.append(a_square)current = a_squarereturn totalPath - We create a
findMinfunction to locate the grid block that we have explored with the lowestFdef findMin(map):minmap = []for square in map:if minmap == []:minmap = squarecontinueif square.F_value < minmap.F_value:minmap = squarereturn minmap - Then, we create the
navigationdef A_Star_navigation(start, goal, exploredMap, map):while len(exploredMap>0):current = findMin(exploredMap)if current.position == goal.position:# we are done – we are at the goalreturn reconstructPath(current)neighbors = getNeighbors(current) - The
neighborsfunction returns all the neighbors of the current square that are not markedfor a_square in neighbors:if a_square.predecessor == None: - We only compute each grid
old_score = a_square.F_valuescore = a_square.compute(GOAL, START)
- Now, we look for the square that has the lowest
Gvalue – that is, the one closest toif a_square.G_value < current.G_value:a_square.predecessor = currentcurrent = a_squarecurrent.compute(GOAL, START)exploredMap.append(current)
So, in this section, we’ve covered the A* approach to finding the shortest path on a map, given that we know where all of the obstacles are in advance. But what if we don’t? Another method we can use is the D* algorithm.
Introducing the D* (D-star or dynamic A*) algorithm
Section titled “Introducing the D* (D-star or dynamic A*) algorithm”Earlier in the chapter, I talked about a priori knowledge. The A-star algorithm, for all its usefulness, requires that obstacles in the entire map be known in advance. What do we do if we are planning a movement into an unknown space, where we will create the map as we go along? If we have a robot with sensors, such as sonar or lidar, then the robot will be detecting and identifying obstacles as it goes. So, it must continually replan its route based on increasing information.
The A* process is only run one time to plan a route for a robot before it begins to move. D*, a dynamic replanning process, is constantly updating the robot’s path as new information becomes available.
The D* algorithm allows for replanning by adding some additional information to each grid square. You will remember that in A*, we had the G value (distance to the start along the path), and the H value (straight-line distance to the goal). D-star adds a tag to the square that can have several possible values:
- The square’s tag could be
NEWfor a new square that had never been explored before. - It could be
OPENfor tags that have been evaluated and are being considered as part of the path. CLOSEDis for squares that have been dropped from consideration.- The next two tags are
RAISEDandLOWERED. TheRAISEDflag is set if a sensor reading or additional information caused the cost of that square to increase, andLOWEREDis the opposite. ForLOWEREDsquares, we need to propagate the new path cost to the neighbors of the now lower-cost square, so that they can be re-evaluated. This may cause tags to change on the neighboring squares.RAISEDsquares have increased cost, and so may be dropped from the path, andLOWEREDsquares have reduced cost and may be added into the path.
Note
Keep in mind that changes in cost values ripple through the D* evaluation of paths like a wave as the path is backtracked all the way to the start when the values change.
Another major difference between D* and A* is that D* starts at the goal and works backward toward the start. This allows D* to know the exact cost to the target – it is using the actual path distance to the goal from the current position and not a heuristic or estimate of the distance to go, as A* did.
This is a good time to remind you that all these grid-searching techniques we just covered are still variations of decision trees. We are going from leaf to leaf – which we have been calling grid squares, but they are still leaves of a decision tree. We set some criteria for choosing which of several paths to take, which make branching paths. We are working toward some goal or endpoint in each case. I bring this up because, in the next section, we will combine decision trees and the type of path planning we learned from the A* and D* algorithms to find a path through streets with a GPS.
GPS path finding
Section titled “GPS path finding”I wanted to have the opportunity (since we have come this far) to talk just for a little bit about topological path planners. This is an alternative method to the grid-based techniques we used in the preceding sections. There are types of problems and types of navigation where a grid-based approach is not appropriate or would require astronomical amounts of detailed data that may not be available or practical in a small robot.
As an example, I wanted to talk about how your GPS in your car finds a route along streets to reach your destination. You must have wondered about how that box has enough information in its tiny brain to provide turn-by-turn directions from one place to another. You may have imagined, if you stopped to think about it, that the GPS was using the same map you were viewing on the LCD screen to determine where you need to go. You would also think that some sort of grid-based search took place, such as the A* algorithm we discussed in such detail. And you would be wrong.
The data that the GPS uses to plan a route does not look like a map at all. Instead, it is a topological network that shows how streets are interconnected. In format, it looks more like a database of vectors (which have a direction and a magnitude, or distance), rather than an X, Y gridded raster map made up of pixels. The database format also takes up a lot less room in the GPS internal storage. The streets are divided by nodes or points where roads intersect or change. Each node shows which streets are connected. The nodes are connected by links, which allow you to traverse the data from node to node. The links represent the roads and have a length, along with cost data about the quality of the road. The cost data is used to compute the desirability of the route. A limited access highway with a high-speed limit would have a low cost, and a small side street or dirt road with a lot of stop signs would have a high cost since that link is both less desirable and slower.
The technique that most GPS path planners use is called Dijkstra’s algorithm, after Edsger W. Dijkstra, from the Netherlands. He wanted to find the shortest path from Rotterdam to Groningen, back in 1956. His graph-based solution has withstood the test of time and is very commonly used for GPS routing. It’s not of any help to us for our robot, so you can research this on your own.
We use the same procedures with the GPS road network database as we would when working the A-star process on a grid map. We evaluate each node, and progress outward from our start node, choosing the path that takes us closest in the direction of our destination:

Figure 8.12 – A road-based network can be represented as a series of nodes (circles) and links (lines)
Many GPS systems also simultaneously try to backward-chain from the endpoint – the goal or destination – and try to meet somewhere in the middle. An amazing amount of work has gone into making our current crop of GPS systems small, lightweight, and reliable. Of course, they are dependent on up-to-date information in the database.
Summary
Section titled “Summary”Well, this has been a very busy chapter. We covered the uses of decision trees for a variety of applications. The basic decision tree has leaves (nodes) and links, or branches, that each represent a decision or a change in a path. We learned about fishbone diagrams and root cause analysis, a special type of decision tree. We showed a method using scikit-learn to have the computer build a classification decision tree for us and create a usable graph. We discussed the concept of random forests, which are just an evolved form of using groups of decision trees to perform prediction or regression. Then, we got into graph search algorithms and path planners, spending some time on the A* (or A-star) algorithm, which is widely used for making routes and paths. For times when we do not have a map created in advance, the D* (or dynamic A-star) process can use dynamic replanning to continually adjust the robot’s path to reach its goal. Finally, we introduced topological graph path planning and discussed how GPS systems find a route for you to the coffee shop.
In our next chapter, we’ll be talking about giving your robot an artificial personality, by simulating emotions using a Monte Carlo model.
Questions
Section titled “Questions”- What are the three ways to traverse a decision tree?
- In the fishbone diagram example, how does one go about pruning the branches of the decision tree?
- What is the role of the Gini evaluator in creating a classification?
- In the toy classifier example using Gini indexing, which attributes of the toy were not used by the decision tree? Why not?
- Which color for the toys was used as a criterion by one of the classification techniques we tried?
- Give an example of label encoding and one-hot encoding for menu items at a restaurant.
- In the A* algorithm, discuss the different ways that
G()andH()are computed. - In the A* algorithm, why is
H()considered a heuristic andG()is not? Also, in the D* algorithm, heuristics are not used. Why not? - In the D* algorithm, why is there a
RAISEDandLOWEREDtag and not just aCHANGEDflag?
Further reading
Section titled “Further reading”- Introduction to the A* Algorithm: https://www.redblobgames.com/pathfinding/a-star/introduction.html
- Introduction to AI Robotics by Robin R. Murphy, MIT Press, 2000
- How Decision Tree Algorithm Works: https://dataaspirant.com/2017/01/30/how-decision-tree-algorithm-works/
- Game Programming Heuristics: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
- D*Lite Algorithm Blog (Project Fast Replanning) by Sven Koening: http://idm-lab.org/project-a.html
- Graph-Based Path Planning for Mobile Robots, Dissertation by David Wooden, School of Electrical and Computer Engineering, Georgia Institute of Technology, December 2006
- The Focused D* Algorithm for Real-Time Replanning by Anthony Stentz: https://robotics.caltech.edu/~jwb/courses/ME132/handouts/Dstar_ijcai95.pdf