knn演算法及java實現
1. KNN演算法,k近鄰
K最近鄰(k-Nearest Neighbour,KNN)分類演算法,是一個理論上比較成熟的方法,也是最簡單的機器學習演算法之一。該方法的思路是:如果一個樣本在特徵空間中的k個最相似(即特徵空間中最鄰近)的樣本中的大多數屬於某一個類別,則該樣本也屬於這個類別。
2. 求KNN文本分類演算法java實現源代碼【散分了!!!!】
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
#define NATTRS 5 //number of attributes
#define MAXSZ 1700 //max size of training set
#define MAXVALUE 10000.0 //the biggest attribute's value is below 10000(int)
#define K 5
struct vector {
double attributes[NATTRS];
double classlabel;
};
struct item {
double distance;
double classlabel;
};
struct vector trSet[MAXSZ];//global variable,the training set
struct item knn[K];//global variable,the k-neareast-neighbour set
int curTSize = 0; //current size of the training set
int AddtoTSet(struct vector v)
{
if(curTSize>=MAXSZ) {
cout<<endl<<"The training set has "<<MAXSZ<<" examples!"<<endl<<endl;
return 0;
}
trSet[curTSize] = v;
curTSize++;
return 1;
}
double Distance(struct vector v1,struct vector v2)
{
double d = 0.0;
double tem = 0.0;
for(int i = 0;i < NATTRS;i++)
tem += (v1.attributes[i]-v2.attributes[i])*(v1.attributes[i]-v2.attributes[i]);
d = sqrt(tem);
return d;
}
int max(struct item knn[]) //return the no. of the item which has biggest distance(
//should be replaced)
{
int maxNo = 0;
if(K > 1)
for(int i = 1;i < K;i++)
if(knn[i].distance>knn[maxNo].distance)
maxNo = i;
return maxNo;
}double Classify(struct vector v)//decide which class label will be assigned to
//a given input vetor with the knn method
{
double dd = 0;
int maxn = 0;
int freq[K];
double mfreqC = 0;//the class label appears most frequently
int i;
for(i = 0;i < K;i++)
knn[i].distance = MAXVALUE;
for(i = 0;i < curTSize;i++)
{
dd = Distance(trSet[i],v);
maxn = max(knn);//for every new state of the training set should update maxn
if(dd < knn[maxn].distance) {
knn[maxn].distance = dd;
knn[maxn].classlabel = trSet[i].classlabel;
}
}
for(i = 0;i < K;i++)//freq[i] represents knn[i].classlabel appears how many times
freq[i] = 1;
for(i = 0;i < K;i++)
for(int j = 0;j < K;j++)
if((i!=j)&&(knn[i].classlabel == knn[j].classlabel))
freq[i]+=1;
int mfreq = 1;
mfreqC = knn[0].classlabel;
for(i = 0;i < K;i++)
if(freq[i] > mfreq) {
mfreq = freq[i];//mfreq represents the most frepuences
mfreqC = knn[i].classlabel; //mfreqNo is the item no. with the most frequent
//classlabel
}
return mfreqC;
}
void main()
{ double classlabel;
double c;
double n;
struct vector trExmp;
int i;
ifstream filein("G:\\data\\for knn\\data.txt");
if(filein.fail()){cout<<"Can't open data.txt"<<endl; return;}
while(!filein.eof()) {
filein>>c;
trExmp.classlabel = c;
cout<<trExmp.classlabel<<" "; for(int i = 0;i < NATTRS;i++) {
filein>>n;
trExmp.attributes[i] = n;
cout<<trExmp.attributes[i]<<" ";
} cout<<endl;
if(!AddtoTSet(trExmp))
break;
}filein.close();struct vector testv={{142,188,11,1159,0.5513196},17};
classlabel = Classify(testv);
cout<<"The classlable of the testv is: ";
cout<<classlabel<<endl;
for(i = 0;i < K;i++)
cout<<knn[i].distance<<"\t"<<knn[i].classlabel<<endl;
//cout<<max(knn);
}
3. 你好,關於KNN演算法的maprece化
==================cluster.txt===========================
A 2 2
B 2 4
C 4 2
D 4 4
E 6 6
F 6 8
G 8 6
H 8 8
==================cluster.center.conf===========================
K1 3 2
K2 6 2
====================================================================================
package com.mahout.cluster;
//二維坐標的點
public class DmRecord {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private double xpodouble;
private double ypodouble;
public DmRecord(){
}
public DmRecord(String name,double x,double y){
this.name = name;
this.xpodouble = x;
this.ypodouble = y;
}
public double getXpoint() {
return xpodouble;
}
public void setXpoint(double xpodouble) {
this.xpodouble = xpodouble;
}
public double getYpoint() {
return ypodouble;
}
public void setYpoint(double ypodouble) {
this.ypodouble = ypodouble;
}
public double distance(DmRecord record){
return Math.sqrt(Math.pow(this.xpodouble-record.xpodouble, 2)+Math.pow(this.ypodouble-record.ypodouble, 2));
}
}
==============================================================================
package com.mahout.cluster;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.io.IOUtils;
public class DmRecordParser {
private Map<String,DmRecord> urlMap = new HashMap<String,DmRecord>();
/**
* 讀取配置文件記錄,生成對象
*/
public void initialize(File file) throws IOException {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
while ((line = in.readLine()) != null) {
String [] strKey = line.split("\t");
urlMap.put(strKey[0],parse(line));
}
} finally {
IOUtils.closeStream(in);
}
}
/**
* 生成坐標對象
*/
public DmRecord parse(String line){
String [] strPlate = line.split("\t");
DmRecord Dmurl = new DmRecord(strPlate[0],Integer.parseInt(strPlate[1]),Integer.parseInt(strPlate[2]));
return Dmurl;
}
/**
* 獲取分類中心坐標
*/
public DmRecord getUrlCode(String cluster){
DmRecord returnCode = null;
DmRecord dmUrl = (DmRecord)urlMap.get(cluster);
if(dmUrl == null){
//35 6
returnCode = null;
}else{
returnCode =dmUrl;
}
return returnCode;
}
}
==============================================================================
package com.mahout.cluster;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Recer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import com.mahout.test.StringStringPairAsce;
public class Kmeans extends Configured implements Tool {
public static class KmeansMapper extends MapReceBase implements
Mapper<LongWritable, Text, Text, Text> {
private DmRecordParser drp ;
private String clusterNode = "K";
private DmRecord record0 = null;
private DmRecord record1 = new DmRecord();
private double Min_distance = 9999;
private int tmpK = 0;
private Text tKey = new Text();
private Text tValue = new Text();
//獲取聚類中心坐標
@Override
public void configure(JobConf conf) {
drp = new DmRecordParser();
try {
drp.initialize(new File("cluster.center.conf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//根據聚類坐標,把文件中的點進行類別劃分
@Override
public void map(LongWritable key, Text value,
OutputCollector<Text, Text> output, Reporter arg3)
throws IOException {
String [] strArr = value.toString().split("\t");
for(int i=1; i <= 2; i++){
record0 = drp.getUrlCode("K"+i);
record1.setName(strArr[0]);
record1.setXpoint(Double.parseDouble(strArr[1]));
record1.setXpoint(Integer.parseInt(strArr[2]));
if(record0.distance(record1) < Min_distance){
tmpK = i;
Min_distance = record0.distance(record1);
}
}
tKey.set("C"+tmpK);
output.collect(tKey, value);
}
}
//計算新的聚類中心
public static class KmeansRecer extends MapReceBase implements
Recer<Text, Text, Text, Text> {
private Text tKey = new Text();
private Text tValue = new Text();
@Override
public void rece(Text key, Iterator<Text> value,
OutputCollector<Text, Text> output, Reporter arg3)
throws IOException {
double avgX=0;
double avgY=0;
double sumX=0;
double sumY=0;
int count=0;
String [] strValue = null;
while(value.hasNext()){
count++;
strValue = value.next().toString().split("\t");
sumX = sumX + Integer.parseInt(strValue[1]);
sumY = sumY + Integer.parseInt(strValue[1]);
}
avgX = sumX/count;
avgY = sumY/count;
tKey.set("K"+key.toString().substring(1,2));
tValue.set(avgX + "\t" + avgY);
System.out.println("K"+key.toString().substring(1,2)+"\t"+avgX + "\t" + avgY);
output.collect(tKey, tValue);
}
}
@Override
public int run(String[] args) throws Exception {
JobConf conf = new JobConf(getConf(), Kmeans.class);
conf.setJobName("Kmeans");
//conf.setNumMapTasks(200);
// 設置Map輸出的key和value的類型
conf.setMapOutputKeyClass(Text.class);
conf.setMapOutputValueClass(Text.class);
// 設置Rece輸出的key和value的類型
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
// 設置Mapper和Recer
conf.setMapperClass(KmeansMapper.class);
conf.setRecerClass(KmeansRecer.class);
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
// 設置輸入輸出目錄
FileInputFormat.setInputPaths(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
JobClient.runJob(conf);
return 0;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new Kmeans(), args);
System.exit(exitCode);
}
}
4. 你好,請問你現在有基於MapRece的knn演算法的Java代碼么謝謝~
14/09/0308:08:01INFOjvm.JvmMetrics:=JobTracker,sessionId=
14/09/0308:08:01WARNmapred.JobClient:..
14/09/0308:08:01WARNmapred.JobClient:Nojobjarfileset.Userclassesmaynotbefound.SeeJobConf(Class)orJobConf#setJar(String).
14/09/0308:08:02INFOinput.FileInputFormat:Totalinputpathstoprocess:1
14/09/0308:08:02INFOmapred.JobClient:Runningjob:job_local_0001
14/09/0308:08:02INFOinput.FileInputFormat:Totalinputpathstoprocess:1
14/09/0308:08:02INFOmapred.MapTask:io.sort.mb=100
14/09/0308:08:03INFOmapred.MapTask:databuffer=79691776/99614720
14/09/0308:08:03INFOmapred.MapTask:recordbuffer=262144/327680
14/09/0308:08:03WARNmapred.LocalJobRunner:job_local_0001
java.lang.ClassCastException:classPoint2D
atjava.lang.Class.asSubclass(Class.java:3018)
atorg.apache.hadoop.mapred.JobConf.getOutputKeyComparator(JobConf.java:599)
atorg.apache.hadoop.mapred.MapTask$MapOutputBuffer.<init>(MapTask.java:791)
atorg.apache.hadoop.mapred.MapTask$NewOutputCollector.<init>(MapTask.java:524)
atorg.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:613)
atorg.apache.hadoop.mapred.MapTask.run(MapTask.java:305)
atorg.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:177)
14/09/0308:08:03INFOmapred.JobClient:map0%rece0%
14/09/0308:08:03INFOmapred.JobClient:Jobcomplete:job_local_0001
14/09/0308:08:03INFOmapred.JobClient:Counters:0
5. knn演算法算是一種python模型嗎
「演算法」不能算是「模型」,更不能說是「python模型」,因為python能實現的,c++、java等通用語言也能實現。
6. knn是什麼意思
作為一種非參數的分類演算法,K-近鄰(KNN)演算法是非常有效和容易實現的。它已經廣泛應用於分類、回歸和模式識別等。
在應用KNN演算法解決問題的時候,要注意兩個方面的問題——樣本權重和特徵權重。利用SVM來確定特徵的權重,提出了基於SVM的特徵加權演算法(FWKNN,featureweightedKNN)。實驗表明,在一定的條件下,FWKNN能夠極大地提高分類准確率。
(6)knn演算法及java實現擴展閱讀:
KNN(K- Nearest Neighbor)法即K最鄰近法,最初由 Cover和Hart於1968年提出,是一個理論上比較成熟的方法,也是最簡單的機器學習演算法之一。該方法的思路非常簡單直觀:
如果一個樣本在特徵空間中的K個最相似(即特徵空間中最鄰近)的樣本中的大多數屬於某一個類別,則該樣本也屬於這個類別。該方法在定類決策上只依據最鄰近的一個或者幾個樣本的類別來決定待分樣本所屬的類別。
7. 什麼是knn演算法
作為一種非參數的分類演算法,K-近鄰(KNN)演算法是非常有效和容易實現的。它已經廣泛應用於分類、回歸和模式識別等。在應用KNN演算法解決問題的時候,要注意兩個方面的問題——樣本權重和特徵權重。利用SVM來確定特徵的權重,提出了基於SVM的特徵加權演算法(FWKNN,feature
weighted
KNN)。實驗表明,在一定的條件下,FWKNN能夠極大地提高分類准確率。
8. 怎樣在spark里跑java版的knn算
1、將KNN演算法調用Spark的api進行重寫。
2、然後就可以在sparkshell里運行了
9. knn演算法是什麼
KNN(K- Nearest Neighbor)法即K最鄰近法,最初由Cover和Hart於1968年提出,是一個理論上比較成熟的方法,也是最簡單的機器學習演算法之一。
作為一種非參數的分類演算法,K-近鄰(KNN)演算法是非常有效和容易實現的。它已經廣泛應用於分類、回歸和模式識別等。
介紹
KNN演算法本身簡單有效,它是一種lazy-learning演算法,分類器不需要使用訓練集進行訓練,訓練時間復雜度為0。KNN分類的計算復雜度和訓練集中的文檔數目成正比,也就是說,如果訓練集中文檔總數為n,那麼KNN的分類時間復雜度為O(n)。
KNN方法雖然從原理上也依賴於極限定理,但在類別決策時,只與極少量的相鄰樣本有關。由於KNN方法主要靠周圍有限的鄰近的樣本,而不是靠判別類域的方法來確定所屬類別的,因此對於類域的交叉或重疊較多的待分樣本集來說,KNN方法較其他方法更為適合。