EECS 442: Computer Vision

my wechat:Yooo932851

Don't hesitate to contact me

Problem Set 3: Introduction to Machine Learning

Problem 3.1 Nearest Neighbor Classification

In this problem, we will implement the k-nearest neighbor algorithm to recognize objects in tiny images. We will use images from Imagenette [3], a small, easy-to-classify subset of ImageNet [2] (Figure 1). The code for loading and pre-processing the dataset has been provided for you.

Note: There is a DEBUG flag in the starter code that you can set to True while you are debugging your code. When the flag is set, only 20% of the training set will be loaded, so the rest of the code should take less time to run. However, before reporting the answers to questions, please remember to set the flag back to False, and to rerun the cells! There is also an option to run the code with a different image size, which you are welcome to experiment with (again, please set this back to the default before submitting!).

(a) For the class KNearestNeighbor defined in the notebook, please finish implementing the following methods:

i. (1 point) Please read the header for the method compute distance two loops and understand its inputs and outputs. Fill the remainder of the method as indicated in the notebook, to compute the L2 distance between the images in the test set and the images

in the training set. The L2 distance is computed as the square root of the sum of the squared differences between the corresponding pixels of the two images.

Hint: You may use np.linalg.norm to compute the L2 distance.

ii. (1 point) It will be important in subsequent problem sets to write fast vectorized code: that is, code that operates on multiple examples at once, using as few for loops as possible. As practice, please complete the methods compute distance one loops which computes the L2 distance only using a single for loop (and is thus partially vectorized) and compute distance no loops which computes the L2 distance without using any loops and is thus fully vectorized.

Hint: ||x − y||2 = ||x||2 + ||y||2 − 2x T y

iii. (1 point) Complete the implementation of predict labels to find the k nearest neighbors for each test image.

Hint: It might be helpful to use the function np.argsort.

(b) (0 points) Run the subsequent cells, so that we can check your implementation above.

You will use KNearestNeighbor to predict the labels of test images and calculate the accuracy of these predictions. We have implemented the code for k = 1 and k = 3. For k = 1, you should expect to see approximately 29% test accuracy.

(c) (1 point) Find the best value for k using grid search on the validation set: for each value of k, calculate the accuracy on the validation set, then choose the highest one. Report the highest accuracy and the associated k in the provided cell below in the notebook. Also, please run the code that we’ve provided which uses the best k to calculate accuracy on the test set, and to see some visualizations of the nearest neighbors. (Optional, 0 points) Run the provided cells below to see the effects of normalization on the accuracy.

(d) (2 points) Instead of finding the most similar images based on raw pixels, we obtain better performance using hand-crafted image features. We’ll use a simplified version of the Histogram of Oriented Gradients (HOG) features [1]. To compute these features, you will:

i. Compute the orientations of the gradients by filling in the compute angles function.

Use modulo for angles that exceed 180 degrees so that all angles are in the range of [0, 180 deg].

Hint: You can use np.gradient to compute the image gradients.

ii. Create a histogram of edge orientations by filling the compute hog function. Weigh each edge’s vote based on its gradient magnitudes. Each edge votes for one bin that its orientation falls in. You can make use of math.floor() to find the index of the bin.

iii. (0 points) Perform block normalization across the histogram (provided in starter code) Please read the descriptions in the starter code and fill in the code blocks. Please also run the cells below to test your code. You should expect slightly lower accuracy with this simplified HOG than that with raw pixels. Our implementation obtains about 3% lower accuracy.

Note: We implement HOG in a simplified way, so the accuracy using HOG is worse than using raw pixels.

(e) (Optional, 0 points) For reference, we have provided code that computes full HOG features, using a library function. These features should obtain significantly higher accuracy (42% in our implementation). 

Problem 3.2 Linear classifier with Multinomial Logistic (Softmax) Loss In this problem, we will train a linear classifier using the softmax (multinomial logistic) loss (Equation 2) for image classification (Figure 1), using stochastic gradient descent.

(a) (3 points) Estimating the loss and gradients. Complete the implementation of the softmax loss naive function and its gradients using the formulae we have provided, following its specification. Please note that we are calculating the loss on a minibatch of N images. The inputs are (x1, y1),(x2, y2), ...(xN , yN ) where xi represents the i-th image in the batch, and yi is its corresponding label.

We first calculate the scores for each object class, i.e. the unnormalized probability that the image is of a particular class. We’ll denote the scores for a single image as s1, s2, ..., sC where C is the total number of classes, and compute them as, s = W xi . The softmax loss for a single image, Li can be defined as,

The total loss L for all images in the minibatch can then be calculated by averaging the losses over all of the individual examples:

Caution: When you exponentiate large numbers in your softmax layer, the result could be quite large, resulting in values of inf. To avoid these numerical issues, you can first subtract the maximum score from each scores as shown below:

Gradients We provide the formulae for the gradients, ∂L ∂W , which will also be returned by softmax loss naive:

As described in the notebook, after implementing this, please run the indicated cells for loss check and gradient check and make sure you get the expected values.

(b) (3 points) For the LinearClassifier class defined in the notebook, please complete the implementation of the following:

i. Stochastic gradient descent. Read the header for the method train and fill in the portions of the code as indicated, to sample random elements from the training data to form batched inputs and perform parameter update using gradient descent. (Loss and gradient calculation has already been taken care of by us) .

ii. Running the classifier. Similarly, write the code to implement predict method which returns the predicted classes by the linear classifier.

(c) (optional) (i) Show that Equation 1 is equivalent to Equation 3. That is, subtracting the largest score does not change the result of softmax. (ii) Explain why this may reduce numerical issues during training. (0 point).

(d) (0 points) Please run the rest of the code that we have provided, which uses LinearClassifier to train on the training split of the dataset and obtain the accuracies on the training and validation sets. Observe the accuracy on the test set, which should be around 38%.

(e) Finally, please refer to the visualizations of the learned classifiers. In these visualizations, we treat the classifier weights as though they were an image, and plot them. You may observe some interesting patterns in the way that each classifier distributes its weight.

Acknowledgements. Some of the homework and the starter code was taken from previous CS231n course at Stanford University by Fei-Fei Li, Justin Johnson and Serena Yeung.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,076评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,658评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,732评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,493评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,591评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,598评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,601评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,348评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,797评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,114评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,278评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,953评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,585评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,202评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,442评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,180评论 2 367
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,139评论 2 352

推荐阅读更多精彩内容