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.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子集惋,更是在濱河造成了極大的恐慌,老刑警劉巖贡耽,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件匙头,死亡現(xiàn)場離奇詭異琉历,居然都是意外死亡舞萄,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進(jìn)店門誊稚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來翔始,“玉大人,你說我怎么就攤上這事里伯〕窍梗” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵俏脊,是天一觀的道長全谤。 經(jīng)常有香客問我肤晓,道長爷贫,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任补憾,我火速辦了婚禮漫萄,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘盈匾。我一直安慰自己腾务,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布削饵。 她就那樣靜靜地躺著岩瘦,像睡著了一般。 火紅的嫁衣襯著肌膚如雪窿撬。 梳的紋絲不亂的頭發(fā)上启昧,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天,我揣著相機(jī)與錄音劈伴,去河邊找鬼密末。 笑死,一個胖子當(dāng)著我的面吹牛跛璧,可吹牛的內(nèi)容都是我干的严里。 我是一名探鬼主播,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼追城,長吁一口氣:“原來是場噩夢啊……” “哼刹碾!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起座柱,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤迷帜,失蹤者是張志新(化名)和其女友劉穎叨吮,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體瞬矩,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡茶鉴,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了景用。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片涵叮。...
    茶點(diǎn)故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖伞插,靈堂內(nèi)的尸體忽然破棺而出割粮,到底是詐尸還是另有隱情,我是刑警寧澤媚污,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布舀瓢,位于F島的核電站,受9級特大地震影響耗美,放射性物質(zhì)發(fā)生泄漏京髓。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一商架、第九天 我趴在偏房一處隱蔽的房頂上張望堰怨。 院中可真熱鬧,春花似錦蛇摸、人聲如沸备图。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽贴谎。三九已至惜犀,卻和暖如春蛛芥,著一層夾襖步出監(jiān)牢的瞬間诗箍,已是汗流浹背朦前。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工裂七, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留唬格,地道東北人家破。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像购岗,于是被迫代替她去往敵國和親汰聋。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容