Lab 5

From 6.034 Wiki

Jump to: navigation, search


This lab is due by Friday, October 21 at 10:00pm.

To work on this lab, you will need to get the code, much like you did for the previous labs. You can:

Your answers for this lab belong in the main file This lab covers both identification trees and k-nearest neighbors. The two halves of the lab are independent, so you may work on them in parallel.

The online tester is now available! Note that if you downloaded the Lab 5 files before the morning of Tuesday October 11, you will need to git pull or download a new in order to submit your code online.

Identification Trees

In this section of the lab, we will first warm up by using an ID tree to classify points. Then, we will learn how to construct new ID trees from raw data, using the techniques we learned in class.

Note: We strongly recommend reading the API section before writing any code. Otherwise, you may find yourself re-writing code that needn't be written again.

Using an ID Tree to classify unknown points

In this lab, we will represent an ID tree recursively as a tree of IdentificationTreeNode objects. For more information, see the API below.

For the ID trees section, we will represent a data point as a dictionary mapping attributes to values. For example, the following could represent a data point in our vampires example from lecture:

datapoint1 = {"name":"person1", "Vampire?":"Vampire", "Shadow":"?", "Eats Garlic":"No", "Complexion":"Ruddy", "Accent":"Odd"}

To begin, let's use an ID tree to classify a point! Classifying a point using an ID tree is straight-forward. We recursively apply the current node's classifier to the data point, using the result to choose which branch to take to the child node. If a "leaf" node is ever encountered, that node gives the final classification of the point.

Write a function id_tree_classify_point that takes in a point (represented as a dictionary) and an ID tree (represented as a IdentificationTreeNode) and uses the ID tree to classify the point (even if the point already has a classification defined), returning the final classification:

def id_tree_classify_point(point, id_tree):

(Note that the point argument in this function and in all ID-tree questions in this lab has nothing to do with the Point API introduced later on in the kNN section of the lab!)

This function can be written cleanly in 3-4 lines, either iteratively or recursively. If you're not sure how, check out the available methods in the IdentificationTreeNode API. In particular, the methods .apply_classifier(point) and .get_node_classification() may be useful.

Splitting Data with a Classifier

In order to actually construct an ID tree, we'll need to work directly with classifiers, also known as tests. Recall that at each node of an ID tree, unless the training data at this node is homogeneous, we pick the best available classifier to split the data up. This same logic is repeated at every level of the tree, with each node taking as training data the data points sorted into that category by the node above it.

We will represent each classifier as a Classifier object, described in the Classifier API below.

Implement split_on_classifier, which should take in a particular Classifier and a list of points, and return a dictionary mapping each possible feature value for that classifier to a list of the points that have that value (i.e. the data in its branch):

def split_on_classifier(data, classifier):

For example, split_on_classifier(angel_data, feature_test("Shape")) should return a dictionary mapping "Human" to a list of four points and "Animal" to a list of two points.

Calculating Disorder

One of the first steps in constructing an ID tree is to calculate disorder. We'll start by coding the information-disorder equations to calculate the disorder of a branch or test.

However, before we start, we will review some nomenclature:

  • A branch, conceptually, is a set of data representing the points that, upon applying a particular classifier (e.g. "Eats garlic") to a set of many points, all result in the same feature result. For example, suppose our data set is [p1, p2, p3, p4, p5, p6], where each of p1, ... are Python dictionaries representing data points. Then, for example, applying the "Eats garlic" classifier to the data could yield two branches, one for all of the points with "Eats garlic": "Yes" and one for all of the points with "Eats garlic": "No".
  • A test (also known as a decision stump or feature test, and sometimes referred to loosely as a classifier) encompasses all of the branches for a particular classifier. In the example for branches above, the two branches ("Yes" and "No") together constitute the decision stump for the "Eats garlic" classifier, often referred to concisely as the test.

Now, recall that the information disorder of a branch represents how different the values are in that branch. A branch whose points all have the same final classification is homogeneous, and has a disorder of 0. On the other hand, a branch with many different values has a very high disorder. For example, a branch that has two points with classification "Vampire" and two points with classification "Not Vampire" has a disorder of 1.

The formula we use for disorder originates in information theory, and is described in detail on page 429 of the reading.

As a quick example, suppose we have a data set representing different types of balls:

