机器学习 MLIA学习笔记(三)之 KNN(二) Dating可能性实例
这是个KNN算法的另一实例,计算Dating的可能性。
import numpy as np
import os
import operator
import matplotlib
import matplotlib.pyplot as plt def classify(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]#lines num; samples num
diffMat = np.tile(inX, (dataSetSize,1)) - dataSet#dataSize*(1*inX)
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)#add as the first dim
distances = sqDistances**0.5
#return indicies array from min to max
#this is an array
sortedDistanceIndices = distances.argsort()
#classCount={}
classCount=dict() #define a dictionary
for i in range(k):
voteIlabel = labels[sortedDistanceIndices[i]]
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1#get(key,default=none)
#return a list like [('C',4),('B',3),('A',2)], not a dict
#itemgetter(0) is the 1st element
#default: from min to max
sortedClassCount = sorted(classCount.iteritems(),
key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0] def file2matrix(fileName):
fileHandler = open(fileName)
numberOfLines = len(fileHandler.readlines()) #get the number of lines in the file
returnMat = np.zeros((numberOfLines, 3)) #init a zero return matrix
classLabelVector = []
#classLabelVector = list() #will be used to record labels
fileHandler = open(fileName)
index = 0
for line in fileHandler.readlines():
line = line.strip() #strip blank characters
listFromLine = line.split('\t')
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(listFromLine[-1])
index += 1
return returnMat, classLabelVector #normalize data set
def autoNorm(dataSet):
minVal = dataSet.min(0)
maxVal = dataSet.max(0)
ranges = maxVal - minVal
normDataSet = np.zeros(np.shape(dataSet))
m = dataSet.shape[0]
normDataSet = dataSet - np.tile(minVal, (m,1))
normDataSet = normDataSet/np.tile(ranges, (m,1))
return normDataSet, ranges, minVal def showMatrix():
m,l = file2matrix("datingTestSet.txt")
m,r,mv = autoNorm(m)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(m[:,1],m[:,2])
plt.show() #calculate the error rate of sample
def calcErrorRate():
ratio = 0.1 #only use 10% samples to calc the error rate
matrix,l = file2matrix("datingTestSet.txt")
matrix,r,mv = autoNorm(matrix)
m = matrix.shape[0]
numTestSample = int(m*ratio)
errorCount = 0
for i in range(numTestSample):
classifyResult = classify(matrix[i,:], matrix[numTestSample:m,:],l[numTestSample:m],3)
print "the classifier came back with: %s, the real answer is: %s" % (classifyResult, l[i])
if (classifyResult != l[i]):
errorCount += 1
print "the total error rate is: %f" %(errorCount/float(numTestSample))
print errorCount def classifyPerson():
percentTats = float(raw_input(\
"percentage of time spent playing vedio games?"))
ffMiles = float(raw_input("frequent flier miles earned per year?"))
iceCream = float(raw_input("liters of ice cream consumed per year?"))
datingDataMat, datingLabels = file2matrix("datingTestSet.txt")
normMat, ranges, minVal = autoNorm(datingDataMat)
inArr = np.array([ffMiles, percentTats, iceCream])
classifyResult = classify((inArr-minVal)/ranges, normMat, datingLabels,3)
print "You will probaly like this person: ", classifyResult
机器学习 MLIA学习笔记(三)之 KNN(二) Dating可能性实例的更多相关文章
- 机器学习 MLIA学习笔记(二)之 KNN算法(一)原理入门实例
KNN=K-Nearest Neighbour 原理:我们取前K个相似的数据(排序过的)中概率最大的种类,作为预测的种类.通常,K不会大于20. 下边是一个简单的实例,具体的含义在注释中: impor ...
- 机器学习 MLIA学习笔记(一)
监督学习(supervised learning):叫监督学习的原因是因为我们告诉了算法,我们想要预测什么.所谓监督,其实就是我们的意愿是否能直接作用于预测结果.典型代表:分类(classificat ...
- 【机器学习实战学习笔记(1-2)】k-近邻算法应用实例python代码
文章目录 1.改进约会网站匹配效果 1.1 准备数据:从文本文件中解析数据 1.2 分析数据:使用Matplotlib创建散点图 1.3 准备数据:归一化特征 1.4 测试算法:作为完整程序验证分类器 ...
- Android Studio 学习笔记(三):简单控件及实例
控件.组件.插件概念区分 说到控件,就不得不区分一些概念. 控件(Control):编程中用到的部件 组件(Component):软件的组成部分 插件(plugin): 应用程序中已经预留接口的组件 ...
- 学习笔记(三)--->《Java 8编程官方参考教程(第9版).pdf》:第十章到十二章学习笔记
回到顶部 注:本文声明事项. 本博文整理者:刘军 本博文出自于: <Java8 编程官方参考教程>一书 声明:1:转载请标注出处.本文不得作为商业活动.若有违本之,则本人不负法律责任.违法 ...
- Oracle学习笔记三 SQL命令
SQL简介 SQL 支持下列类别的命令: 1.数据定义语言(DDL) 2.数据操纵语言(DML) 3.事务控制语言(TCL) 4.数据控制语言(DCL)
- [Firefly引擎][学习笔记三][已完结]所需模块封装
原地址:http://www.9miao.com/question-15-54671.html 学习笔记一传送门学习笔记二传送门 学习笔记三导读: 笔记三主要就是各个模块的封装了,这里贴 ...
- VSTO学习笔记(三) 开发Office 2010 64位COM加载项
原文:VSTO学习笔记(三) 开发Office 2010 64位COM加载项 一.加载项简介 Office提供了多种用于扩展Office应用程序功能的模式,常见的有: 1.Office 自动化程序(A ...
- JavaScript学习笔记之数组(二)
JavaScript学习笔记之数组(二) 1.['1','2','3'].map(parseInt) 输出什么,为什么? ['1','2','3'].map(parseInt)//[1,NaN,NaN ...
随机推荐
- loadrunner获取接口返回参数(包括body,headers等)
Action() { web_set_max_html_param_len("); // 默认最大长度为256 web_reg_save_param("ResponseBody&q ...
- 读书--编写高质量代码 改善C#程序的157个建议2
重新从图书馆将这本书借出来,看一遍似乎记不住,这次打算看一点就记录点,记录下自己容易忘记的知识点,便于记住. 建议1:正确使用字符串: 1 string str1= "hellowor ...
- JavaScript DOM2
1.Window.history:window.open打开网页的方式必须是_self window.history.back()后退 Window.history.forward()前进 <b ...
- CQRS/ES框架调研
1.Enode一个C#写的CQRS/ES框架,由汤雪华设计及实现,github上有相关源码,其个人博客上有详细的孵化.设计思路.版本迭代及最新的完善: 2.axon framwork,java编写,网 ...
- Storm集成Siddhi
<Siddhi初探>中我们介绍了Siddhi的基本使用方法,并表示我们将把Siddhi集成到Storm中作为流任务处理引擎.本文将用<Storm初探>中的例子讲解如何集成Sid ...
- 用rewrite把旧域名直接跳转到新域名的nginx配置
用rewrite把旧域名直接跳转到新域名的nginx配置 把下面代码保存到daziran.com.conf 放在nginx配置目录下 /etc/nginx/conf.d/ #把旧域名zdz8207直接 ...
- java commons.lang3 ArrayUtils使用
java commons.lang3 ArrayUtils使用import org.apache.commons.lang3.ArrayUtils; /** *数组追加数组,不重复 */ public ...
- php判断数组元素是否存在某个字符串的方法
php判断数组元素是否存在某个字符串的方法: 方法一:采用in_array(value,array,type) type 可选.如果设置该参数为 true,则检查搜索的数据与数组的值的类型是否相同. ...
- pyDay5
内容来自廖雪峰的官方网站 1.递归函数的优点是定义简单,逻辑清晰. 2.使用递归函数需要注意防止栈溢出. 3.在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会 ...
- php json_decode返回null
在使用json_decode函数想把json串转化为数组的时候,出现了null,当时还以为是因为json对字符串的长度有限制,还以为是因为两边少了引号,经过多次处理,发现都没有效果. 百度各种帖子,发 ...