R語言-KNN算法

kNN算法原理

1、K最近鄰(k-NearestNeighbor,KNN)分類算法,是一個理論上比較成熟的方法,也是最簡單的機器學習算法之一。該方法的思路是:如果一個樣本在特征空間中的k個最相似(即特征空間中最鄰近)的樣本中的大多數屬于某一個類別,則該樣本也屬于這個類別。

2、KNN算法中,所選擇的鄰居都是已經正確分類的對象。該方法在定類決策上只依據最鄰近的一個或者幾個樣本的類別來決定待分樣本所屬的類別。 KNN方法雖然從原理上也依賴于極限定理,但在類別決策時,只與極少量的相鄰樣本有關。由于KNN方法主要靠周圍有限的鄰近的樣本,而不是靠判別類域的方法來確定所屬類別的,因此對于類域的交叉或重疊較多的待分樣本集來說,KNN方法較其他方法更為適合。

3、KNN算法不僅可以用于分類,還可以用于回歸。通過找出一個樣本的k個最近鄰居,將這些鄰居的屬性的平均值賦給該樣本,就可以得到該樣本的屬性。更有用的方法是將不同距離的鄰居對該樣本產生的影響給予不同的權值(weight),如權值與距離成正比。

簡言之,就是將未標記的案例歸類為與它們最近相似的、帶有標記的案例所在的類

原理及舉例

工作原理:我們知道樣本集中每一個數據與所屬分類的對應關系,輸入沒有標簽的新數據后,將新數據與訓練集的數據對應特征進行比較,找出“距離”最近的k(通常k<20)數據,選擇這k個數據中出現最多的分類作為新數據的分類。

算法描述

1、計算已知數據集中的點與當前點的距離

2、按距離遞增次序排序

3、選取與當前數據點距離最近的K個點

4、確定前K個點所在類別出現的頻率

5、返回頻率最高的類別作為當前類別的預測

距離計算方法有"euclidean"(歐氏距離),”minkowski”(明科夫斯基距離), "maximum"(切比雪夫距離), "manhattan"(絕對值距離),"canberra"(蘭式距離), 或 "minkowski"(馬氏距離)等


Usage

knn(train, test, cl, k = 1, l = 0, prob =FALSE, use.all = TRUE)

Arguments

train

matrix or data frame of training set cases.

test

matrix or data frame of test set cases. A vector will ?be interpreted as a row vector for a single case.

cl

factor of true classifications of training set

k

number of neighbours considered.

l

minimum vote for definite decision, otherwisedoubt. (More precisely, less thank-ldissenting votes are allowed, even

ifkis ?increased by ties.)

prob

If this is true, the proportion of the votes for the

winning class are returned as attributeprob.

use.all

controls handling of ties. If true, all distances equal

to thekth largest are

included. If false, a random selection of distances equal to thekth is chosen to use exactlykneighbours.


一、R語言KKNN公式說明:

kknn(formula = formula(train), train, test, na.action = na.omit(), k = 7, distance = 2, kernel = "optimal", ykernel = NULL, scale=TRUE, contrasts = c('unordered' = "contr.dummy", ordered = "contr.ordinal"))

參數:

formula ? ? ? ? ? ? ? ? ? ? ? ? ? ?A formula object.

train ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Matrix or data frame of training set cases.

test ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Matrix or data frame of test set cases.

na.action ? ? ? ? ? ? ? ? ? ? ? ? A function which indicates what should happen when the data contain ’NA’s.

k ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Number of neighbors considered.

distance ? ? ? ? ? ? ? ? ? ? ? ? ?Parameter of Minkowski distance.

kernel ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Kernel to use. Possible choices are "rectangular" (which is standard unweighted knn), "triangular", "epanechnikov" (or beta(2,2)), "biweight" (or beta(3,3)), "triweight" (or beta(4,4)), "cos", "inv", "gaussian", "rank" and "optimal".

ykernel ? ? ? ? ? ? ? ? ? ? ? ? ? ?Window width of an y-kernel, especially for prediction of ordinal classes.

scale ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Logical, scale variable to have equal sd.

contrasts ? ? ? ? ? ? ? ? ? ? ? ? A vector containing the ’unordered’ and ’ordered’ contrasts to use

kknn的返回值如下:

fitted.values ? ? ? ? ? ? ?Vector of predictions.

CL ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Matrix of classes of the k nearest neighbors.

W ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Matrix of weights of the k nearest neighbors.

D ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Matrix of distances of the k nearest neighbors.

C ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Matrix of indices of the k nearest neighbors.

prob ? ? ? ? ? ? ? ? ? ? ? ? ? ?Matrix of predicted class probabilities.

response ? ? ? ? ? ? ? ? ? Type of response variable, one of continuous, nominal or ordinal.

