R语言-KNN算法

Python017

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

在R语言中找到了计算遗传距离的函数dist.dna()但是不知道在R里面如何利用循环批量处理文件计算遗传距离。想到了利用python来调用R函数的方法,查找相关教程发现需要用到rpy2模块。

easy_install rpy2 报错(看不懂报错内容);

pip install rpy2 报错(提示需要更新pip到pip19.0.3);

利用 python -m pip install --upgrade pip 更新pip报错(看不懂报错内容);

利用 https://pip.pypa.io/en/stable/installing/ 教程安装pip成功更新。

使用 pip install rpy2 安装依旧报错(看不懂报错内容);

尝试教程 https://blog.csdn.net/suzyu12345/article/details/51476321 安装rpy2,提示 rpy2-2.9.5-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform

在rpy2主页 https://rpy2.bitbucket.io/ 发现一句话 Releasend source packages are available on PyPi. Installing should be as easy * as

(*:except on Windows)

这意思是在windows系统使用pip安装不太容易吗?

找到了教程 rpy2:在python中调用R函数的一个实例 ;发现其中rpy2的安装使用的是conda,自己也尝试在windows的DOS窗口下使用 conda install rpy2 成功。但是结尾处提示了一句 此时不应有do 不明白是什么意思

在python中加载R包查到可以使用

加载R语言自带的包时没有遇到问题;但是加载需要额外安装的包时遇到了报错

按照教程 https://blog.csdn.net/arcers/article/details/79109535 使用 conda install -c r r-ggplot2 安装需要用到的包解决问题

一个简便描述序列分歧大小的测度是两条核苷酸序列中不同核苷酸位点的比例 P = nd/n;

nd为检测两条序列间不同核苷酸数;n为配对总数;P成为核苷酸间的p距离

关于谱能量,有这样一种解释,你可以试着去算一算信号可以分成能量信号与功率信号,非周期能量信号具有能量谱密度,是傅立叶变换的平方,功率信号具有功率谱密度,其与自相关函数是一对傅立叶变换对,等于傅立叶变换的平方/区间长度。不能混淆。能量信号是没有功率谱的。胡广书老师的书上找到这么一段话,“随机信号在时间上是无限的,在样本上也是无穷多,因此随机信号的能量是无限的,它应是功率信号。功率信号不满足付里叶变换的绝对可积的条件,因此其付里叶变换是不存在的。如确定性的正弦函数的付里叶变换是不存在,只有引入了冲激函数才求得其付里叶变换。因此,对随机信号的频谱分析,不再简单的是频谱,而是功率谱。”对于确定性信号而言,里面存在能量信号,是没有功率谱密度的,也存在功率信号,是有功率谱密度的。所以信号的频谱与是否是确定性信号没有必然联系。以下论点来源于研学论坛:频谱是信号的傅立叶变换。它描述了信号在各个频率上的分布大小。频谱的平方(当能量有限,平均功率为0时称为能量谱)描述了信号能量在各个频率上的分布大小。计算过程中,都是通过样本数据的快速傅立叶变换来计算。但不同的是,信号的频谱是复数,包含幅频响应和相频响应,重复计算时的结果基本相同。而随机信号的功率谱也可以对数据进行FFT,但必须计算模值的平方,因为功率谱是实数。而且换一组样本后,计算的结果略有不同,因为随机信号的样本取值不同。要得到真实的功率谱必须进行多次平均,次数越多越好。根据parseval定理,信号傅氏变换模平方被定义为能量谱,即单位频率范围内包含的信号能量。自然,能量跟功率有一个时间平均的关系,所以,能量谱密度在时间上平均就得到了功率谱。matlab实现经典功率谱估计fft做出来是频谱,psd做出来是功率谱;功率谱丢失了频谱的相位信息;频谱不同的信号其功率谱是可能相同的;功率谱是幅度取模后平方,结果是个实数matlab中自功率谱密度直接用psd函数就可以求,按照matlab的说法,psd能实现Welch法估计,即相当于用改进的平均周期图法来求取随机信号的功率谱密度估计。psd求出的结果应该更光滑吧。1、直接法:直接法又称周期图法,它是把随机序列x(n)的N个观测数据视为一能量有限的序列,直接计算x(n)的离散傅立叶变换,得X(k),然后再取其幅值的平方,并除以N,作为序列x(n)真实功率谱的估计。Matlab代码示例:clearFs=1000%采样频率n=0:1/Fs:1%产生含有噪声的序列xn=cos(2*pi*40*n)+3*cos(2*pi*100*n)+randn(size(n))window=boxcar(length(xn))%矩形窗nfft=1024[Pxx,f]=periodogram(xn,window,nfft,Fs)%直接法plot(f,10*log10(Pxx))2、间接法:间接法先由序列x(n)估计出自相关函数R(n),然后对R(n)进行傅立叶变换,便得到x(n)的功率谱估计。Matlab代码示例:clearFs=1000%采样频率n=0:1/Fs:1%产生含有噪声的序列xn=cos(2*pi*40*n)+3*cos(2*pi*100*n)+randn(size(n))nfft=1024cxn=xcorr(xn,'unbiased')%计算序列的自相关函数CXk=fft(cxn,nfft)Pxx=abs(CXk)index=0:round(nfft/2-1)k=index*Fs/nfftplot_Pxx=10*log10(Pxx(index+1))plot(k,plot_Pxx)3、改进的直接法:对于直接法的功率谱估计,当数据长度N太大时,谱曲线起伏加剧,若N太小,谱的分辨率又不好,因此需要改进。3.1、Bartlett法Bartlett平均周期图的方法是将N点的有限长序列x(n)分段求周期图再平均。Matlab代码示例:clear;Fs=1000n=0:1/Fs:1xn=cos(2*pi*40*n)+3*cos(2*pi*100*n)+randn(size(n))nfft=1024window=boxcar(length(n))%矩形窗noverlap=0%数据无重叠p=0.9%置信概率[Pxx,Pxxc]=psd(xn,nfft,Fs,window,noverlap,p)index=0:round(nfft/2-1)k=index*Fs/nfftplot_Pxx=10*log10(Pxx(index+1))plot_Pxxc=10*log10(Pxxc(index+1))figure(1)plot(k,plot_Pxx)pausefigure(2)plot(k,[plot_Pxx plot_Pxx-plot_Pxxc plot_Pxx+plot_Pxxc])3.2、Welch法Welch法对Bartlett法进行了两方面的修正,一是选择适当的窗函数w(n),并再周期图计算前直接加进去,加窗的优点是无论什么样的窗函数均可使谱估计非负。二是在分段时,可使各段之间有重叠,这样会使方差减小。Matlab代码示例:clearFs=1000n=0:1/Fs:1xn=cos(2*pi*40*n)+3*cos(2*pi*100*n)+randn(size(n))nfft=1024window=boxcar(100)%矩形窗window1=hamming(100)%海明窗window2=blackman(100)%blackman窗noverlap=20%数据无重叠range='half'%频率间隔为[0 Fs/2],只计算一半的频率[Pxx,f]=pwelch(xn,window,noverlap,nfft,Fs,range)[Pxx1,f]=pwelch(xn,window1,noverlap,nfft,Fs,range)[Pxx2,f]=pwelch(xn,window2,noverlap,nfft,Fs,range)plot_Pxx=10*log10(Pxx)plot_Pxx1=10*log10(Pxx1)plot_Pxx2=10*log10(Pxx2)figure(1)plot(f,plot_Pxx)pausefigure(2)plot(f,plot_Pxx1)pausefigure(3)plot(f,plot_Pxx2)