Skip to content
Snippets Groups Projects
Commit eb5d718d authored by Zeynep Hakguder's avatar Zeynep Hakguder
Browse files

Update ProgrammingAssignment1.ipynb

parent 98dcbe39
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# *k*-Nearest Neighbor # *k*-Nearest Neighbor
We'll implement *k*-Nearest Neighbor (*k*-NN) algorithm for this assignment. We will use the **madelon** dataset as in Programming Assignment 0. We'll implement *k*-Nearest Neighbor (*k*-NN) algorithm for this assignment. We will use the **madelon** dataset as in Programming Assignment 0.
A skeleton of a general supervised learning model is provided in "model.ipynb". The functions that will be implemented there will be indicated in this notebook. A skeleton of a general supervised learning model is provided in "model.ipynb". The functions that will be implemented there will be indicated in this notebook.
### Assignment Goals: ### Assignment Goals:
In this assignment, we will: In this assignment, we will:
* implement 'Euclidean' and 'Manhattan' distance metrics * implement 'Euclidean' and 'Manhattan' distance metrics
* use the validation dataset to find a good value for *k* * use the validation dataset to find a good value for *k*
* evaluate our model with respect to performance measures: * evaluate our model with respect to performance measures:
* accuracy, generalization error * accuracy, generalization error
* confusion matrix * confusion matrix
* Receiver Operating Characteristic (ROC) curve * Receiver Operating Characteristic (ROC) curve
* try to assess if *k*-NN is suitable for the dataset you used * try to assess if *k*-NN is suitable for the dataset you used
## Note: ## Note:
You are not required to follow this exact template. You can change what parameters your functions take or partition the tasks across functions differently. However, make sure there are outputs and implementation for items listed in the rubric for each task. Also, indicate in code with comments which task you are attempting. You are not required to follow this exact template. You can change what parameters your functions take or partition the tasks across functions differently. However, make sure there are outputs and implementation for items listed in the rubric for each task. Also, indicate in code with comments which task you are attempting.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# GRADING # GRADING
You will be graded on parts that are marked with **TODO** comments. Read the comments in the code to make sure you don't miss any. You will be graded on parts that are marked with **TODO** comments. Read the comments in the code to make sure you don't miss any.
### Mandatory for 478 & 878: ### Mandatory for 478 & 878:
| | Tasks | 478 | 878 | | | Tasks | 478 | 878 |
|---|----------------------------|-----|-----| |---|----------------------------|-----|-----|
| 1 | Implement `distance` | 15 | 15 | | 1 | Implement `distance` | 15 | 15 |
| 2 | Implement `k-NN` methods | 35 | 30 | | 2 | Implement `k-NN` methods | 35 | 30 |
| 3 | Model evaluation | 25 | 20 | | 3 | Model evaluation | 25 | 20 |
| 5 | ROC curve analysis | 25 | 25 | | 5 | ROC curve analysis | 25 | 25 |
### Mandatory for 878, bonus for 478 ### Mandatory for 878, bonus for 478
| | Tasks | 478 | 878 | | | Tasks | 478 | 878 |
|---|----------------|-----|-----| |---|----------------|-----|-----|
| 4 | Optimizing *k* | 10 | 10 | | 4 | Optimizing *k* | 10 | 10 |
### Bonus for 478/878 ### Bonus for 478/878
| | Tasks | 478 | 878 | | | Tasks | 478 | 878 |
|---|----------------|-----|-----| |---|----------------|-----|-----|
| 6 | Assess suitability of *k*-NN | 10 | 10 | | 6 | Assess suitability of *k*-NN | 10 | 10 |
Points are broken down further below in Rubric sections. The **first** score is for 478, the **second** is for 878 students. There are a total of 100 points in this assignment and extra 20 bonus points for 478 students and 10 bonus points for 878 students. Points are broken down further below in Rubric sections. The **first** score is for 478, the **second** is for 878 students. There are a total of 100 points in this assignment and extra 20 bonus points for 478 students and 10 bonus points for 878 students.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# YOUR GRADE # YOUR GRADE
### Group Members: ### Group Members:
| | Tasks | Points | | | Tasks | Points |
|---|----------------------------|-----| |---|----------------------------|-----|
| 1 | Implement `distance` | | | 1 | Implement `distance` | |
| 2 | Implement `k-NN` methods | | | 2 | Implement `k-NN` methods | |
| 3 | Model evaluation | | | 3 | Model evaluation | |
| 4 | Optimizing *k* | | | 4 | Optimizing *k* | |
| 5 | ROC curve analysis | | | 5 | ROC curve analysis | |
| 6 | Assess suitability of *k*-NN| | | 6 | Assess suitability of *k*-NN| |
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
You can use numpy for array operations and matplotlib for plotting for this assignment. Please do not add other libraries. You can use numpy for array operations and matplotlib for plotting for this assignment. Please do not add other libraries.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Following code makes the Model class and relevant functions available from model.ipynb. Following code makes the Model class and relevant functions available from model.ipynb.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%run 'model.ipynb' %run 'model.ipynb'
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## TASK 1: Implement `distance` function ## TASK 1: Implement `distance` function
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Choice of distance metric plays an important role in the performance of *k*-NN. Let's start with implementing a distance method in the "distance" function in **model.ipynb**. It should take two data points and the name of the metric and return a scalar value. Choice of distance metric plays an important role in the performance of *k*-NN. Let's start with implementing a distance method in the "distance" function in **model.ipynb**. It should take two data points and the name of the metric and return a scalar value.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Rubric: ### Rubric:
* Euclidean +7.5, +7.5 * Euclidean +7.5, +7.5
* Manhattan +7.5, +7.5 * Manhattan +7.5, +7.5
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Test `distance` ### Test `distance`
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
x = np.array(range(100)) x = np.array(range(100))
y = np.array(range(100, 200)) y = np.array(range(100, 200))
dist_euclidean = distance(x, y, 'Euclidean') dist_euclidean = distance(x, y, 'Euclidean')
dist_manhattan = distance(x, y, 'Manhattan') dist_manhattan = distance(x, y, 'Manhattan')
print('Euclidean distance: {}, Manhattan distance: {}'.format(dist_euclidean, dist_manhattan)) print('Euclidean distance: {}, Manhattan distance: {}'.format(dist_euclidean, dist_manhattan))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## TASK 2: Implement *k*-NN Class Methods ## TASK 2: Implement *k*-NN Class Methods
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We can start implementing our *k*-NN classifier. *k*-NN class inherits Model class. Use the "distance" function you defined above. "fit" method takes *k* as an argument. "predict" takes as input an *mxd* array containing *d*-dimensional *m* feature vectors for examples and for each input point outputs the predicted class and the ratio of positive examples in *k* nearest neighbors. We can start implementing our *k*-NN classifier. *k*-NN class inherits Model class. Use the "distance" function you defined above. "fit" method takes *k* as an argument. "predict" takes as input an *mxd* array containing *d*-dimensional *m* feature vectors for examples and for each input point outputs the predicted class and the ratio of positive examples in *k* nearest neighbors.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Rubric: ### Rubric:
* correct implementation of fit method +10, +10 * correct implementation of fit method +10, +10
* correct implementation of predict method +25, +20 * correct implementation of predict method +25, +20
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
class kNN(Model): class kNN(Model):
''' '''
Inherits Model class. Implements the k-NN algorithm for classification. Inherits Model class. Implements the k-NN algorithm for classification.
''' '''
def fit(self, training_features, training_labels, classes, k, distance_f,**kwargs): def fit(self, training_features, training_labels, classes, k, distance_f,**kwargs):
''' '''
Fit the model. This is pretty straightforward for k-NN. Fit the model. This is pretty straightforward for k-NN.
Args: Args:
training_features: ndarray training_features: ndarray
training_labels: ndarray training_labels: ndarray
classes: ndarray classes: ndarray
1D array containing unique classes in the dataset 1D array containing unique classes in the dataset
k: int k: int
distance_f: function distance_f: function
kwargs: dict kwargs: dict
Contains keyword arguments that will be passed to distance_f Contains keyword arguments that will be passed to distance_f
''' '''
# TODO # TODO
# set self.train_features, self.train_labels, self.classes, self.k, self.distance_f, self.distance_metric # set self.train_features, self.train_labels, self.classes, self.k, self.distance_f, self.distance_metric
raise NotImplementedError raise NotImplementedError
return return
def predict(self, test_features): def predict(self, test_features):
''' '''
Args: Args:
test_features: ndarray test_features: ndarray
mxd array containing features for the points to be predicted mxd array containing features for the points to be predicted
Returns: Returns:
preds: ndarray preds: ndarray
mx2 array containing predicted class and proportion for each test point mx2 array containing predicted class and proportion for each test point
''' '''
raise NotImplementedError raise NotImplementedError
# TODO # TODO
# for each point in test_features # for each point in test_features
# use your implementation of distance function # use your implementation of distance function
# distance_f(..., distance_metric) # distance_f(..., distance_metric)
# to find the labels of k-nearest neighbors. # to find the labels of k-nearest neighbors.
# you'll need proportion of the dominant class # you'll need proportion of the dominant class
# in k nearest neighbors # in k nearest neighbors
return preds return preds
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## TASK 3: Build and Evaluate the Model ## TASK 3: Build and Evaluate the Model
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Rubric: ### Rubric:
* Reasonable accuracy values +10, +5 * Reasonable accuracy values +10, +5
* Reasonable confidence intervals on the error estimate +10, +10 * Reasonable confidence intervals on the error estimate +10, +10
* Reasonable confusion matrix +5, +5 * Reasonable confusion matrix +5, +5
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Preprocess the data files and partition the data. Preprocess the data files and partition the data.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# initialize the model # initialize the model
my_model = kNN() my_model = kNN()
# obtain features and labels from files # obtain features and labels from files
features, labels = preprocess(feature_file=..., label_file=...) features, labels = preprocess(feature_file=..., label_file=...)
# get class names (unique entries in labels) # get class names (unique entries in labels)
classes = np.unique(labels) classes = np.unique(labels)
# partition the data set # partition the data set
val_indices, test_indices, train_indices = partition(size=..., t = 0.3, v = 0.1) val_indices, test_indices, train_indices = partition(size=..., t = 0.3, v = 0.1)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Assign a value to *k* and fit the *k*-NN model. Assign a value to *k* and fit the *k*-NN model.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# pass the training features and labels to the fit method # pass the training features and labels to the fit method
kwargs_f = {'metric': 'Euclidean'} kwargs_f = {'metric': 'Euclidean'}
my_model.fit(training_features=..., training_labels-..., classes, k=10, distance_f=..., **kwargs_f) my_model.fit(training_features=..., training_labels-..., classes, k=10, distance_f=..., **kwargs_f)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Computing the confusion matrix for *k* = 10 ### Computing the confusion matrix for *k* = 10
Now that we have the true labels and the predicted ones from our model, we can build a confusion matrix and see how accurate our model is. Implement the "conf_matrix" function (in model.ipynb) that takes as input an array of true labels (*true*) and an array of predicted labels (*pred*). It should output a numpy.ndarray. You do not need to change the value of the threshold parameter yet. Now that we have the true labels and the predicted ones from our model, we can build a confusion matrix and see how accurate our model is. Implement the "conf_matrix" function (in model.ipynb) that takes as input an array of true labels (*true*) and an array of predicted labels (*pred*). It should output a numpy.ndarray. You do not need to change the value of the threshold parameter yet.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# TODO # TODO
# get model predictions # get model predictions
pred_ratios = my_model.predict(features[test_indices]) pred_ratios = my_model.predict(features[test_indices])
# For now, we will consider a data point as predicted in a class if more than 0.5 # For now, we will consider a data point as predicted in a class if more than 0.5
# of its k-neighbors are in that class. # of its k-neighbors are in that class.
threshold = 0.5 threshold = 0.5
# convert predicted ratios to predicted labels # convert predicted ratios to predicted labels
pred_labels = None pred_labels = None
# show the distribution of predicted and true labels in a confusion matrix # show the distribution of predicted and true labels in a confusion matrix
confusion = conf_matrix(...) confusion = conf_matrix(...)
confusion confusion
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Evaluate your model on the test data and report your **accuracy**. Also, calculate and report the 95% confidence interval on the generalization **error** estimate. Evaluate your model on the test data and report your **accuracy**. Also, calculate and report the 95% confidence interval on the generalization **error** estimate.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# TODO # TODO
# Calculate and report accuracy and generalization error with confidence interval here. Show your work in this cell. # Calculate and report accuracy and generalization error with confidence interval here. Show your work in this cell.
print('Accuracy: {}'.format(accuracy)) print('Accuracy: {}'.format(accuracy))
print('Confidence interval: {}-{}'.format(lower_bound, upper_bound)) print('Confidence interval: {}-{}'.format(lower_bound, upper_bound))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## TASK 4: Determining *k* ## TASK 4: Determining *k*
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Rubric: ### Rubric:
* Accuracies reported with various *k* values +5, +5 * Accuracies reported with various *k* values +5, +5
* Confusion matrix for new *k* +5, +5 * Confusion matrix for new *k* +5, +5
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We can use the validation set to come up with a *k* value that results in better performance in terms of accuracy. We can use the validation set to come up with a *k* value that results in better performance in terms of accuracy.
Below calculate the accuracies for different values of *k* using the validation set. Report a good *k* value and use it in the analyses that follow this section. Report confusion matrix for the new value of *k*. Below calculate the accuracies for different values of *k* using the validation set. Report a good *k* value and use it in the analyses that follow this section. Report confusion matrix for the new value of *k*.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# TODO # TODO
# Change values of k. # Change values of k.
# Calculate accuracies for the validation set. # Calculate accuracies for the validation set.
# Report a good k value. # Report a good k value.
# Calculate the confusion matrix for new k. # Calculate the confusion matrix for new k.
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## TASK 5: ROC curve analysis ## TASK 5: ROC curve analysis
* Correct implementation +25, +25 * Correct implementation +25, +25
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
ROC curves are a good way to visualize sensitivity vs. 1-specificity for varying cut off points. Now, implement, in **model.ipynb**, a "ROC" function. "ROC" takes a list containing different threshold values to try and returns two arrays; one where each entry is the sensitivity at a given threshold and the other where entries are 1-specificities. ROC curves are a good way to visualize sensitivity vs. 1-specificity for varying cut off points. Now, implement, in **model.ipynb**, a "ROC" function. "ROC" takes a list containing different threshold values to try and returns two arrays; one where each entry is the sensitivity at a given threshold and the other where entries are 1-specificities.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Use the *k* value you found above, if you completed TASK 4, else use *k* = 10 to plot the ROC curve for values between 0.1 and 1.0. Use the *k* value you found above, if you completed TASK 4, else use *k* = 10 to plot the ROC curve for values between 0.1 and 1.0.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# TODO # TODO
# ROC curve # ROC curve
roc_sens, roc_spec_ = ROC(true_labels=..., preds=..., np.arange(0.1, 1.0, 0.1)) roc_sens, roc_spec_ = ROC(true_labels=..., preds=..., np.arange(0.1, 1.0, 0.1))
plt.plot(roc_sens, roc_spec_) plt.plot(roc_sens, roc_spec_)
plt.show() plt.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## TASK 6: Assess suitability of *k*-NN to your dataset ## TASK 6: Assess suitability of *k*-NN to your dataset
* +10, +10 * +10, +10
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Use the cell below to write about your understanding of why *k*-NN performed well if it did or why not if it didn't. What properties of the dataset could have affected the performance of the algorithm? Insert a cell below to write about your understanding of why *k*-NN performed well if it did or why not if it didn't. What properties of the dataset could have affected the performance of the algorithm?
%% Cell type:markdown id: tags:
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment