Machine Learning in Action_CH2_1_kNN
来源:互联网 发布:java poi maven 编辑:程序博客网 时间:2024/05/22 16:04
from numpy import *import operatordef createDataBase(): group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) # numpy向量 labels = ['A', 'A', 'B', 'B'] # 列表 return group, labelsdef classify0(inX, dataSet, labels, k): dataSetSize = dataSet.shape[0] # 获得向量第一维长度 diffMat = tile(inX, (dataSetSize, 1)) - dataSet # 纵向扩大dataSetSize倍 sqDiffMat = diffMat ** 2 sqDistances = sqDiffMat.sum(axis = 1) # 按行求和 distances = sqDistances ** 0.5 sortedDistIndicies = distances.argsort() # 从小到大排序,返回的是索引值的列表 classCount = {} # python字典 for i in range(k): voteIlabel = labels[sortedDistIndicies[i]] classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # 数频度,每次加1 # 对字典进行排序 # Python 2 才能使用classCount.iteritems() sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True) return sortedClassCount[0][0]if __name__ == '__main__': # arr = array([[1, 2, 3, 4], [5, 6, 7, 8]]) # print(arr.shape) # matrix = mat(arr) # print(matrix.shape) # print(array([[1, 2],[3, 4]])) # print(array([(1, 2), (3, 4)])) # a = array([1, 2]) # print(a.dtype) # a = [1, 2, 3, 4] # print(tile(a, 2)) group, labels = createDataBase() print(classify0([0, 0], group, labels, 3)) # 输出B
1 0
- Machine Learning in Action_CH2_1_kNN
- Thinking In Machine Learning
- machine learning in R
- machine learning in action
- Hyperparameters in Machine Learning
- Machine Learning in Python
- Machine Learning in Action
- Machine Learning in iOS
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Math in machine learning
- Android中远程Service和Activity交互
- Httpservlet cannot be resolved to a type的原因与解决方法
- DAY 2 HTML作诗
- virtualenv
- systemctl命令
- Machine Learning in Action_CH2_1_kNN
- 最大和子矩阵
- js中对象的内部原型和构造器原型对象的深入剖析
- 【IMWeb训练营作业】 --- todo list
- 网易校园招聘dp题
- Go实战--net/http中JSON的使用(The way to go)
- k-近邻算法(k-NN)及其Python实现
- python装饰器
- 17-4-19 代码