机器学习 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 ...
随机推荐
- [wx]自然数学规律
有趣的数学规律 椭圆 双曲线 抛物线都叫圆锥曲线 它们跟圆锥有着怎样的关系? 他们都是圆锥与平面在不同姿势下交配的产物. 参考 椭圆 抛物线 小结 e: 离线率 P: 任意一点 F: 焦点 准线: 一 ...
- 安插,复制,替换和删除ul中的li
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- [LeetCode] 345. Reverse Vowels of a String_Easy tag:Two Pointers
Write a function that takes a string as input and reverse only the vowels of a string. Example 1: In ...
- 获取多达 16GB 的 Dropbox 免费空间!
Dropbox官网
- linux文件系统软链接硬链接
引子 目前,UNIX的文件系统有很多种实现,例如UFS(基于BSD的UNIX文件系统).ext3.ext4.ZFS和Reiserfs等等. 不论哪一种文件系统,总是需要存储数据.硬盘的最小存储单位是扇 ...
- ts实战项目启动中遇到的问题
项目链接:https://github.com/Jiasm/typescript-example 储备知识须知: sequelize入门篇 : 依照README执行以下操作: npm i brew s ...
- vue性能优化1--懒加载
懒加载也叫延迟加载,即在需要的时候进行加载.随用随载.为什么需要懒加载?像vue这种单页面应用,如果没有应用懒加载,运用webpack打包后的文件将会异常的大,造成进入首页时,需要加载的内容过多,时间 ...
- lnmp之阿里云源码安装mysql5.7.17
mysql5.7.17一直号称世界上最好的mysql 那么就在阿里云主机linux安装它(采用的源码安装mysql5.7.17) 我在阿里云主机上安装它 连接阿里云主机 进入,跟我们自己装的虚拟机一毛 ...
- Visual Studio 2013旗舰版KEY
Visual Studio 2013旗舰版KEY:BWG7X-J98B3-W34RT-33B3R-JVYW9
- 了解SpringBoot
一.SpringBoot是什么? Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发 ...