这是个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. 【Cocos2dx 3.3 Lua】触屏事件

    cocos2dx 3.x触屏时间分为单点触摸和多点触摸:     单点触摸:(即只有注册的Layer才能接收触摸事件)      多点触摸点单用法(多个Layer获取屏幕事件):           ...

  2. [LeetCode] 114. Flatten Binary Tree to Linked List_Medium tag: DFS

    Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 ...

  3. [LeetCode] 394. Decode String_Medium tag: stack 666

    Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], where ...

  4. javascript console自动点击页面元素

    原文地址https://jingyan.baidu.com/article/0a52e3f41c0b0abf63ed726d.html 这里拿百度音乐VIP兑换页面来做演示. 首先打开百度音乐VIP兑 ...

  5. 软件包管理:rpm包管理-yum在线管理-IP地址配置和网络yum源

    只需告诉系统你想安装那个包,剩下的所有依赖问题yum都会解决. 有些情况下不能上网,但可以使用光盘. centos的yum是免费的.redhatyum付费. yum管理的其实同样是rpm包.并没有yu ...

  6. 树结构数据的展示和编辑-zTree树插件的简单使用

    最近在项目当中遇到一个需求,需要以树结构的方式展示一些数据,并可对每一个树节点做内容的编辑以及树节点的添加和删除,刚好听说有zTree这个插件可以实现这样的需求,所以在项目的这个需求完成之后,在博客里 ...

  7. 你真的了解[super ]关键字吗?

    前言 此篇文章是看了阮老师的es6教程,看到super关键字的时候觉得有必要总结梳理一下,原文还是参考 ECMAScript 6入门. 正文 super 这个关键字,既可以当作函数使用,也可以当作对象 ...

  8. 模仿WIN32程序处理消息

    #include "stdafx.h" #include "MyMessage.h" #include <conio.h> using namesp ...

  9. SQL 中【NULL】和【无】烦躁的问题

    很烦躁,烦躁的很,总结一下. 先简单的说下: NULL   : 不确定的东西 无       :没有东西 复杂的见下文....... 一 .null值 下面举个最简单的例子,平常工作当中肯定比这个sq ...

  10. 每天一个Linux命令(1)ls命令

    ls是list的缩写,ls命令是Linux系统下最常用的命令之一. ls命令用于打印当前目录的清单,如果指定其它目录,那么就会显示其他目录的文件及文件夹的清单. 通过ls 命令还可以查看文件其它的详细 ...