knn

import numpy as np

class KNearestNeighbor(object):

""" a kNN classifier with L2 distance """

def __init__(self):

pass

def train(self, X, y):

"""

Train the classifier. For k-nearest neighbors this is just

memorizing the training data.

Inputs:

- X: A numpy array of shape (num_train, D) containing the training data

consisting of num_train samples each of dimension D.

- y: A numpy array of shape (N,) containing the training labels, where

y[i] is the label for X[i].

"""

self.X_train = X

self.y_train = y

def predict(self, X, k=1, num_loops=0):

"""

Predict labels for test data using this classifier.

Inputs:

- X: A numpy array of shape (num_test, D) containing test data consisting

of num_test samples each of dimension D.

- k: The number of nearest neighbors that vote for the predicted labels.

- num_loops: Determines which implementation to use to compute distances

between training points and testing points.

Returns:

- y: A numpy array of shape (num_test,) containing predicted labels for the

test data, where y[i] is the predicted label for the test point X[i].

"""

if num_loops == 0:

dists = self.compute_distances_no_loops(X)

elif num_loops == 1:

dists = self.compute_distances_one_loop(X)

elif num_loops == 2:

dists = self.compute_distances_two_loops(X)

else:

raise ValueError('Invalid value %d for num_loops' % num_loops)

return self.predict_labels(dists, k=k)

def compute_distances_two_loops(self, X):

"""

Compute the distance between each test point in X and each training point

in self.X_train using a nested loop over both the training data and the

test data.

Inputs:

- X: A numpy array of shape (num_test, D) containing test data.

Returns:

- dists: A numpy array of shape (num_test, num_train) where dists[i, j]

is the Euclidean distance between the ith test point and the jth training

point.

"""

num_test = X.shape[0]

num_train = self.X_train.shape[0]

dists = np.zeros((num_test, num_train))

for i in xrange(num_test):

for j in xrange(num_train):

#####################################################################

# TODO:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

# Compute the l2 distance between the ith test point and the jth? ? #

# training point, and store the result in dists[i, j]. You should? #

# not use a loop over dimension.? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#####################################################################

# pass

dists[i][j] = np.sqrt(np.sum(np.square(X[i] - self.X_train[j])))

#####################################################################

#? ? ? ? ? ? ? ? ? ? ? END OF YOUR CODE? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#####################################################################

return dists

def compute_distances_one_loop(self, X):

"""

Compute the distance between each test point in X and each training point

in self.X_train using a single loop over the test data.

Input / Output: Same as compute_distances_two_loops

"""

num_test = X.shape[0]

num_train = self.X_train.shape[0]

dists = np.zeros((num_test, num_train))

for i in xrange(num_test):

#######################################################################

# TODO:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

# Compute the l2 distance between the ith test point and all training #

# points, and store the result in dists[i, :].? ? ? ? ? ? ? ? ? ? ? ? #

#######################################################################

# pass

dists[i] = np.sqrt(np.sum(np.square(self.X_train - X[i]), axis = 1))

#######################################################################

#? ? ? ? ? ? ? ? ? ? ? ? END OF YOUR CODE? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#######################################################################

return dists

def compute_distances_no_loops(self, X):

"""

Compute the distance between each test point in X and each training point

in self.X_train using no explicit loops.

Input / Output: Same as compute_distances_two_loops

"""

num_test = X.shape[0]

num_train = self.X_train.shape[0]

dists = np.zeros((num_test, num_train))

#########################################################################

# TODO:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

# Compute the l2 distance between all test points and all training? ? ? #

# points without using any explicit loops, and store the result in? ? ? #

# dists.? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

# You should implement this function using only basic array operations; #

# in particular you should not use functions from scipy.? ? ? ? ? ? ? ? #

#? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

# HINT: Try to formulate the l2 distance using matrix multiplication? ? #

#? ? ? and two broadcast sums.? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#########################################################################

# pass

dists = np.sqrt(-2*np.dot(X, self.X_train.T) + np.sum(np.square(self.X_train), axis = 1) + np.transpose([np.sum(np.square(X), axis = 1)]))

#########################################################################

#? ? ? ? ? ? ? ? ? ? ? ? END OF YOUR CODE? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#########################################################################

return dists

def predict_labels(self, dists, k=1):