distance ? ? ? ? ? ? ? ? ? ? Parameter of Minkowski distance.

call ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?The matched call.

terms ? ? ? ? ? ? ? ? ? ? ? ? ?The ’terms’ object used.

實例:


library(ggvis)

iris%>%ggvis(~Length,~Sepal.Width,fill=~Species)


iris%>%ggvis(~Length,~Sepal.Width,fill=~Species)


library(kknn)
data(iris)

dim(iris)

m<-(dim(iris))[1]
val<-sample(1:m,size=round(m/3),replace=FALSE,prob=rep(1/m,m))

建立訓練數據集

data.train<-iris[-val,]

建立測試數據集

data.test<-iris[val,]

調用kknn ?之前首先定義公式

formula :Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width

iris.kknn<-kknn(Species~.,iris.train,iris.test,distance=1,kernel="triangular")

summary(iris.kknn)

# 獲取fitted.values

fit <- fitted(iris.kknn)

# 建立表格檢驗判類準確性

table(iris.valid$Species, fit)
# 繪畫散點圖,k-nearest neighbor用紅色高亮顯示

pcol <- as.character(as.numeric(iris.valid$Species))

pairs(iris.valid[1:4], pch = pcol, col = c("green3", "red")[(iris.valid$Species != fit)+1]


二、R語言knn算法


install.packages("class")

library(class)

對于新的測試樣例基于距離相似度的法則,確定其K個最近的鄰居,在K個鄰居中少數服從多數

確定新測試樣例的類別

1、獲得數據

2、理解數據

對數據進行探索性分析,散點圖

如上例

3、確定問題類型,分類數據分析

4、機器學習算法knn

5、數據處理,歸一化數據處理

normalize <- function(x){

num <- x - min(x)

denom <- max(x) - min(x)

return(num/denom)

}

iris_norm <-as.data.frame(lapply(iris[,1:4], normalize))

summary(iris_norm)

6、訓練集與測試集選取

一般按照3:1的比例選取

方法一、set.seed(1234)

ind <- sample(2,nrow(iris), replace=TRUE, prob=c(0.67, 0.33))

iris_train <-iris[ind==1, 1:4]

iris_test <-iris[ind==2, 1:4]

train_label <-iris[ind==1, 5]

test_label <-iris[ind==2, 5]

方法二、

ind<-sample(1:150,50)

iris_train<-iris[-ind,]

iris_test<-iris[ind,1:4]

iris_train<-iris[-ind,1:4]

train_label<-iris[-ind,5]

test_label<-iris[ind,5]

7、構建KNN模型

iris_pred<-knn(train=iris_train,test=iris_test,cl=train_label,k=3)

8、模型評價

交叉列聯表法

table(test_label,iris_pred)

實例二

數據集

http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data

導入數據

dir <-'http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data'wdbc.data <-read.csv(dir,header = F)

names(wdbc.data) <- c('ID','Diagnosis','radius_mean','texture_mean','perimeter_mean','area_mean','smoothness_mean','compactness_mean','concavity_mean','concave points_mean','symmetry_mean','fractal dimension_mean','radius_sd','texture_sd','perimeter_sd','area_sd','smoothness_sd','compactness_sd','concavity_sd','concave points_sd','symmetry_sd','fractal dimension_sd','radius_max_mean','texture_max_mean','perimeter_max_mean','area_max_mean','smoothness_max_mean','compactness_max_mean','concavity_max_mean','concave points_max_mean','symmetry_max_mean','fractal dimension_max_mean')

table(wdbc.data$Diagnosis)## M = malignant, B = benign

wdbc.data$Diagnosis <- factor(wdbc.data$Diagnosis,levels =c('B','M'),labels = c(B ='benign',M ='malignant'))

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 前言 學習數據挖掘已經有一段時間了,相關的文章和書也看了一些,感覺學習這個的關鍵還是離不開其中形形色色的算法。作為...
    謙嘯閱讀 5,546評論 2 21
  • 土制的房子,收藏了我大部分的童年。 向上生長的泡桐,見證了我三年的青春。 高中,隨著年級的轉變,教室,也...
    離洛殊閱讀 376評論 0 1
  • 【原創】2017—09—14 堅持分享第177天 開學兩周了,老師、家長、孩子都在努力,有的孩...
    禾雨分享閱讀 1,207評論 2 2
  • 4天8斤,效果杠杠的! 公司的食堂阿姨,聽人說我減肥21斤,于2017.4.17嘗試食用159換食,換食前134斤...
    錦衣漏馬閱讀 186評論 0 0
  • 以下內容是根據楊萃先《職場36計》整理。 如果說,職場中有一件事是我們每天都在做的,我想,它一定是:發出請求。比如...
    一直這樣幸福著閱讀 8,472評論 0 3