資源簡介
knn算法的c代碼,支持從文件從讀取數據,支持不同維度,測試正確,非常有用!
代碼片段和文件信息
#include
#include
#include
#define?K?3?//近鄰數k
typedef?float?type;
//動態創建二維數組
type?**createarray(int?nint?m)
{
int?i;
type?**array;
array=(type?**)malloc(n*sizeof(type?*));
array[0]=(type?*)malloc(n*m*sizeof(type));
for(i=1;i ????return?array;
}
//讀取數據,要求首行格式為?N=數據量D=維數
void?loaddata(int?*nint?*dtype?***arraytype?***karray)
{
int?ij;
FILE?*fp;
if((fp=fopen(“data.txt““r“))==NULL) fprintf(stderr“can?not?open?data.txt!\n“);
if(fscanf(fp“N=%dD=%d“nd)!=2) fprintf(stderr“reading?error!\n“);
*array=createarray(*n*d);
*karray=createarray(2K);
????for(i=0;i<*n;i++)
for(j=0;j<*d;j++)
fscanf(fp“%f“&(*array)[i][j]);????//讀取數據
for(i=0;i<2;i++)
for(j=0;j (*karray)[i][j]=9999.0;????//默認的最大值
if(fclose(fp)) fprintf(stderr“can?not?close?data.txt“);
}
//計算歐氏距離
type?computedistance(int?ntype?*avectortype?*bvector)
{
????int?i;
????type?dist=0.0;
????for(i=0;i ????????dist+=pow(avector[i]-bvector[i]2);
????return?sqrt(dist);
}
//冒泡排序
void?bublesort(int?ntype?**aint?choice)
{
????int?ij;
????type?k;
????for(j=0;j ????????for(i=0;i ????????????if(0==choice){
????????????????if(a[0][i]>a[0][i+1]){
????????????????????k=a[0][i];
????????????????????a[0][i]=a[0][i+1];
????????????????????a[0][i+1]=k;
????????????????????k=a[1][i];
????????????????????a[1][i]=a[1][i+1];
????????????????????a[1][i+1]=k;
????????????????}
????????????}
????????????else?if(1==choice){
????????????????if(a[1][i]>a[1][i+1]){
????????????????????k=a[0][i];
????????????????????a[0][i]=a[0][i+1];
????????????????????a[0][i+1]=k;
????????????????????k=a[1][i];
????????????????????a[1][i]=a[1][i+1];
????????????????????a[1][i+1]=k;
????????????????}
????????????}
????????}
}
//統計有序表中的元素個數
type?orderedlist(int?ntype?*list)
{
????int?icount=1maxcount=1;
????type?value;
????for(i=0;i<(n-1);i++)?{
????????if(list[i]!=list[i+1])?{
????????????//printf(“count?of?%d?is?value?%d\n“list[i]count);
????????????if(count>maxcount){
????????????????maxcount=count;
????????????????value=list[i];
????????????????coun
評論
共有 條評論