这是个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可能性实例的更多相关文章

  1. 机器学习 MLIA学习笔记(二)之 KNN算法(一)原理入门实例

    KNN=K-Nearest Neighbour 原理:我们取前K个相似的数据(排序过的)中概率最大的种类,作为预测的种类.通常,K不会大于20. 下边是一个简单的实例,具体的含义在注释中: impor ...

  2. 机器学习 MLIA学习笔记(一)

    监督学习(supervised learning):叫监督学习的原因是因为我们告诉了算法,我们想要预测什么.所谓监督,其实就是我们的意愿是否能直接作用于预测结果.典型代表:分类(classificat ...

  3. 【机器学习实战学习笔记(1-2)】k-近邻算法应用实例python代码

    文章目录 1.改进约会网站匹配效果 1.1 准备数据:从文本文件中解析数据 1.2 分析数据:使用Matplotlib创建散点图 1.3 准备数据:归一化特征 1.4 测试算法:作为完整程序验证分类器 ...

  4. Android Studio 学习笔记(三):简单控件及实例

    控件.组件.插件概念区分 说到控件,就不得不区分一些概念. 控件(Control):编程中用到的部件 组件(Component):软件的组成部分 插件(plugin): 应用程序中已经预留接口的组件 ...

  5. 学习笔记(三)--->《Java 8编程官方参考教程(第9版).pdf》:第十章到十二章学习笔记

    回到顶部 注:本文声明事项. 本博文整理者:刘军 本博文出自于: <Java8 编程官方参考教程>一书 声明:1:转载请标注出处.本文不得作为商业活动.若有违本之,则本人不负法律责任.违法 ...

  6. Oracle学习笔记三 SQL命令

    SQL简介 SQL 支持下列类别的命令: 1.数据定义语言(DDL) 2.数据操纵语言(DML) 3.事务控制语言(TCL) 4.数据控制语言(DCL)  

  7. [Firefly引擎][学习笔记三][已完结]所需模块封装

    原地址:http://www.9miao.com/question-15-54671.html 学习笔记一传送门学习笔记二传送门 学习笔记三导读:        笔记三主要就是各个模块的封装了,这里贴 ...

  8. VSTO学习笔记(三) 开发Office 2010 64位COM加载项

    原文:VSTO学习笔记(三) 开发Office 2010 64位COM加载项 一.加载项简介 Office提供了多种用于扩展Office应用程序功能的模式,常见的有: 1.Office 自动化程序(A ...

  9. JavaScript学习笔记之数组(二)

    JavaScript学习笔记之数组(二) 1.['1','2','3'].map(parseInt) 输出什么,为什么? ['1','2','3'].map(parseInt)//[1,NaN,NaN ...

随机推荐

  1. Gcc ------ gcc的使用简介与命令行参数说明

    gcc的使用简介与命令行参数说明 2011年06月19日 20:29:00 阅读数:10221 2011-06-19 wcdj 参考:<GNU gcc嵌入式系统开发 作者:董文军> (一) ...

  2. 百度编辑器UEditor源码模式下过滤div/style等html标签

    UEditor在html代码模式下,当输入带有<div style="">.<iframe>这类带有html标签的内容时,切换为编辑器模式后,会发现输入的内 ...

  3. Biorhythms(中国剩余定理)

    http://shuxueshi.jie.blog.163.com/blog/static/13611628820104179856631/ 这篇博客写的很棒! #include<stdio.h ...

  4. [LeetCode] 104. Maximum Depth of Binary Tree_Easy tag: DFS

    Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the long ...

  5. keras搭建深度学习模型的一些小tips

    定义模型两种方法:  1.sequential 类仅用于层的线性堆叠,这是目前最常用的网络架构 2.函数式API,用于层组成的有向无环图,让你可以构建任意形式的架构 from keras import ...

  6. Oracle 错误代码小结

    ORA-00001: 违反唯一约束条件 (.) ORA-00017: 请求会话以设置跟踪事件 ORA-00018: 超出最大会话数 ORA-00019: 超出最大会话许可数 ORA-00020: 超出 ...

  7. SpringMVC学习笔记二第一个小的程序

    首先:我们要用springmvc来写一个helloworld的例子: 首先我们需要导入所需要的架包: /demo1/WebRoot/WEB-INF/lib/commons-logging-1.1.1. ...

  8. mysql的innodb存储引擎和myisam存储引擎的区别

    主要区别如下: 1.事务支持.innodb支持事务,事务(commit).回滚(rollback)和崩溃修复能力(crash recovery capabilities)的事务安全(transacti ...

  9. Keepalived保证Nginx高可用配置

    Keepalived保证Nginx高可用配置部署环境 keepalived-1.2.18 nginx-1.6.2 VM虚拟机redhat6.5-x64:192.168.1.201.192.168.1. ...

  10. Python: Pycharm简单介绍

    1. Pycharm是什么?                                                                                       ...