www.pudn.com > means.rar > myk-means.cpp, change:2007-02-11,size:1792b


#include "myk-means.h" 
#include <fstream> 
#include <cmath> 
using namespace std; 
 
void kmeans::initial(string fileName,int clusterNum) 
{ 
	getData(fileName); 
	if(data.size()<clusterNum) 
		numOfCluster = data.size(); 
	else 
		numOfCluster = clusterNum; 
	center.resize(clusterNum,-1); 
	cluster.resize(clusterNum); 
} 
 
void kmeans::getData(string fileName) 
{ 
	ifstream in; 
	in.open(fileName.c_str(),ios::in); 
	if(!in.is_open()) 
	{ 
		cout<<"open file failed!"; 
		exit(0); 
	} 
	int size; 
	in>>size; 
	for(int i=0;i<size;i++) 
	{ 
		double temp; 
		in>>temp; 
		data.push_back(temp); 
	} 
	in.close(); 
} 
 
void kmeans::distribute() 
{ 
	for(int i=0;i<numOfCluster;i++) 
		cluster[i].clear(); 
	for(int i=0;i<data.size();i++) 
	{ 
		int location = findCloset(data[i]); 
		cluster[location].insert(data[i]); 
	} 
} 
 
int kmeans::findCloset(double t) 
{ 
	int location=0; 
	double delta=9.9e+20; 
 
	for(int i=0;i<numOfCluster;i++) 
	{ 
		if(fabs(center[i]-t)<delta) 
		{ 
			delta = fabs(center[i]-t); 
			location = i; 
		} 
	} 
	return location; 
} 
 
bool kmeans::findNewCenter() 
{ 
	bool again = false; 
	for(int i=0;i<numOfCluster;i++) 
	{ 
		double avg=0; 
		int size = cluster[i].size(); 
		set<double>::iterator ite = cluster[i].begin(); 
		while(ite!=cluster[i].end()) 
		{ 
			avg = avg + (*ite)/size; 
			ite++; 
		} 
		if(avg!=center[i]) 
		{ 
			center[i]=avg; 
			again=true; 
		} 
	} 
	return again; 
} 
 
void kmeans::print() 
{ 
	ofstream cout("mean.txt",ios::out); 
	for(int i=0;i<numOfCluster;i++) 
	{ 
		cout<<"cluster  "<<i+1<<':'<<endl; 
		cout<<"center  "<<center[i]<<endl; 
		set<double>::iterator ite = cluster[i].begin(); 
		while(ite!=cluster[i].end()) 
		{ 
			cout<<(*ite)<<' '; 
			ite++; 
		} 
		cout<<endl<<endl<<endl; 
	} 
	//cout.close(); 
}