"""

Given a matrix of distances between test points and training points,

predict a label for each test point.

Inputs:

- dists: A numpy array of shape (num_test, num_train) where dists[i, j]

gives the distance betwen the ith test point and the jth training point.

Returns:

- y: A numpy array of shape (num_test,) containing predicted labels for the

test data, where y[i] is the predicted label for the test point X[i].

"""

num_test = dists.shape[0]

y_pred = np.zeros(num_test)

for i in xrange(num_test):

# A list of length k storing the labels of the k nearest neighbors to

# the ith test point.

closest_y = []

#########################################################################

# TODO:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

# Use the distance matrix to find the k nearest neighbors of the ith? ? #

# testing point, and use self.y_train to find the labels of these? ? ? #

# neighbors. Store these labels in closest_y.? ? ? ? ? ? ? ? ? ? ? ? ? #

# Hint: Look up the function numpy.argsort.? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#########################################################################

# pass

closest_y = self.y_train[np.argsort(dists[i])[:k]]

#########################################################################

# TODO:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

# Now that you have found the labels of the k nearest neighbors, you? ? #

# need to find the most common label in the list closest_y of labels.? #

# Store this label in y_pred[i]. Break ties by choosing the smaller? ? #

# label.? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#########################################################################

# pass

y_pred[i] = np.argmax(np.bincount(closest_y))

#########################################################################

#? ? ? ? ? ? ? ? ? ? ? ? ? END OF YOUR CODE? ? ? ? ? ? ? ? ? ? ? ? ? ? #

#########################################################################

return y_pred

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子官紫,更是在濱河造成了極大的恐慌,老刑警劉巖娃循,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鹿驼,死亡現(xiàn)場離奇詭異,居然都是意外死亡药版,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門喻犁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來槽片,“玉大人,你說我怎么就攤上這事肢础』顾ǎ” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵传轰,是天一觀的道長剩盒。 經(jīng)常有香客問我,道長慨蛙,這世上最難降的妖魔是什么辽聊? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮期贫,結(jié)果婚禮上跟匆,老公的妹妹穿的比我還像新娘。我一直安慰自己通砍,他們只是感情好贾铝,可當(dāng)我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般垢揩。 火紅的嫁衣襯著肌膚如雪玖绿。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天叁巨,我揣著相機與錄音斑匪,去河邊找鬼。 笑死锋勺,一個胖子當(dāng)著我的面吹牛蚀瘸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播庶橱,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼贮勃,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了苏章?” 一聲冷哼從身側(cè)響起寂嘉,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎枫绅,沒想到半個月后泉孩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡并淋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年寓搬,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片县耽。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡句喷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出兔毙,到底是詐尸還是另有隱情唾琼,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布瞒御,位于F島的核電站,受9級特大地震影響神郊,放射性物質(zhì)發(fā)生泄漏肴裙。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一涌乳、第九天 我趴在偏房一處隱蔽的房頂上張望蜻懦。 院中可真熱鬧,春花似錦夕晓、人聲如沸宛乃。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽征炼。三九已至析既,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間谆奥,已是汗流浹背眼坏。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留酸些,地道東北人宰译。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像魄懂,于是被迫代替她去往敵國和親沿侈。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,629評論 2 354

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

  • 前言: 以斯坦福cs231n課程的python編程任務(wù)為主線市栗,展開對該課程主要內(nèi)容的理解和部分?jǐn)?shù)學(xué)推導(dǎo)缀拭。該課程相關(guān)...
    卑鄙的我_閱讀 3,375評論 0 2
  • 一、前言 CS231n是斯坦福大學(xué)開設(shè)的一門深度學(xué)習(xí)與計算機視覺課程肃廓,是目前公認的該領(lǐng)域內(nèi)最好的公開課智厌。目前,該課...
    金戈大王閱讀 4,771評論 3 7
  • 跟著cs231n assignment1的knn部分的notebook引導(dǎo)盲赊,把這個作業(yè)做完了铣鹏。knn的算法本身很簡...
    xionghuisquall閱讀 5,227評論 0 1
  • 我是踢到深夜的一只瓶子 我是藏不住眼淚的瓶子 我是被捏疼的瓶子 瘦了下來 被你踢到深夜 你厭倦了 我便也停下來 風(fēng)...
    張?zhí)旃?/span>閱讀 199評論 0 1
  • 做一個簡單的人, 看得清世間繁雜卻不在心中留下痕跡哀蘑。 整理一下自己的心情诚卸, 忘記那些不愉快的往事, 聽聽音樂绘迁,看看...
    時間刺客閱讀 230評論 0 0