Skip to content

Commit c7b4be1

Browse files
committed
Start code upload
1 parent 1d46344 commit c7b4be1

File tree

109 files changed

+21603
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

109 files changed

+21603
-0
lines changed

assignment1/.gitignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
*.swp
2+
*.pyc
3+
.env/*
4+
*.ipynb_checkpoints/*
5+
6+
# gitignore the built release.
7+
assignment3/*

assignment1/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Details about this assignment can be found [on the course webpage](http://cs231n.github.io/), under Assignment #1 of Spring 2019.

assignment1/assignment1.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
---
2+
layout: page
3+
mathjax: true
4+
permalink: /assignments2019/assignment1/
5+
---
6+
7+
In this assignment you will practice putting together a simple image classification pipeline, based on the k-Nearest Neighbor or the SVM/Softmax classifier. The goals of this assignment are as follows:
8+
9+
- understand the basic **Image Classification pipeline** and the data-driven approach (train/predict stages)
10+
- understand the train/val/test **splits** and the use of validation data for **hyperparameter tuning**.
11+
- develop proficiency in writing efficient **vectorized** code with numpy
12+
- implement and apply a k-Nearest Neighbor (**kNN**) classifier
13+
- implement and apply a Multiclass Support Vector Machine (**SVM**) classifier
14+
- implement and apply a **Softmax** classifier
15+
- implement and apply a **Two layer neural network** classifier
16+
- understand the differences and tradeoffs between these classifiers
17+
- get a basic understanding of performance improvements from using **higher-level representations** than raw pixels (e.g. color histograms, Histogram of Gradient (HOG) features)
18+
19+
## Setup
20+
21+
Get the code as a zip file [here](http://cs231n.github.io/assignments/2019/spring1819_assignment1.zip).
22+
23+
You can follow the setup instructions [here](/setup-instructions).
24+
25+
### Download data:
26+
Once you have the starter code (regardless of which method you choose above), you will need to download the CIFAR-10 dataset.
27+
Run the following from the `assignment1` directory:
28+
29+
```bash
30+
cd cs231n/datasets
31+
./get_datasets.sh
32+
```
33+
34+
### Start IPython:
35+
After you have the CIFAR-10 data, you should start the IPython notebook server from the
36+
`assignment1` directory, with the `jupyter notebook` command. (See the [Google Cloud Tutorial](https://github.com/cs231n/gcloud/) for any additional steps you may need to do for setting this up, if you are working remotely)
37+
38+
If you are unfamiliar with IPython, you can also refer to our
39+
[IPython tutorial](/ipython-tutorial).
40+
41+
### Some Notes
42+
**NOTE 1:** There are `# *****START OF YOUR CODE`/`# *****END OF YOUR CODE` tags denoting the start and end of code sections you should fill out. Take care to not delete or modify these tags, or your assignment may not be properly graded.
43+
44+
**NOTE 2:** The submission process this year has **2 steps**, requiring you to 1. run a submission script and 2. download/upload an auto-generated pdf (details below.) We suggest **_making a test submission early on_** to make sure you are able to successfully submit your assignment on time (a maximum of 10 submissions can be made.)
45+
46+
**NOTE 3:** This year, the `assignment1` code has been tested to be compatible with python version `3.7` (it may work with other versions of `3.x`, but we won't be officially supporting them). You will need to make sure that during your virtual environment setup that the correct version of `python` is used. You can confirm your python version by (1) activating your virtualenv and (2) running `which python`.
47+
48+
**NOTE 4:** If you are working in a virtual environment on OSX, you may *potentially* encounter
49+
errors with matplotlib due to the [issues described here](http://matplotlib.org/faq/virtualenv_faq.html). In our testing, it seems that this issue is no longer present with the most recent version of matplotlib, but if you do end up running into this issue you may have to use the `start_ipython_osx.sh` script from the `assignment1` directory (instead of `jupyter notebook` above) to launch your IPython notebook server. Note that you may have to modify some variables within the script to match your version of python/installation directory. The script assumes that your virtual environment is named `.env`.
50+
51+
### Q1: k-Nearest Neighbor classifier (20 points)
52+
53+
The IPython Notebook **knn.ipynb** will walk you through implementing the kNN classifier.
54+
55+
### Q2: Training a Support Vector Machine (25 points)
56+
57+
The IPython Notebook **svm.ipynb** will walk you through implementing the SVM classifier.
58+
59+
### Q3: Implement a Softmax classifier (20 points)
60+
61+
The IPython Notebook **softmax.ipynb** will walk you through implementing the Softmax classifier.
62+
63+
### Q4: Two-Layer Neural Network (25 points)
64+
The IPython Notebook **two\_layer\_net.ipynb** will walk you through the implementation of a two-layer neural network classifier.
65+
66+
### Q5: Higher Level Representations: Image Features (10 points)
67+
68+
The IPython Notebook **features.ipynb** will walk you through this exercise, in which you will examine the improvements gained by using higher-level representations as opposed to using raw pixel values.
69+
70+
### Submitting your work
71+
72+
**Important:** _Please make sure that the submitted notebooks have been run and the cell outputs are visible._
73+
74+
There are **_two_** steps to submitting your assignment:
75+
76+
**1.** Run the provided `collectSubmission.sh` script in the `assignment1` directory.
77+
78+
You will be prompted for your SunetID (e.g. `jdoe`) and will need to provide your Stanford password. This script will generate a zip file of your code, submit your source code to Stanford AFS, and generate a pdf `a1.pdf` in a `cs231n-2019-assignment1/` folder in your AFS home directory.
79+
80+
If your submission for this step was successful, you should see a display message
81+
82+
`### Code submitted at [TIME], [N] submission attempts remaining. ###`
83+
84+
**2.** Download the generated `a1.pdf` from AFS, then submit the pdf to [Gradescope](https://gradescope.com/courses/17367). If you are enrolled in the course, you should have already been automatically added to the course on Gradescope.

assignment1/collectSubmission.sh

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#!/bin/bash
2+
#NOTE: DO NOT EDIT THIS FILE-- MAY RESULT IN INCOMPLETE SUBMISSIONS
3+
4+
NOTEBOOKS="knn.ipynb
5+
svm.ipynb
6+
softmax.ipynb
7+
two_layer_net.ipynb
8+
features.ipynb"
9+
10+
CODE="cs231n/classifiers/k_nearest_neighbor.py
11+
cs231n/classifiers/linear_classifier.py
12+
cs231n/classifiers/linear_svm.py
13+
cs231n/classifiers/softmax.py
14+
cs231n/classifiers/neural_net.py"
15+
16+
LOCAL_DIR=`pwd`
17+
REMOTE_DIR="cs231n-2019-assignment1"
18+
ASSIGNMENT_NO=1
19+
ZIP_FILENAME="a1.zip"
20+
21+
C_R="\e[31m"
22+
C_G="\e[32m"
23+
C_BLD="\e[1m"
24+
C_E="\e[0m"
25+
26+
FILES=""
27+
for FILE in "${NOTEBOOKS} ${CODE}"
28+
do
29+
if [ ! -f ${F} ]; then
30+
echo -e "${C_R}Required file ${FILE} not found, Exiting.${C_E}"
31+
exit 0
32+
fi
33+
FILES="${FILES} ${LOCAL_DIR}/${FILE}"
34+
done
35+
36+
echo -e "${C_BLD}### Zipping file ###${C_E}"
37+
rm -f ${ZIP_FILENAME}
38+
zip -r ${ZIP_FILENAME} . -x "*.git*" "*cs231n/datasets*" "*.ipynb_checkpoints*" "*README.md" "collectSubmission.sh" "*requirements.txt" "*__pycache__*" ".env/*" > assignment_zip.log
39+
echo ""
40+
41+
echo -e "${C_BLD}### Submitting to myth ###${C_E}"
42+
echo "Type in your Stanford student ID (alphanumeric, *not* the 8-digit ID):"
43+
read -p "Student ID: " SUID
44+
echo ""
45+
46+
echo -e "${C_BLD}### Copying to ${SUID}@myth.stanford.edu:${REMOTE_DIR} ###${C_E}"
47+
echo -e "${C_G}Note: if myth is under heavy use, this may hang: If this happens, rerun the script.${C_E}"
48+
FILES="${FILES} ${LOCAL_DIR}/${ZIP_FILENAME}"
49+
rsync -avP ${FILES} ${SUID}@myth.stanford.edu:${REMOTE_DIR}
50+
echo ""
51+
52+
echo -e "${C_BLD}### Running remote submission script from ${SUID}@myth.stanford.edu:${REMOTE_DIR} ###${C_E}"
53+
ssh ${SUID}@myth.stanford.edu "cd ${REMOTE_DIR} && /afs/ir/class/cs231n/grading/submit ${ASSIGNMENT_NO} ${SUID} ${ZIP_FILENAME} && exit"

assignment1/cs231n/__init__.py

Whitespace-only changes.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from cs231n.classifiers.k_nearest_neighbor import *
2+
from cs231n.classifiers.linear_classifier import *
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
from builtins import range
2+
from builtins import object
3+
import numpy as np
4+
from past.builtins import xrange
5+
6+
7+
class KNearestNeighbor(object):
8+
""" a kNN classifier with L2 distance """
9+
10+
def __init__(self):
11+
pass
12+
13+
def train(self, X, y):
14+
"""
15+
Train the classifier. For k-nearest neighbors this is just
16+
memorizing the training data.
17+
18+
Inputs:
19+
- X: A numpy array of shape (num_train, D) containing the training data
20+
consisting of num_train samples each of dimension D.
21+
- y: A numpy array of shape (N,) containing the training labels, where
22+
y[i] is the label for X[i].
23+
"""
24+
self.X_train = X
25+
self.y_train = y
26+
27+
def predict(self, X, k=1, num_loops=0):
28+
"""
29+
Predict labels for test data using this classifier.
30+
31+
Inputs:
32+
- X: A numpy array of shape (num_test, D) containing test data consisting
33+
of num_test samples each of dimension D.
34+
- k: The number of nearest neighbors that vote for the predicted labels.
35+
- num_loops: Determines which implementation to use to compute distances
36+
between training points and testing points.
37+
38+
Returns:
39+
- y: A numpy array of shape (num_test,) containing predicted labels for the
40+
test data, where y[i] is the predicted label for the test point X[i].
41+
"""
42+
if num_loops == 0:
43+
dists = self.compute_distances_no_loops(X)
44+
elif num_loops == 1:
45+
dists = self.compute_distances_one_loop(X)
46+
elif num_loops == 2:
47+
dists = self.compute_distances_two_loops(X)
48+
else:
49+
raise ValueError('Invalid value %d for num_loops' % num_loops)
50+
51+
return self.predict_labels(dists, k=k)
52+
53+
def compute_distances_two_loops(self, X):
54+
"""
55+
Compute the distance between each test point in X and each training point
56+
in self.X_train using a nested loop over both the training data and the
57+
test data.
58+
59+
Inputs:
60+
- X: A numpy array of shape (num_test, D) containing test data.
61+
62+
Returns:
63+
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
64+
is the Euclidean distance between the ith test point and the jth training
65+
point.
66+
"""
67+
num_test = X.shape[0]
68+
num_train = self.X_train.shape[0]
69+
dists = np.zeros((num_test, num_train))
70+
for i in range(num_test):
71+
for j in range(num_train):
72+
#####################################################################
73+
# TODO: #
74+
# Compute the l2 distance between the ith test point and the jth #
75+
# training point, and store the result in dists[i, j]. You should #
76+
# not use a loop over dimension, nor use np.linalg.norm(). #
77+
#####################################################################
78+
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
79+
80+
pass
81+
82+
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
83+
return dists
84+
85+
def compute_distances_one_loop(self, X):
86+
"""
87+
Compute the distance between each test point in X and each training point
88+
in self.X_train using a single loop over the test data.
89+
90+
Input / Output: Same as compute_distances_two_loops
91+
"""
92+
num_test = X.shape[0]
93+
num_train = self.X_train.shape[0]
94+
dists = np.zeros((num_test, num_train))
95+
for i in range(num_test):
96+
#######################################################################
97+
# TODO: #
98+
# Compute the l2 distance between the ith test point and all training #
99+
# points, and store the result in dists[i, :]. #
100+
# Do not use np.linalg.norm(). #
101+
#######################################################################
102+
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
103+
104+
pass
105+
106+
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
107+
return dists
108+
109+
def compute_distances_no_loops(self, X):
110+
"""
111+
Compute the distance between each test point in X and each training point
112+
in self.X_train using no explicit loops.
113+
114+
Input / Output: Same as compute_distances_two_loops
115+
"""
116+
num_test = X.shape[0]
117+
num_train = self.X_train.shape[0]
118+
dists = np.zeros((num_test, num_train))
119+
#########################################################################
120+
# TODO: #
121+
# Compute the l2 distance between all test points and all training #
122+
# points without using any explicit loops, and store the result in #
123+
# dists. #
124+
# #
125+
# You should implement this function using only basic array operations; #
126+
# in particular you should not use functions from scipy, #
127+
# nor use np.linalg.norm(). #
128+
# #
129+
# HINT: Try to formulate the l2 distance using matrix multiplication #
130+
# and two broadcast sums. #
131+
#########################################################################
132+
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
133+
134+
pass
135+
136+
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
137+
return dists
138+
139+
def predict_labels(self, dists, k=1):
140+
"""
141+
Given a matrix of distances between test points and training points,
142+
predict a label for each test point.
143+
144+
Inputs:
145+
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
146+
gives the distance betwen the ith test point and the jth training point.
147+
148+
Returns:
149+
- y: A numpy array of shape (num_test,) containing predicted labels for the
150+
test data, where y[i] is the predicted label for the test point X[i].
151+
"""
152+
num_test = dists.shape[0]
153+
y_pred = np.zeros(num_test)
154+
for i in range(num_test):
155+
# A list of length k storing the labels of the k nearest neighbors to
156+
# the ith test point.
157+
closest_y = []
158+
#########################################################################
159+
# TODO: #
160+
# Use the distance matrix to find the k nearest neighbors of the ith #
161+
# testing point, and use self.y_train to find the labels of these #
162+
# neighbors. Store these labels in closest_y. #
163+
# Hint: Look up the function numpy.argsort. #
164+
#########################################################################
165+
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
166+
167+
pass
168+
169+
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
170+
#########################################################################
171+
# TODO: #
172+
# Now that you have found the labels of the k nearest neighbors, you #
173+
# need to find the most common label in the list closest_y of labels. #
174+
# Store this label in y_pred[i]. Break ties by choosing the smaller #
175+
# label. #
176+
#########################################################################
177+
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
178+
179+
pass
180+
181+
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
182+
183+
return y_pred

0 commit comments

Comments
 (0)