ball1 = {"size": "big", "color": "brown", "type": "basketball"}
ball2 = {"size": "big", "color": "white", "type": "soccer"}
ball3 = {"size": "small", "color": "white", "type": "lacrosse"}
ball4 = {"size": "small", "color": "blue", "type": "lacrosse"}
ball5 = {"size": "small", "color": "yellow", "type": "tennis"}
ball_data = [ball1, ball2, ball3, ball4, ball5]

Then, applying the classifier for "size" yields two branches:

branch1 = [ball1, ball2]
branch2 = [ball3, ball4, ball5]

where branch1 represents balls that are big and branch2 represents balls that are small. The disorder of branch1 is 1, because the classifications in this branch are ["basketball", "soccer"]. However, the disorder of branch2 is roughly 0.9, because the classifications in this branch are ["lacrosse", "lacrosse", "tennis"].

However, applying the classifier for "color" instead yields

branch1 = [ball1]
branch2 = [ball2, ball3]
branch3 = [ball4]
branch4 = [ball5]

Here, the disorders of branch1, branch3, and branch4 are all 0, and the disorder of branch2 is 1.

Now, complete the function branch_disorder. branch_disorder should take in a list of data points in the current branch as well as the classifier that for determining the final classification of the points, and return the disorder of the branch, as a number:

def branch_disorder(data, target_classifier):

For example, calling branch_disorder([ball3, ball4, ball5], ball_type_classifier) should yield approximately 0.918.

The following Python tricks and shortcuts may be useful here and/or later in the lab:

  • log2: We've defined a function log2 that takes in a single number and returns log2 of the number.
  • INF: As in previous labs, we've defined the constant INF, which is a float representing infinity
  • float: Recall that if you divide two ints in Python2, it rounds down to the nearest int, so you'll need to cast one of them to a float if you want to perform normal division.

Next, use your branch_disorder function to help compute the disorder of an entire test (a decision stump). Recall that the disorder of a test is the weighted average of the disorders of the constituent branches, where the weights are determined by the fraction of points in each branch.

average_test_disorder should take in a list of points (the data), a Classifier (the feature test), and the target_classifier for determining the final classification of the points, then compute and return the disorder of the entire test, as a number:

def average_test_disorder(data, test_classifier, target_classifier):

For example, calling average_test_disorder(ball_data, size_classifier, ball_type_classifier) should yield approximately 0.959, because the "small" branch has weight 3/5 and a disorder of about 0.918, while the "big" branch has a weight of 2/5 and a disorder of 1.

Constructing an ID Tree

Using the disorder functions you defined above, implement a function to select the best classifier. The function should take in some data (as a list of point dictionaries), a list of classifiers (Classifier objects), and the target classifier that you ultimately want your ID tree to be classifying by (e.g. a Classifier representing the test "Vampire?"). The function should return the classifier that has the lowest disorder.

Edge cases:

  • If multiple classifiers are tied for lowest disorder, break ties by preferring the classifier that occurs earlier in the list.
  • If the classifier with lowest disorder wouldn't separate the data at all (that is, the classifier has only one branch), raise the exception NoGoodClassifiersError instead of returning a classifier.
def find_best_classifier(data, possible_classifiers, target_classifier):

Now, it is time to build an ID tree!

The function construct_greedy_id_tree should take in four arguments:

  • data: a list of points
  • possible_classifiers: a list of Classifier objects that you can use in constructing your tree
  • target_classifier: the Classifier that the tree should ultimately classify by (e.g. a Classifier representing "Vampire?")
  • id_tree_node (optional): an incomplete tree, represented as an IdentificationTreeNode. If the incomplete tree is provided, finish it; if it is not provided, create a new tree using the constructor: id_tree_node = IdentificationTreeNode(target_classifier)

Then, add classifiers and classifications to the tree until either perfect classification has been achieved, or there are no good classifiers left.

We recommend implementing this function recursively (which can be done cleanly in 16 lines). Your base case should occur when you encounter a leaf node, in which case you should set the node's classification. The recursive step occurs when your classifier splits the data into groups, in which case you should set the classifier, expand the node (hint: set_classifier_and_expand), and recursively construct the tree for each new branch.

As a general outline:

1. Once the current id_tree_node is defined, perform one of three actions, depending on the input node's data and available classifiers:
  • If the node is homogeneous, then it should be a leaf node, so add the classification to the node.
  • If the node is not homogeneous and the data can be divided further, add the best classifier to the node.
  • If the node is not homogeneous but there are no good classifiers left (i.e. no classifiers with more than one branch), leave the node's classification unassigned (which defaults to None).
