"We'll implement $k$-Nearest Neighbor ($k$-NN) algorithm for this assignment. A skeleton of a general supervised learning model is provided in \"model.ipynb\". Please look through it and complete the \"preprocess\" and \"partition\" methods.\n",
"We'll implement $k$-Nearest Neighbor ($k$-NN) algorithm for this assignment. We recommend using [Madelon](https://archive.ics.uci.edu/ml/datasets/Madelon) dataset, although it is not mandatory. If you choose to use a different dataset, it should meet the following criteria:\n",
"* dependent variable should be binary (suited for binary classification)\n",
"* number of features (attributes) should be at least 50\n",
"* number of examples (instances) should be at least 1,000\n",
"\n",
"A skeleton of a general supervised learning model is provided in \"model.ipynb\". Please look through it and complete the \"preprocess\" and \"partition\" methods. \n",
"\n",
"\n",
"### Assignment Goals:\n",
"### Assignment Goals:\n",
"In this assignment, we will:\n",
"In this assignment, we will:\n",
...
@@ -53,7 +58,7 @@
...
@@ -53,7 +58,7 @@
"cell_type": "markdown",
"cell_type": "markdown",
"metadata": {},
"metadata": {},
"source": [
"source": [
"Choice of distance metric plays an important role in the performance of $k$-NN. Let's start by implementing a distance method in the \"distance\" function below. 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 below. It should take two data points and the name of the metric and return a scalar value."
]
]
},
},
{
{
...
@@ -84,7 +89,7 @@
...
@@ -84,7 +89,7 @@
"cell_type": "markdown",
"cell_type": "markdown",
"metadata": {},
"metadata": {},
"source": [
"source": [
"We can start implementing our $k$-NN classifier. $k$-NN class inherits Model class. You'll need to implement \"fit\" and \"predict\" methods. Use the \"distance\" function you defined above. \"fit\" method takes $k$ as an argument. \"predict\" takes as input the feature vector for a single test point and outputs the predicted class and the proportion of predicted class labels in $k$ nearest neighbors."
"We can start implementing our $k$-NN classifier. $k$-NN class inherits Model class. You'll need to implement \"fit\" and \"predict\" methods. 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 outputs the predicted class and the proportion of predicted class labels in $k$ nearest neighbors."
]
]
},
},
{
{
...
@@ -97,32 +102,32 @@
...
@@ -97,32 +102,32 @@
" '''\n",
" '''\n",
" Inherits Model class. Implements the k-NN algorithm for classification.\n",
" Inherits Model class. Implements the k-NN algorithm for classification.\n",
"Use \"predict_batch\" function above to report your model's accuracy on the test set. Also, calculate and report the confidence interval on the generalization error estimate."
"Evaluate your model on the test data and report your accuracy. Also, calculate and report the confidence interval on the generalization error estimate."
"# Calculate accuracy and generalization error with confidence interval here."
"# Calculate accuracy and generalization error with confidence interval here."
]
]
},
},
...
@@ -220,9 +195,9 @@
...
@@ -220,9 +195,9 @@
"cell_type": "markdown",
"cell_type": "markdown",
"metadata": {},
"metadata": {},
"source": [
"source": [
"# TODO: leaa \n",
"# TODO: learning curve \n",
"\n",
"\n",
"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 that takes as input an array of true labels ($true$) and an array of predicted labels ($pred$). It should output a numpy.ndarray. "
"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."
]
]
},
},
{
{
...
@@ -231,14 +206,8 @@
...
@@ -231,14 +206,8 @@
"metadata": {},
"metadata": {},
"outputs": [],
"outputs": [],
"source": [
"source": [
"def conf_matrix(true, pred):\n",
"# You should see array([ 196, 106, 193, 105]) with seed 123\n",
" pred: nx1 array of predicted labels for test set\n",
" '''\n",
" raise NotImplementedError\n",
" # returns the confusion matrix as numpy.ndarray\n",
" return c_mat"
]
]
},
},
{
{
...
@@ -259,7 +228,7 @@
...
@@ -259,7 +228,7 @@
"outputs": [],
"outputs": [],
"source": [
"source": [
"# Change values of $k. \n",
"# Change values of $k. \n",
"# Calculate accuracies and confusion matrices for the validation set.\n",
"# Calculate accuracies for the validation set.\n",
"# Report a good k value that you'll use in the following analyses."
"# Report a good k value that you'll use in the following analyses."
]
]
},
},
...
...
%% 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. A skeleton of a general supervised learning model is provided in "model.ipynb". Please look through it and complete the "preprocess" and "partition" methods.
We'll implement $k$-Nearest Neighbor ($k$-NN) algorithm for this assignment. We recommend using [Madelon](https://archive.ics.uci.edu/ml/datasets/Madelon) dataset, although it is not mandatory. If you choose to use a different dataset, it should meet the following criteria:
* dependent variable should be binary (suited for binary classification)
* number of features (attributes) should be at least 50
* number of examples (instances) should be at least 1,000
A skeleton of a general supervised learning model is provided in "model.ipynb". Please look through it and complete the "preprocess" and "partition" methods.
### Assignment Goals:
### Assignment Goals:
In this assignment, we will:
In this assignment, we will:
* learn to split a dataset into training/validation/test partitions
* learn to split a dataset into training/validation/test partitions
* use the validation dataset to find a good value for $k$
* use the validation dataset to find a good value for $k$
* Having found the "best" $k$, we'll obtain final performance measures:
* Having found the "best" $k$, we'll obtain final performance measures:
* accuracy, generalization error and ROC curve
* accuracy, generalization error and ROC curve
%% 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
importnumpyasnp
importnumpyasnp
importmatplotlib.pyplotasplt
importmatplotlib.pyplotasplt
```
```
%% 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:
Choice of distance metric plays an important role in the performance of $k$-NN. Let's start by implementing a distance method in the "distance" function below. 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 below. It should take two data points and the name of the metric and return a scalar value.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defdistance(x,y,metric):
defdistance(x,y,metric):
'''
'''
x: a 1xd array
x: a 1xd array
y: a 1xd array
y: a 1xd array
metric: Euclidean, Hamming, etc.
metric: Euclidean, Hamming, etc.
'''
'''
raiseNotImplementedError
raiseNotImplementedError
returndist# scalar distance btw x and y
returndist# scalar distance btw x and y
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### $k$-NN Class Methods
### $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. You'll need to implement "fit" and "predict" methods. Use the "distance" function you defined above. "fit" method takes $k$ as an argument. "predict" takes as input the feature vector for a single test point and outputs the predicted class and the proportion of predicted class labels in $k$ nearest neighbors.
We can start implementing our $k$-NN classifier. $k$-NN class inherits Model class. You'll need to implement "fit" and "predict" methods. 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 outputs the predicted class and the proportion of predicted class labels in $k$ nearest neighbors.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
classkNN(Model):
classkNN(Model):
'''
'''
Inherits Model class. Implements the k-NN algorithm for classification.
Inherits Model class. Implements the k-NN algorithm for classification.
Fit the model. This is pretty straightforward for k-NN.
Fit the model. This is pretty straightforward for k-NN.
'''
'''
# set self.k, self.distance_f, self.distance_metric
raiseNotImplementedError
raiseNotImplementedError
return
return
defpredict(self,test_point):
defpredict(self,test_indices):
raiseNotImplementedError
raiseNotImplementedError
pred=[]
# for each point in test points
# use your implementation of distance function
# distance_f(..., distance_metric)
# to find the labels of k-nearest neighbors.
# Find the ratio of the positive labels
# and append to pred with pred.append(ratio).
# use self.distance_f(...,self.distance_metric)
# return the predicted class label and the following ratio:
returnnp.array(pred)
# number of points that have the same label as the test point / k
returnpredicted_label,ratio
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### Build and Evaluate the Model (Accuracy, Confidence Interval, Confusion Matrix)
### Build and Evaluate the Model (Accuracy, Confidence Interval, Confusion Matrix)
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
It's time to build and evaluate our model now. Remember you need to provide values to $p$, $v$ parameters for "partition" function and to $file\_path$ for "preprocess" function.
It's time to build and evaluate our model now. Remember you need to provide values to $p$, $v$ parameters for "partition" function and to $file\_path$ for "preprocess" function.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# populate the keyword arguments dictionary kwargs
# populate the keyword arguments dictionary kwargs
You can use "predict_batch" function below to evaluate your model on the test data. You do not need to change the value of the threshold yet.
Evaluate your model on the test data and report your accuracy. Also, calculate and report the confidence interval on the generalization error estimate.
Use "predict_batch" function above to report your model's accuracy on the test set. Also, calculate and report the confidence interval on the generalization error estimate.
%% Cell type:code id: tags:
``` python
predict_batch(my_model,my_model.test_indices)
# Calculate accuracy and generalization error with confidence interval here.
# Calculate accuracy and generalization error with confidence interval here.
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# TODO: leaa
# TODO: learning curve
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 that takes as input an array of true labels ($true$) and an array of predicted labels ($pred$). It should output a numpy.ndarray.
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
defconf_matrix(true,pred):
# You should see array([ 196, 106, 193, 105]) with seed 123
We can use the validation set to come up with a $k$ value that results in better performance in terms of accuracy. Additionally, in some cases, predicting examples from a certain class correctly is more critical than other classes. In those cases, we can use the confusion matrix to find a good trade off between correct and wrong predictions and allow more wrong predictions in some classes to predict more examples correctly in a that class.
We can use the validation set to come up with a $k$ value that results in better performance in terms of accuracy. Additionally, in some cases, predicting examples from a certain class correctly is more critical than other classes. In those cases, we can use the confusion matrix to find a good trade off between correct and wrong predictions and allow more wrong predictions in some classes to predict more examples correctly in a that class.
Below calculate the accuracies and confusion matrices for different values of $k$ using the validation set. Report a good $k$ value and use it in the analyses that follow this section.
Below calculate the accuracies and confusion matrices for different values of $k$ using the validation set. Report a good $k$ value and use it in the analyses that follow this section.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
# Change values of $k.
# Change values of $k.
# Calculate accuracies and confusion matrices for the validation set.
# Calculate accuracies for the validation set.
# Report a good k value that you'll use in the following analyses.
# Report a good k value that you'll use in the following analyses.
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
### ROC curve and confusion matrix for the final model
### ROC curve and confusion matrix for the final model
ROC curves are a good way to visualize sensitivity vs. 1-specificity for varying cut off points. Now, implement a "ROC" function that predicts the labels of the test set examples using different $threshold$ values in "predict" and plot the ROC curve. "ROC" takes a list containing different $threshold$ parameter 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 a "ROC" function that predicts the labels of the test set examples using different $threshold$ values in "predict" and plot the ROC curve. "ROC" takes a list containing different $threshold$ parameter 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:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defROC(model,indices,value_list):
defROC(model,indices,value_list):
'''
'''
model: a fitted k-NN model
model: a fitted k-NN model
indices: for data points to predict
indices: for data points to predict
value_list: array containing different threshold values
value_list: array containing different threshold values
Calculate sensitivity and 1-specificity for each point in value_list
Calculate sensitivity and 1-specificity for each point in value_list
Return two nX1 arrays: sens (for sensitivities) and spec_ (for 1-specificities)
Return two nX1 arrays: sens (for sensitivities) and spec_ (for 1-specificities)
'''
'''
# use predict_batch to obtain predicted labels at different threshold values
# use predict_batch to obtain predicted labels at different threshold values
raiseNotImplementedError
raiseNotImplementedError
returnsens,spec_
returnsens,spec_
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
We can finally create the confusion matrix and plot the ROC curve for our optimal $k$-NN classifier.
We can finally create the confusion matrix and plot the ROC curve for our optimal $k$-NN classifier.
"If the data is better suited for quadratic/cubic regression, regions of positive and negative residuals will alternate in the plot. Regardless, modify the fit and predict in the class definition to raise the feature values to $polynomial\\_degree$. You can directly make the modification in the above definition, do not repeat. Use the validation set to find among the degree of polynomial that results in lowest \"mse\"."
"If the data is better suited for quadratic/cubic regression, regions of positive and negative residuals will alternate in the plot. Regardless, modify fit\" and \"predict\" in the class definition to raise the feature values to $polynomial\\_degree$. You can directly make the modification in the above definition, do not repeat. Use the validation set to find the degree of polynomial that results in lowest \"mse\"."
]
]
},
},
{
{
...
@@ -211,7 +211,7 @@
...
@@ -211,7 +211,7 @@
},
},
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": 27,
"execution_count": null,
"metadata": {},
"metadata": {},
"outputs": [],
"outputs": [],
"source": [
"source": [
...
...
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# Linear Regression & Naive Bayes
# Linear Regression & Naive Bayes
We'll implement linear regression & Naive Bayes algorithms for this assignment. Please modify the "preprocess" and "partition" methods in "model.ipynb" to suit your datasets for this assignment. In this assignment, we have a small dataset available to us. We won't have examples to spare for validation set, instead we'll use cross-validation to tune hyperparameters.
We'll implement linear regression & Naive Bayes algorithms for this assignment. Please modify the "preprocess" and "partition" methods in "model.ipynb" to suit your datasets for this assignment. In this assignment, we have a small dataset available to us. We won't have examples to spare for validation set, instead we'll use cross-validation to tune hyperparameters.
### Assignment Goals:
### Assignment Goals:
In this assignment, we will:
In this assignment, we will:
* implement linear regression
* implement linear regression
* use gradient descent for optimization
* use gradient descent for optimization
* use residuals to decide if we need a polynomial model
* use residuals to decide if we need a polynomial model
* change our model to quadratic/cubic regression and use cross-validation to find the "best" polynomial degree
* change our model to quadratic/cubic regression and use cross-validation to find the "best" polynomial degree
* implement regularization techniques
* implement regularization techniques
* $l_1$/$l_2$ regularization
* $l_1$/$l_2$ regularization
* use cross-validation to find a good regularization parameter $\lambda$
* use cross-validation to find a good regularization parameter $\lambda$
* implement Naive Bayes
* implement Naive Bayes
* address sparse data problem with **pseudocounts** (**$m$-estimate**)
* address sparse data problem with **pseudocounts** (**$m$-estimate**)
%% 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
importnumpyasnp
importnumpyasnp
importmatplotlib.pyplotasplt
importmatplotlib.pyplotasplt
```
```
%% 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:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defmse(y_pred,y_true):
defmse(y_pred,y_true):
'''
'''
y_hat: values predicted by our method
y_hat: values predicted by our method
y_true: true y values
y_true: true y values
'''
'''
raiseNotImplementedError
raiseNotImplementedError
# returns mean squared error between y_pred and y_true
# returns mean squared error between y_pred and y_true
returncost
returncost
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
We'll start by implementing a partition function for $k$-fold cross-validation. $5$ and $10$ are commonly used values for $k$. You can use either one of them.
We'll start by implementing a partition function for $k$-fold cross-validation. $5$ and $10$ are commonly used values for $k$. You can use either one of them.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defkfold(k):
defkfold(k):
'''
'''
k: number of desired splits in data.
k: number of desired splits in data.
Assume test set is already separated.
Assume test set is already separated.
This function chooses 1/k of training indices randomly and separates them as validation partition.
This function chooses 1/k of training indices randomly and separates them as validation partition.
It returns the 1/k selected indices as val_indices and the remaining 1-(1/k) of the indices as train_indices
It returns the 1/k selected indices as val_indices and the remaining 1-(1/k) of the indices as train_indices
# use fit_kwargs to pass arguments to regularization function
# use fit_kwargs to pass arguments to regularization function
fit_kwargs={}
fit_kwargs={}
my_model.fit(**fit_kwargs)
my_model.fit(**fit_kwargs)
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Residuals are the differences between the predicted value $y_{hat}$ and the true value $y$ for each example. Predict $y_{hat}$ for the validation set. Calculate and plot residuals.
Residuals are the differences between the predicted value $y_{hat}$ and the true value $y$ for each example. Predict $y_{hat}$ for the validation set. Calculate and plot residuals.
If the data is better suited for quadratic/cubic regression, regions of positive and negative residuals will alternate in the plot. Regardless, modify the fit and predict in the class definition to raise the feature values to $polynomial\_degree$. You can directly make the modification in the above definition, do not repeat. Use the validation set to find among the degree of polynomial that results in lowest "mse".
If the data is better suited for quadratic/cubic regression, regions of positive and negative residuals will alternate in the plot. Regardless, modify fit" and "predict" in the class definition to raise the feature values to $polynomial\_degree$. You can directly make the modification in the above definition, do not repeat. Use the validation set to find the degree of polynomial that results in lowest "mse".
Define "regularization" function which implements $l_1$ and $l_2$ regularization. You'll use this function in "fit" method of "linear_regression" class.
Define "regularization" function which implements $l_1$ and $l_2$ regularization. You'll use this function in "fit" method of "linear_regression" class.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defregularization(method):
defregularization(method):
ifmethod=="l1":
ifmethod=="l1":
raiseNotImplementedError
raiseNotImplementedError
elifmethod=="l2":
elifmethod=="l2":
raiseNotImplementedError
raiseNotImplementedError
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Using the validation set, and the value of $polynomial_{degree}$ you found above, try different values of $\lambda$ to find a a good value that results in low $mse$. You can
Using the validation set, and the value of $polynomial_{degree}$ you found above, try different values of $\lambda$ to find a a good value that results in low $mse$. You can
" # returns the confusion matrix as numpy.ndarray\n",
" #raise NotImplementedError"
]
}
}
],
],
"metadata": {
"metadata": {
...
...
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
You might need to preprocess your dataset depending on which dataset you are using. This step is for reading the dataset and for extracting features and labels. The "preprocess" function should return an $n \times d$ features array, and an $n \times 1$ labels array, where $n$ is the number of examples and $d$ is the number of features in the dataset.
You might need to preprocess your dataset depending on which dataset you are using. This step is for reading the dataset and for extracting features and labels. The "preprocess" function should return an $n \times d$ features array, and an $n \times 1$ labels array, where $n$ is the number of examples and $d$ is the number of features in the dataset.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defpreprocess(file_path):
defpreprocess(file_path):
'''
'''
file_path: where to read the dataset from
file_path: where to read the dataset from
returns nxd features, nx1 labels
returns nxd features, nx1 labels
'''
'''
# You might find np.genfromtxt useful for reading in the file. Be careful with the file delimiter,
# You might find np.genfromtxt useful for reading in the file. Be careful with the file delimiter,
# e.g. for comma-separated files use delimiter=',' argument.
# e.g. for comma-separated files use delimiter=',' argument.
#raise NotImplementedError
#raise NotImplementedError
feature_path=file_path+'.data'
feature_path=file_path+'.data'
label_path=file_path+'.labels'
label_path=file_path+'.labels'
features=np.genfromtxt(feature_path)
features=np.genfromtxt(feature_path)
labels=np.genfromtxt(label_path)
labels=np.genfromtxt(label_path)
#features = data[:, 1:]
#features = data[:, 1:]
#labels = data[:, 0]
#labels = data[:, 0]
####################
####################
returnfeatures,labels
returnfeatures,labels
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Next, you'll need to split your dataset into training and validation and test sets. The "split" function should take as input the size of the whole dataset and randomly sample a proportion $p$ of the dataset as test partition and a proportion of $v$ as validation partition. The remaining will be used as training data. For example, to keep 30% of the examples as test and %10 as validation, set $p=0.3$ and $v=0.1$. You should choose these values according to the size of the data available to you. The "split" function should return indices of the training, validation and test sets. These will be used to index into the whole training set.
Next, you'll need to split your dataset into training and validation and test sets. The "split" function should take as input the size of the whole dataset and randomly sample a proportion $p$ of the dataset as test partition and a proportion of $v$ as validation partition. The remaining will be used as training data. For example, to keep 30% of the examples as test and %10 as validation, set $p=0.3$ and $v=0.1$. You should choose these values according to the size of the data available to you. The "split" function should return indices of the training, validation and test sets. These will be used to index into the whole training set.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defpartition(size,p,v,seed):
defpartition(size,p,v,seed):
'''
'''
size: number of examples in the whole dataset
size: number of examples in the whole dataset
p: proportion kept for test
p: proportion kept for test
v: proportion kept for validation
v: proportion kept for validation
'''
'''
# np.random.choice might come in handy. Do not sample with replacement!
# np.random.choice might come in handy. Do not sample with replacement!
# Be sure to not use the same indices in test and validation sets!
# Be sure to not use the same indices in test and validation sets!
#raise NotImplementedError
#raise NotImplementedError
data_list=np.arange(size)
data_list=np.arange(size)
p_size=np.int(np.ceil(size*p))
p_size=np.int(np.ceil(size*p))
v_size=np.int(np.ceil(size*v))
v_size=np.int(np.ceil(size*v))
np.random.seed(seed)
np.random.seed(seed)
permuted=np.random.permutation(data_list)
permuted=np.random.permutation(data_list)
test_indices=permuted[:p_size]
test_indices=permuted[:p_size]
val_indices=permuted[p_size+1:p_size+v_size]
val_indices=permuted[p_size+1:p_size+v_size]
##########################
##########################
# return two 1d arrays: one keeping validation set indices, the other keeping test set indices
# return two 1d arrays: one keeping validation set indices, the other keeping test set indices
returnval_indices,test_indices
returnval_indices,test_indices
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
classModel:
classModel:
# set the preprocessing function, partition_function
# set the preprocessing function, partition_function
# use kwargs to pass arguments to preprocessor_f and partition_f
# use kwargs to pass arguments to preprocessor_f and partition_f
# kwargs is a dictionary and should contain p, v and file_path
# kwargs is a dictionary and should contain p, v and file_path
# e.g. {'p': 0.3, 'v': 0.1, 'file_path': some_path}
# e.g. {'p': 0.3, 'v': 0.1, 'file_path': some_path}
" # np.random.choice might come in handy. Do not sample with replacement!\n",
" # np.random.choice might come in handy. Do not sample with replacement!\n",
" # Be sure to not use the same indices in test and validation sets!\n",
" # Be sure to not use the same indices in test and validation sets!\n",
" \n",
" \n",
" # use the first np.ceil(size*p) for test, \n",
" # the following np.ceil(size*v) for validation set.\n",
" \n",
" raise NotImplementedError\n",
" raise NotImplementedError\n",
" \n",
" \n",
" # return two 1d arrays: one keeping validation set indices, the other keeping test set indices \n",
" # return two 1d arrays: one keeping validation set indices, the other keeping test set indices \n",
...
@@ -79,7 +82,7 @@
...
@@ -79,7 +82,7 @@
},
},
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": 2,
"execution_count": 3,
"metadata": {},
"metadata": {},
"outputs": [],
"outputs": [],
"source": [
"source": [
...
@@ -103,6 +106,41 @@
...
@@ -103,6 +106,41 @@
" def predict(self, testpoint):\n",
" def predict(self, testpoint):\n",
" raise NotImplementedError"
" raise NotImplementedError"
]
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## General supervised learning related functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Implement the \"conf_matrix\" function that takes as input an array of true labels ($true$) and an array of predicted labels ($pred$). It should output a numpy.ndarray."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def conf_matrix(true, pred):\n",
" '''\n",
" true: nx1 array of true labels for test set\n",
" pred: nx1 array of predicted labels for test set\n",
" # false positives (fp) and false negatives (fn)\n",
" \n",
" # returns the confusion matrix as numpy.ndarray\n",
" return np.array([tp,tn, fp, fn])"
]
}
}
],
],
"metadata": {
"metadata": {
...
...
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# JUPYTER NOTEBOOK TIPS
# JUPYTER NOTEBOOK TIPS
Each rectangular box is called a cell.
Each rectangular box is called a cell.
* ctrl+ENTER evaluates the current cell; if it contains Python code, it runs the code, if it contains Markdown, it returns rendered text.
* ctrl+ENTER evaluates the current cell; if it contains Python code, it runs the code, if it contains Markdown, it returns rendered text.
* alt+ENTER evaluates the current cell and adds a new cell below it.
* alt+ENTER evaluates the current cell and adds a new cell below it.
* If you click to the left of a cell, you'll notice the frame changes color to blue. You can erase a cell by hitting 'dd' (that's two "d"s in a row) when the frame is blue.
* If you click to the left of a cell, you'll notice the frame changes color to blue. You can erase a cell by hitting 'dd' (that's two "d"s in a row) when the frame is blue.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# Supervised Learning Model Skeleton
# Supervised Learning Model Skeleton
We'll use this skeleton for implementing different supervised learning algorithms. Please complete "preprocess" and "partition" methods below.
We'll use this skeleton for implementing different supervised learning algorithms. Please complete "preprocess" and "partition" methods below.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
You might need to preprocess your dataset depending on which dataset you are using. This step is for reading the dataset and for extracting features and labels. The "preprocess" function should return an $n \times d$ features array, and an $n \times 1$ labels array, where $n$ is the number of examples and $d$ is the number of features in the dataset. In cases where there is a big difference between the scales of feautures, we want to normalize the features to have values in the same range [0,1]. If that is the case with your dataset, output normalized features to get better prediction results.
You might need to preprocess your dataset depending on which dataset you are using. This step is for reading the dataset and for extracting features and labels. The "preprocess" function should return an $n \times d$ features array, and an $n \times 1$ labels array, where $n$ is the number of examples and $d$ is the number of features in the dataset. In cases where there is a big difference between the scales of feautures, we want to normalize the features to have values in the same range [0,1]. If that is the case with your dataset, output normalized features to get better prediction results.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defpreprocess(file_path):
defpreprocess(file_path):
'''
'''
file_path: where to read the dataset from
file_path: where to read the dataset from
returns nxd features, nx1 labels
returns nxd features, nx1 labels
'''
'''
# You might find np.genfromtxt useful for reading in the file. Be careful with the file delimiter,
# You might find np.genfromtxt useful for reading in the file. Be careful with the file delimiter,
# e.g. for comma-separated files use delimiter=',' argument.
# e.g. for comma-separated files use delimiter=',' argument.
raiseNotImplementedError
raiseNotImplementedError
returnfeatures,labels
returnfeatures,labels
```
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
Next, you'll need to split your dataset into training and validation and test sets. The "split" function should take as input the size of the whole dataset and randomly sample a proportion $p$ of the dataset as test partition and a proportion of $v$ as validation partition. The remaining will be used as training data. For example, to keep 30% of the examples as test and %10 as validation, set $p=0.3$ and $v=0.1$. You should choose these values according to the size of the data available to you. The "split" function should return indices of the training, validation and test sets. These will be used to index into the whole training set.
Next, you'll need to split your dataset into training and validation and test sets. The "split" function should take as input the size of the whole dataset and randomly sample a proportion $p$ of the dataset as test partition and a proportion of $v$ as validation partition. The remaining will be used as training data. For example, to keep 30% of the examples as test and %10 as validation, set $p=0.3$ and $v=0.1$. You should choose these values according to the size of the data available to you. The "split" function should return indices of the training, validation and test sets. These will be used to index into the whole training set.
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
defpartition(size,p,v):
defpartition(size,p,v):
'''
'''
size: number of examples in the whole dataset
size: number of examples in the whole dataset
p: proportion kept for test
p: proportion kept for test
v: proportion kept for validation
v: proportion kept for validation
'''
'''
# np.random.choice might come in handy. Do not sample with replacement!
# np.random.choice might come in handy. Do not sample with replacement!
# Be sure to not use the same indices in test and validation sets!
# Be sure to not use the same indices in test and validation sets!
# use the first np.ceil(size*p) for test,
# the following np.ceil(size*v) for validation set.
raiseNotImplementedError
raiseNotImplementedError
# return two 1d arrays: one keeping validation set indices, the other keeping test set indices
# return two 1d arrays: one keeping validation set indices, the other keeping test set indices
returnval_indices,test_indices
returnval_indices,test_indices
```
```
%% Cell type:code id: tags:
%% Cell type:code id: tags:
``` python
``` python
classModel:
classModel:
# set the preprocessing function, partition_function
# set the preprocessing function, partition_function
# use kwargs to pass arguments to preprocessor_f and partition_f
# use kwargs to pass arguments to preprocessor_f and partition_f
# kwargs is a dictionary and should contain p, v and file_path
# kwargs is a dictionary and should contain p, v and file_path
# e.g. {'p': 0.3, 'v': 0.1, 'file_path': some_path}
# e.g. {'p': 0.3, 'v': 0.1, 'file_path': some_path}
Implement the "conf_matrix" function that takes as input an array of true labels ($true$) and an array of predicted labels ($pred$). It should output a numpy.ndarray.