KNN分类算法Python实现
来源:互联网 发布:c语言volatile的作用 编辑:程序博客网 时间:2024/06/04 23:03
from numpy import *import operator# inputX - the input sample; dataset - sample dataset; labels - labels of the sample dataset; k is the number of nearest samples used in the classifier def knn_classify(inputX, dataset, labels, k): # number of sample in dataset num = dataset.shape[0] diffMat = tile(inputX, (num, 1)) - dataset sqDiffMat = diffMat**2 sqDistances = sqDiffMat.sum(axis=1) distances = sqDistances**0.5 sortedIndicies = distances.argsort() voteCount={} for i in range(k): voteLabel = labels[sortedIndicies[i]] voteCount[voteLabel] = voteCount.get(voteLabel, 0) + 1 #sortedVoteCount = sorted(viteCount.iteritems(), key = lambda dic:dic[1], reverse = True) sortedVoteCount = sorted(voteCount.iteritems(), key = operator.itemgetter(1), reverse = True) return sortedVoteCount[0][0]# read dataset from file, each line in file is a sample, three features and one labeldef file2matrix(filename): file = open(filename) arrayOfLines = file.readlines() numOfLines = len(arrayOfLines) numOfFeatures = 3 dataset = zeros((numOfLines, numOfFeatures)) labelVector = [] index = 0 for line in arrayOfLines: line = line.strip() sample = line.split('\t') dataset[index,:] = sample[0:numOfFeatures] labelVector.append(int(sample[-1])) index = index + 1 return dataset, labelVector
0 0
- Python实现kNN分类算法
- kNN分类算法python实现
- KNN分类算法Python实现
- 用python实现kNN分类算法
- Python实现KNN算法项目 --- 水果分类
- KNN最邻近规则分类算法实践实现【Python实现】
- 【python 编程】文本分类KNN算法实现及结果输出
- python 实现 knn分类算法 (Iris 数据集)
- Python实现K近邻算法<KNN>_分类器
- KNN(k-近邻)分类算法讲解与实现(python)
- KNN 图像分类python实现
- KNN分类算法的实现
- KNN-分类算法的实现
- KNN分类算法java实现
- 从零开始实现KNN分类算法
- Python实现KNN算法
- KNN算法Python实现
- python实现knn算法
- 一个人写界面有点写累了
- Golang1.7.4标准库sql使用
- CURL使用
- Storm-JDBC 中Date类型转换bug
- python+selenium常用函数
- KNN分类算法Python实现
- OpenCV使用小结
- 1-2交互 vue-resouce
- flask部署-Ubuntu下使用nginx+uwsgi+supervisor部署flask应用
- 邮票分你一半
- Android源码/框架源码分析
- 2017年上半年(2月-9月个人学习计划)
- 8.10.3.1 How the Query Cache Operates
- 如何快速对系统重启问题进行归类