2. If you added a classifier to the node, use recursion to complete each subtree.
3. Return the original input node.
def construct_greedy_id_tree(data, possible_classifiers, target_classifier, id_tree_node=None):

Congrats, you're done constructing ID trees!

We've provided some datasets from past quizzes, so you can now use your ID tree builder to solve problems! For example, if you run

print construct_greedy_id_tree(tree_data, tree_classifiers, feature_test("tree_type")) should compute and print the solution to the tree-identification problem from 2014 Q2.

You can also try:

print construct_greedy_id_tree(angel_data, angel_classifiers, feature_test("Classification"))  #from 2012 Q2
print construct_greedy_id_tree(numeric_data, numeric_classifiers, feature_test("class"))  #from 2013 Q2

You can also change the target_classifier attribute to, for example, use tree_type to predict what type of bark_texture a tree has:

print construct_greedy_id_tree(tree_data, tree_classifiers_reverse, feature_test("bark_texture"))  #build an ID tree to predict bark_texture

Optional: Construct an ID tree with real medical data

Constructing ID trees for small datasets (such as the ones from quiz problems) is straightforward and generally produces nice, simple trees. But what happens if you construct an ID tree on a real-life dataset with hundreds of points and over a dozen features? In a real medical situation, such as in an emergency room, doctors need a way to quickly determine which patients need immediate attention. If a patient comes in complaining of chest pain, doctors may use an ID tree to ask the patient a series of medical questions to determine the likelihood that the patient has heart disease, or to distinguish between patients with heart disease, pneumonia, and broken ribs (all of which may cause chest pain, but require different treatments and different levels of urgency).

We've provided a dataset cleveland_medical_data.txt of anonymized medical data collected by the Cleveland Clinic Foundation. The dataset contains information on 303 patients who were being checked for heart disease. For each patient, it includes 13 features:

  • Age: int (in years)
  • Sex: M or F
  • Chest pain type: typical angina, atypical angina, non-anginal pain, or asymptomatic (Note that "angina" means "chest pain".)
  • Resting blood pressure: int (in mm Hg)
  • Cholesterol level: int (in mg/dl)
  • Is fasting blood sugar < 120 mg/dl: Yes or No
  • Resting EKG type: normal, wave abnormality, or ventricular hypertrophy
  • Maximum heart rate: int
  • Does exercise cause chest pain?: Yes or No
  • ST depression induced by exercise: int
  • Slope type: up, flat, or down
  • # of vessels colored: float or '?' (This is the number of major vessels (0-3) colored by flourosopy.)
  • Thal type: normal, fixed defect, reversible defect, or unknown

(If you don't understand all the medical terminology, don't worry -- you can still use the data!)

Each patient also has a known classification, represented both on a binary scale and on a discrete scale:

  • Heart disease presence: healthy or diseased
  • Heart disease level: int 0-4, where 0 means healthy (no presence of heart disease), and 1-4 indicate different levels of heart disease, with 4 being the most severe

In, we've parsed the dataset for you and stored it in the variable heart_training_data. heart_training_data is a list of 303 dictionaries, where each dictionary represents a patient and looks something like this:

{'name': 'patient280', 'Cholesterol level': 282, 'ST depression induced by exercise': 1, 'Age': 65, 'Resting EKG type': 'ventricular hypertrophy', 'Chest pain type': 'typical angina', 'Does exercise cause chest pain?': 'No', 'Sex': 'M', 'Thal type': 'normal', '# of vessels colored': 1.0, 'Is fasting blood sugar < 120 mg/dl': 'Yes', 'Resting blood pressure': 138, 'Maximum heart rate': 174, 'Heart disease level': 1, 'Slope type': 'flat', 'Heart disease presence': 'diseased'}

We've also defined a list of 345 Classifiers, most of which are numeric threshold classifiers. As recommended in lecture, we included a threshold classifier between every pair of neighboring possible values for a feature. For example, if one patient has a cholesterol level of 150 and another has 156, but there are no values in between, we'll add a Classifier for "Cholesterol level > 153". All of the classifiers are stored in the variable heart_classifiers.

