R语言-KNN算法

Python09

R语言-KNN算法,第1张

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.

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.

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'))

1、线性模型~回归分析:【包】:stats 【函数】:lm(formula, data, ...)逐步回归:step(lm(formula, data, ...))回归诊断:influence.measure(lm(formula, data, ...))多重共线性:kappa(XX,exact=T), eigen(XX)自相关检验:一阶:dwtest(y~x) 多阶:bgtest(y~x,order=2,type=”Chisq”)【备注】:1)stats包里的lm()可做多元线形模型,anova.mlm()比较多个多元线形模型,manova()做多元方差分析(MANOVA)。2)sn包的msn.mle()和 and mst.mle()可拟合多元偏正态和偏t分布模型。3)pls包提供偏最小二乘回归(PLSR)和主成分回归;4)ppls包可做惩罚偏最小二乘回归;5)dr包提供降维回归方法,如:片逆回归法(Sliced Inverse Regression)、片平均方差估计(sliced average variance estimation)。6)plsgenomics包做基于偏最小二乘回归的基因组分析。7)relaimpo包可评估回归参数的相对重要性。2、logistic回归:【包】:stats 【函数】:glm(formula, family=gaussian,data, ...)注:familybinomial(link = "logit") gaussian(link = "identity") Gamma(link = "inverse") inverse.gaussian(link = "1/mu^2") poisson(link = "log") quasi(link = "identity", variance = "constant") quasibinomial(link = "logit") quasipoisson(link = "log")

3、无监督分类~决策树:【包】:rpart 【函数】:rpart(formula,data, method="class",control=ct,parms=list(prior=c(p,1-p),split="information"))

rpart.plot(fit,branch=1,branch.type=2,type=1,extra=102,shadow.col=”gray”,box.col=”green”,

split.cex=1.2,main=”Kyphosis决策树”) #提供了复杂度损失修剪的修剪方法

printcp(fit):告诉分裂到哪一层,CP,nsplit,rel,error,交叉验证的估计误差(xerror),标准误差(xstd)

prune(fit,cp=fit$cptable[which.min(fit$cptable[,"xerror"]),"CP"]):剪枝函数

【备注】:1)CRAN的 MachineLearning任务列表有对树方法的细节描述。

2)分类树也常常是重要的多元方法,rpart包正是这样的包,

3)rpart.permutation包还可以做rpart()模型的置换(permutation)检验。

4)TWIX包的树可以外部剪枝。

5)hier.part包分割多元数据集的方差。

6)mvpart包可做多元回归树,

7)party包实现了递归分割(recursive partitioning),

8)rrp包实现了随机递归分割。

9)caret包可做分类和回归训练,进而caretLSF包实现了并行处理。

10)kknn包的k-近 邻法可用于回归,也可用于分类。

4、支持向量机:

【包】:e1071,kernlab

【函数】:svm(x_train,y_train,type="C-classification",cost=10,kernel="radial",probability=TRUE,scale=FALSE)

svp=ksvm(x,y,type="C-svc",kernel="rbf",kpar=list(sigma=1),C=1)

5、无监督分类~聚类分析:

【包】:stats

【函数】:系统聚类:hclust(d,method=”complete”,members=NULL)

快速聚类:kmeans(x,centers,iter.max=10,nstart=1,algorithm=“Hartigan-Wong”)

距离函数:dist(x,method=”euclidean”,diag=FALSE,upper=FALSE,p=2)

【备注】:1)CRAN的Cluster任务列表全面的综述了R实现的聚类方法。

2)stats里提供等级聚类hclust()和k-均值聚类kmeans()。

3)cluster包里有大量的聚类和可视化技 术,

4)clv包里则有一些聚类确认程序,

5)e1071包的classAgreement()可计算Rand index比较两种分类结果。

6)Trimmed k-means聚类分析可由trimcluster包实现,

7)聚类融合方法(Cluster Ensembles)由clue包实现,

8)clusterSim包能帮助选择最佳的聚类,

9)hybridHclust包提供一些混合聚类方法。

10)energy包里有基于E统计量的距离测度函数edist()和等级聚类方法hclust.energy()。

11)LLAhclust包提供基于似然(likelihood linkage)方法的聚类,也有评定聚类结果的指标。

12)fpc包里有基于Mahalanobis距离的聚类。

13)clustvarsel包有多种基于模型的聚类。

14)模糊聚类(fuzzy clustering)可在cluster包和hopach包里实现。

15)Kohonen包提供用于高维谱(spectra)或模式(pattern)的有监督和无监督的SOM算法。

16)clusterGeneration包帮助模拟聚类。

17)CRAN的Environmetrics任务列表里也有相关的聚类算法的综述。

18)mclust包实现了基于模型的聚类,

19)MFDA包实现了功能数据的基于模型的聚类。

横截面数据回归经典方法

quantreg 分位数回归

MASS  BOX-COX变换

survival 生存函数、COX比例危险回归模型

mfp  COX比例危险回归模型多重分数多项式

car 可以检查vif

ridge 岭回归

lars  lasso回归

msgps adaptive lasso

pls 偏最小二乘

横截面数据 回归机器学习 方法

rpart.plot 画回归树

mboost  boosting回归

ipred  bagging回归

randomForest 随机森林回归

e1071  or kernlab  SVR支持向量机回归

nnet+caret  or neuralnet 神经网络

横截面数据 分类 经典方法

glm( ) 广义线性模型

MASS 的 lda( ) or   mda 的 mda( ) or   fda 的 fda( ) 线性判别

横截面数据 分类机器学习 方法

rpart.plot 画分类树

adabag  adaboost分类、bagging分类

randomForest 随机森林分类

e1071  or kernlab  SVR支持向量机分类

kknn 最近邻分类

nnet 神经网络分类

横截面数据 计数或有序因变量

Possion 散布问题(方差不等于均值):

dglm 双广义线性模型(Tweedie分布)

MASS 的 glm.nb( ) (负二项分布)

pscl 的 zeroinfl( ) 零膨胀计数数据模型

rminer 支持向量机

mlogit 多项logit模型

MASS 的 loglm( )  or nnet 的 multinom( ) 多项分布对数线性模型

MASS 的 polr( )  or VGAM 的 vglm( ) 多项分布对数线性模型

纵向数据:多水平模型、面板数据

lme4 的 lmer( )  or nlme 的 lme( ) 线性随机效应混合模型

REEMtree 拟合固定效应部分的决策树

coxme  cox随机效应分析

JM 联合模型

plm 拟合面板数据

多元分析

factanal( ) 因子分析

cluster 分层聚类

ICGE  INCA指数

ggmap 画地图

NbClust 一系列聚类方法

CCA 典型相关分析

MASS 对应分析

以下为非经典多元数据分析

FactoMineR 主成分分析、对应分析(补充元素作为测试集);多重对应分析(可以包含数量变量和分类变量)、多重因子分析、分层多重因子分析、基于主成分分析的分层聚类

多元数据的关联规则分析

arules 关联规则分析

路径建模数据的PLS分析

plspm 的函数 plspm( ) 偏最小二乘

lavvan 加协方差关系