Finally, we've defined two possible target classifiers:

  • heart_target_classifier_binary, for the binary "Heart disease presence", and
  • heart_target_classifier_discrete, for the discrete "Heart disease level".

To construct an ID tree with this dataset, all you need to do is add from parse import * to your file, then call construct_greedy_id_tree with the heart data, heart classifiers, and target classifier of your choice. (Note: If you downloaded the Lab 5 files on or before Tuesday, October 11, 2016, you may need to git pull or manually download cleveland_medical_data.txt and

What do you notice? Does this seem like the simplest possible tree? If not, why not? What could we change to make it simpler?

Try using the other target classifier (binary or discrete). Is the tree simpler or more complicated? Why?

Try using tree.print_with_data to print the training data at the leaf nodes. What do you notice?

To diagnose a new patient, first create a dictionary of their attributes, for example:

test_patient = {\
    'Age': 20, #int
    'Sex': 'F', #M or F
    'Chest pain type': 'asymptomatic', #typical angina, atypical angina, non-anginal pain, or asymptomatic
    'Resting blood pressure': 100, #int
    'Cholesterol level': 120, #int
    'Is fasting blood sugar < 120 mg/dl': 'Yes', #Yes or No
    'Resting EKG type': 'normal', #normal, wave abnormality, or ventricular hypertrophy
    'Maximum heart rate': 150, #int
    'Does exercise cause chest pain?': 'No', #Yes or No
    'ST depression induced by exercise': 0, #int
    'Slope type': 'flat', #up, flat, or down
    '# of vessels colored': 0, #float or '?'
    'Thal type': 'normal', #normal, fixed defect, reversible defect, or unknown

Then use your id_tree_classify_point function or tree.print_with_data([test_patient]) to classify the patient.

Important notes:

  • Legal disclaimer: Please do not use this to perform real medical diagnosis. As the questions below will show, there are numerous factors that may cause your ID tree to misclassify patients.
  • If you get an error such as KeyError: '?' when using id_tree_classify_point, it's not a bug in your code; it just means that the ID tree is unable to classify the point. Either define a different patient, or use tree.print_with_data to see why the point is unclassifiable.

Try creating and classifying a few patients. (You can copy/paste the test_patient code into your file to define your own patients.) Are the results consistent with your expectations?

What happens if a female patient has 'Thal type': 'unknown'? What happens if a male patient has 'Thal type': 'unknown'? If you're surprised by the results, examine your tree and data to figure out what caused the results. (You can use tree.print_with_data to print your tree with all the training points.) What could we change to improve the classification accuracy of patients with unknown Thal type?

In the discrete classification tree, what happens if a patient has 'Thal type': 'normal', 'Chest pain type': 'asymptomatic', and '# of vessels colored': '?'? Why does this happen? Why might it cause a problem for classifying real patients? What can we do to fix this problem?

(For answers to the questions in this section, look at the bottom of

Multiple Choice

Questions 1-3: Identification (of) Trees

These questions refer to the data from 2014 Quiz 2, Problem 1, Part A, which is stored in the variables tree_data (the data) and tree_classifiers (a list of Classifiers) in

Question 1: Which of the four classifiers (a.k.a. feature tests) has the lowest disorder? Fill in ANSWER_1 with one of the four classifiers as a string: 'has_leaves', 'leaf_shape', 'orange_foliage', or 'bark_texture'.

Question 2: Which of the four classifiers has the second lowest disorder? Fill in ANSWER_2 with one of the four classifiers as a string.

Question 3: If we start constructing the greedy, disorder-minimizing ID tree, we'll start with the classifier from Question 1. Our one-classifier tree has exactly one non-homogeneous branch. For that branch, which of the four classifiers has the lowest disorder? Fill in ANSWER_3 with one of the four classifiers as a string.

Questions 4-7: XOR

Each training point in the dataset below has three binary features (A, B, C) and a binary classification (0 or 1). Note that the classification happens to be the boolean function XOR(A,B), while feature C is just random noise. The dataset is available in as binary_data, and the three classifiers are stored in the variable binary_classifiers.

Classification A B C
0 0 0 0
0 0 0 1
1 0 1 0
1 0 1 1
1 1 0 1
1 1 0 1
0 1 1 0

Consider the three identification trees below. They are defined in the lab code as binary_tree_n, for n from 1 to 3. To answer the questions below, you may use your code or work out the answers by hand. Image:Lab5_binary_trees.png

Question 4: Which of the trees correctly classify all of the training data? Fill in ANSWER_4 with a list of numbers (e.g. [1,2] if trees 1 and 2 correctly classify the training data but tree 3 does not, or [] if no tree correctly classifies the training data).

Question 5: Which of the trees could be created by the greedy, disorder-minimizing ID tree algorithm? Fill in ANSWER_5 with a list of numbers.

Question 6: For any binary dataset with features A, B, and C, which trees correctly compute the function Classification=XOR(A,B)? Fill in ANSWER_6 with a list of numbers.

Question 7: Based on the principle of Occam's Razor, which tree (among the ones that correctly classify the data) is likely to give the most accurate results when classifying unknown test points? Fill in ANSWER_7 with a single number, as an int.

Questions 8-9: General properties of greedy ID trees

These questions are about ID trees in general and do not refer to any specific trees, data, or classifiers.

Question 8: When constructing an ID tree, in the first round we pick a classifier for the top node, in the second round we pick classifiers for the children nodes, and so on. With this in mind, when constructing a greedy, disorder-minimizing ID tree, is the classifier with the second lowest disorder in the first round always the same as the classifier with the lowest disorder in the second round? (Hint: Consider your answers to Questions 1-3.) Answer 'Yes' or 'No' in ANSWER_8.

Question 9: Will a greedy, disorder-minimizing tree always be the simplest possible tree to correctly classify the data? (Hint: Consider your answers to Questions 4-7.) Answer 'Yes' or 'No' in ANSWER_9.

For explanations of the answers to these questions, search for "#ANSWER_n" in, for the appropriate value of n.

k-Nearest Neighbors

Multiple Choice: Drawing boundaries

Below are sketches of 4 different data sets in Cartesian space, with numerous ways of drawing decision boundaries for each. For each sketch, answer the following question by filling in BOUNDARY_ANS_n (for n from 1 to 14) with an int 1, 2, 3, or 4:

Which method could create the decision boundaries drawn in the sketch?
  1. Greedy, disorder-minimizing ID tree, using only tests of the form "X > threshold" or "Y > threshold"
  2. 1-nearest neighbors using Euclidean distance
  3. Both
  4. Neither


For explanations of the answers to some of these questions, search for "#BOUNDARY_ANS_n" in, for the appropriate value of n.

Python warm-up: Distance metrics

We can use many different distance metrics with k-nearest neighbors. In 6.034, we cover four such metrics:

  • Euclidean distance: the straight-line distance between two points.
  • Manhattan distance: the distance between two points assuming you can only move parallel to axes. In two dimensions, you can conceptualize this as only being able to move along the "grid lines."
  • Hamming distance: the number of differing corresponding components between two vectors.
  • Cosine distance: compares the angle between two vectors, where each point is represented as a vector from the origin to the point's coordinates. Note that cosine is a similarity measure, not a difference measure, because cos(0)=1 means two vectors are "perfectly similar," cos(90 deg)=0 represents two "perfectly orthogonal" vectors, and cos(180 deg)=-1 corresponds to two "maximally dissimilar" (or "perfectly opposite") vectors. For our code, however, we need this metric to be a difference measure so that smaller distances means two vectors are "more similar," to match all of the other distance metrics. Accordingly, we will define the cosine distance to be 1 minus the cosine of the angle between two vectors, so that our cosine distance varies between 0 (perfectly similar) and 2 (maximally dissimilar). Thus, the formula for cosine distance is:

It's also possible to transform data instead of using a different metric -- for instance, transforming to polar coordinates -- but in this lab we will only work with distance metrics in Cartesian coordinates.

We'll start with some basic functions for manipulating vectors, which may be useful for cosine_distance. For these, we will represent an n-dimensional vector as a list or tuple of n coordinates. dot_product should compute the dot product of two vectors, while norm computes the length of a vector. (There is a simple implementation of norm that uses dot_product.) Implement both functions:

def dot_product(u, v):
def norm(v):

Next, you'll implement each of the four distance metrics. For the rest of the k-nearest neighbors portion of this lab, we will represent data points as Point objects (described below in the API). Because Point objects are iterable (e.g. you can do for coord in point:), you should be able to call your vector methods on them directly. Each distance function should take in two Points and return the distance between them as a float or int. Implement each distance function:

def euclidean_distance(point1, point2):
def manhattan_distance(point1, point2):
def hamming_distance(point1, point2):
def cosine_distance(point1, point2):

Python hint: The built-in Python keyword zip may be useful. To learn more, type help(zip) in a Python command line, or read about it online.

Classifying Points with k-Nearest Neighbors

Now that we have defined four distance metrics, we will use them to classify points using k-nearest neighbors with various values of k.

First, write a function get_k_closest_points that takes in a point (a Point object), some data (a list of Point objects), a number k, and a distance metric (a function, such as euclidean_distance), and returns the k points in the data that are nearest to the input point, according to the distance metric. Break ties lexicographically using the points' coordinates (i.e. in case of a tie, sort by point.coords). This function can be written cleanly in 5 lines or less.

def get_k_closest_points(point, data, k, distance_metric):

A note about ties: There are two ways to get ties when classifying points using k-nearest neighbors.

  1. If two or more training points are equidistant to the test point, the "k nearest" points may be undefined. If the equidistant points have the same classification, it doesn't make a difference, but in some cases they could cause the classification to be ambiguous. In this lab, these cases are handled in get_k_closest_points by breaking ties lexicographically.
  2. If the two most likely classifications are equally represented among the k nearest training points, the classification is ambiguous. In other words, the k-nearest neighbors are voting on a classification, and if the vote is tied, there needs to be some mechanism for breaking the tie. In this lab, we will assume that there are no voting ties, so you don't need to worry about tie-breaking. (All of the test cases in this section are designed to ensure that there will not be any voting ties.)

Your task is to use that to write a function that classifies a point, given a set of data (as a list of Points), a value of k, and a distance metric (a function):

def knn_classify_point(point, data, k, distance_metric):

Python hint: To get the mode of a list, there's a neat one-line trick using max with the key argument, the list.count function, and converting a list to a set to get the unique elements. .count is a built-in list method that counts how many times an item occurs in a list. For example, [10, 20, 20, 30].count(20) -> 2.

Cross-validation: Choosing the best k and distance metric

There are many possible implementations of cross validation, but the general idea is to separate your data into a training set and a test set, then use the test set to determine how well the training parameters worked. For k-nearest neighbors, this means choosing a value of k and a distance metric, then testing each point in the test set to see whether they are classified correctly. The "cross" part of cross-validation comes from the idea that you can re-separate your data multiple times, so that different subsets of the data take turns being in the training and test sets, respectively.

For the next function, you'll implement a specific type of cross-validation known as leave-one-out cross-validation. If there are n points in the data set, you'll separate the data n times into a training set of size n-1 (all the points except one) and a test set of size one (the one point being left out). Implement the function cross_validate, which takes in a set of data, a value of k, and a distance metric, and returns the fraction of points that were classified correctly using leave-one-out cross-validation.

def cross_validate(data, k, distance_metric):

Use your cross-validation method to write a function that takes in some data (a list of Points) and tries every combination of reasonable values of k and the four distance metrics we defined above, then returns a tuple (k, distance_metric) representing the value of k and the distance metric that produce the best results with cross validation:

def find_best_k_and_metric(data):

More Multiple Choice

kNN Questions 1-3: More tree classification

These questions refer to the k-nearest neighbors data on classifying trees, from 2014 Quiz 2, Part B.

Recall the following terms:

  • Overfitting: Occurs when small amounts of noise in the training data are treated as meaningful trends in the population. (i.e. when relying too heavily on the data, or overutilizing the data, causes a poor classification rate)
  • Underfitting: Occurs when the algorithm blurs out differences in the training data that reflect genuine trends in the population. (i.e. when ignoring information in the data, or underutilizing the data, causes a poor classification rate)

kNN Question 1: Consider the results of cross-validation using k=1 and the Euclidean distance metric. Why is 1 not a good value for k? Answer "Overfitting" or "Underfitting" in kNN_ANSWER_1.

kNN Question 2: Consider the results of cross-validation using k=7 and the Euclidean distance metric. Why is 7 not a good value for k? Answer "Overfitting" or "Underfitting" in kNN_ANSWER_2.

kNN Question 3: Euclidean distance doesn't seem to do very well with any value of k (for this data). Which distance metric yields the highest classification rate for this dataset? Answer 1, 2, 3, or 4 in kNN_ANSWER_3:

  1. Euclidean distance
  2. Manhattan distance
  3. Hamming distance
  4. Cosine distance

kNN Questions 4-7: Choosing metrics

kNN Question 4: Suppose you wanted to classify a mysterious drink as coffee, energy drink, or soda based on the amount of caffeine and amount of sugar per 1-cup serving. Coffee typically contains a large amount of caffeine, lemonade typically contains a large amount of sugar, and energy drinks typically contain a large amount of both. Which distance metric would work best, and why? Answer 1, 2, 3, or 4 in kNN_ANSWER_4:

  1. Euclidean distance, because you're comparing standard numeric quantities
  2. Manhattan distance, because it makes sense to array the training data points in a grid
  3. Hamming distance, because the features "contains caffeine" and "contains sugar" are boolean values
  4. Cosine distance, because you care more about the ratio of caffeine to sugar than the actual amount

kNN Question 5: Suppose you add a fourth possible classification, water, which contains no caffeine or sugar. Now which distance metric would work best, and why? Answer 1, 2, 3, or 4 in kNN_ANSWER_5:

  1. Euclidean distance, because you're still comparing standard numeric quantities, and it's now more difficult to compare ratios
  2. Manhattan distance, because there are now four points, so it makes even more sense to array them in a grid
  3. Hamming distance, because the features "contains caffeine" and "contains sugar" are still boolean values
  4. Cosine distance, because you still care more about the ratio of caffeine to sugar than the actual amount

kNN Question 6: While visiting Manhattan, you discover that there are 3 different types of taxis, each of which has a distinctive logo. Each type of taxi comes in many makes and models of cars. Which distance metric would work best for classifying additional taxis based on their logos, makes, and models? Answer 1, 2, 3, or 4 in kNN_ANSWER_6:

  1. Euclidean distance, because there's a lot of variability in make and model
  2. Manhattan distance, because the streets meet at right angles (and because you're in Manhattan and classifying taxicabs)
  3. Hamming distance, because the features are non-numeric
  4. Cosine distance, because it will separate taxis by how different their makes and models are

kNN Question 7: Why might an ID tree work better for classifying the taxis from Question 6? Answer 1, 2, 3, or 4 in kNN_ANSWER_7:

  1. k-nearest neighbors requires data to be graphed on a coordinate system, but the training data isn't quantitative
  2. Some taxis may have the same make and model, and k-nearest neighbors can't handle identical training points
  3. An ID tree can ignore irrelevant features, such as make and model
  4. Taxis aren't guaranteed to stay within their neighborhood in Manhattan

For explanations of the answers to some of these questions, search for "#kNN_ANSWER_n" in, for the appropriate value of n.


Please answer these questions at the bottom of your file:

  • NAME: What is your name? (string)
  • COLLABORATORS: Other than 6.034 staff, with whom did you work on this lab? (string, or empty string if you worked alone)
  • HOW_MANY_HOURS_THIS_LAB_TOOK: Approximately how many hours did you spend on this lab? (number or string)
  • WHAT_I_FOUND_INTERESTING: Which parts of this lab, if any, did you find interesting? (string)
  • WHAT_I_FOUND_BORING: Which parts of this lab, if any, did you find boring or tedious? (string)
  • (optional) SUGGESTIONS: What specific changes would you recommend, if any, to improve this lab for future years? (string)

(We'd ask which parts you find confusing, but if you're confused you should really ask a TA.)

When you're done, run the online tester to submit your code. Note that if you downloaded the Lab 5 files before the morning of Tuesday October 11, you will need to git pull or download a new

API Reference Documentation

The file defines the Classifier, IdentificationTreeNode, and Point classes, as well as some helper functions for creating Classifiers, all described below.


Classifier objects are used for constructing and manipulating ID trees.

A Classifier has one attribute and one method:

  •, the name of the classifier.
  • classifier.classify(point), which takes in a point and returns its classification. (A classification can be a string (e.g. "Vampire"), a boolean value (True or False) or an int.)

In our ID trees, a point is represented as a dict mapping feature names to their values. For example:

point = {"X": 1, "Y": 2, "Zombie": True}

You can create new Classifiers using these provided methods:

  • feature_test(key): Takes in the name of a feature (such as "X" or "Accent" or "Height"). Returns a new Classifier that classifies based on the value of that feature.
  • threshold_test(key, threshold): Takes in the name of a numeric feature and a threshold value. Returns a new binary Classifier that performs the test point[key] > threshold and returns "Yes" or "No" for each point.

For example:

feature_test_X = feature_test("X")
feature_test_X_threshold = threshold_test("X", 6)

Or you can create your own Classifier using the Classifier constructor, for example:

feature_test_vector_length = Classifier("vector_length", lambda pt: (pt.get("X")**2 + pt.get("Y")**2)**0.5)


In this lab, an ID tree is represented recursively as a tree of IdentificationTreeNode objects. In particular, an IdentificationTreeNode object fully represents an entire ID tree rooted at that node.

For example, suppose we have an IdentificationTreeNode called id_tree_node Then, id_tree_node's children are themselves IdentificationTreeNode objects, each fully describing the sub-trees of id_tree_node. However, if id_tree_node has no children, then id_tree_node is a leaf, meaning that it represents a homogeneous (by classification) set of data points. Furthermore, any datum at this node is definitively classified by that leaf's classification.

As such, in a completed ID tree, each node is either

  • a leaf node with a classification such as "Vampire" or "Not Vampire" in the vampires example; or
  • a non-leaf node with a classifier (such as "Accent" in the vampires example), with branches (one per classifier result, e.g. "Heavy", "Odd", and "None") leading to child nodes.

An IdentificationTreeNode has the following attributes and methods:

  • id_tree_node.target_classifier, the single Classifier by which the tree classifies points (e.g. a Classifier representing "Vampire?" for the vampires example, or "Classification" for the angel data).
  • id_tree_node.get_parent_branch_name(): returns the name of the branch leading to this node, or None if this is a root node.
  • id_tree_node.is_leaf(): returns True if the node is a leaf (has a classification), otherwise False.
  • id_tree_node.set_node_classification(classification): Sets this node's classification, thus defining this node as a leaf node. Modifies and returns the original id_tree_node. May print warnings if the node already has branches defined.
  • id_tree_node.get_node_classification(): returns this node's classification, if it has one. Otherwise, returns None.
  • id_tree_node.set_classifier_and_expand(classifier, features): Takes in a Classifier object and a list of features (e.g. ["Heavy", "Odd", "None"]), then uses the Classifier and list of features to set the current node's classifier and add branches below the current node, instantiating a new child node for each branch. Modifies and returns the original id_tree_node. May print warnings if the specified Classifier is inadvisable. (For your convenience, features can also be a dictionary whose keys are feature names.)
  • id_tree_node.get_classifier(): returns the classifier associated with this node, if it has one. Otherwise, returns None.
  • id_tree_node.apply_classifier(point): Applies this node's classifier to a given data point by following the appropriate branch of the tree, then returns the child node. If this node is a leaf node (and thus doesn't have a classifier), raises a ClassifierError.
  • id_tree_node.get_branches(): returns a dictionary mapping this node's branch names to its child nodes (e.g. {'Heavy':<IdentificationTreeNode object>, 'Odd': <IdentificationTreeNode object>, 'None': <IdentificationTreeNode object>})
  • id_tree_node.copy(): Returns a (deep) copy of the node
  • id_tree_node.print_with_data(data): Given a list of points, automatically classifies each point and prints a graphical representation of the ID tree with each point at the appropriate node.

The constructor for instantiating a new IdentificationTreeNode requires 1-2 arguments:

  • target_classifier: The Classifier by which the overall tree should classify points
  • parent_branch_name (optional): The name of the branch leading into this node, if the node is not the root node.

For example:

vampire_tree_root_node = IdentificationTreeNode(feature_test("Vampire?"))
another_node = IdentificationTreeNode(feature_test("Vampire?"), "Odd")

Point (for kNN)

Point objects are used in the k-nearest neighbors section only.

The Point class supports iteration (to iterate through the coordinates).

A Point has the following attributes:

  •, the name of the point (a string), if defined.
  • point.coords, the coordinates of the point, represented as a vector (a tuple or list of numbers).
  • point.classification, the classification of the point, if known.


How to handle exceptions

(using NoGoodClassifiersError as an example)

Python command Effect
raise NoGoodClassifiersError("message") Stops execution by raising, or throwing, a NoGoodClassifiersError with the specified error message
    #code here
Defines the beginning of a block of code that might raise an exception
except NoGoodClassifiersError:
    #code here
Follows a try block. Defines what to do if a NoGoodClassifiersError was raised in the try block.
Personal tools