机器学习 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
时间: 2024-08-10 23:28:30

机器学习 MLIA学习笔记(三)之 KNN(二) Dating可能性实例的相关文章

马哥学习笔记三十二——计算机及操作系统原理

缓存方式: 直接映射 N路关联 缓存策略: write through:通写 write back:回写 进程类别: 交互式进程(IO密集型) 批处理进程(CPU密集型) 实时进程(Real-time) CPU: 时间片长,优先级低IO:时间片短,优先级高 Linux优先级:priority 实时优先级: 1-99,数字越小,优先级越低 静态优先级:100-139,数据越小,优先级越高 实时优先级比静态优先级高 nice值:调整静态优先级   -20,19:100,139   0:120 ps

【Unity 3D】学习笔记三十二:游戏元素——游戏光源

游戏光源 在3D游戏中,光源是一个非常具有特色的游戏组件.用来提升游戏画面质感的.如果没有加入光源,游戏场景可能就会显得很昏暗.在unity中提供了三种不同的光源类型:点光源,聚光灯,平行光. 点光源 顾名思义,点光源是从一个点向周围散发出光的光源,就像电灯一样.创建点光源在hierarchy视图中点击create--point light: 创建完以后,点击点光源对象,在右侧inspector视图中可以看到点光源的所有信息: type:光源的类型.有point(点光源),directional

NFC学习笔记——三(在windows操作系统上安装libnfc)

本篇翻译文章: 这篇文章主要是说明如何在windows操作系统上安装.配置和使用libnfc. 一.基本信息 1.操作系统: Windows Vista Home Premium SP 2 2.硬件信息: System: Dell Inspiron 1720 Processor: Intel Core 2 Duo CPU T9300 @ 2.5GHz 2.5GHz System type: 32-bit Operating System 3.所需软件: 在windows操作系统上安装软件需要下列

swift学习笔记(三)关于拷贝和引用

在swift提供的基本数据类型中,包括Int ,Float,Double,String,Enumeration,Structure,Dictionary都属于值拷贝类型. 闭包和函数同属引用类型 捕获则为拷贝.捕获即定义这些常量和变量的原作用域已不存在,闭包仍然可以在闭包函数体内引用和修改这些值 class属于引用类型. Array的情况稍微复杂一些,下面主要对集合类型进行分析: 一.关于Dictionary:无论何时将一个字典实例赋给一个常量,或者传递给一个函数方法时,在赋值或调用发生时,都会

机器学习实战学习笔记(一)

1.k-近邻算法 算法原理: 存在一个样本数据集(训练样本集),并且我们知道样本集中的每个数据与其所属分类的对应关系.输入未知类别的数据后将新数据的每个特征与样本集中数据对应的特征进行比较,然后算法提取样本集中特征最相似(最近邻)的k组数据.然后将k组数据中出现次数最多的分类,来作为新数据的分类. 算法步骤: 计算已知类别数据集中的每一个点与当前点之前的距离.(相似度度量) 按照距离递增次序排序 选取与当前点距离最小的k个点 确定k个点所在类别的出现频率 返回频率最高的类别作为当前点的分类 py

Object C学习笔记26-文件管理(二)

上一篇简单的介绍了如何获取文件属性,删除,拷贝文件等,本文继续记录Object C中文件IO操作. 一. 获取文件的执行主目录 在Object C中提供了一个方法 NSHomeDirectory() 用于获得执行执行的主目录,使用如下代码测试: NSString *homePath=NSHomeDirectory(); NSLog(@"执行文件的主目录:%@",homePath); 通过以上代码可以正确的输出应用程序的执行目录,上一张也提到了文件的目录问题,这个和Windows系统的有

Oracle学习笔记三 SQL命令

SQL简介 SQL 支持下列类别的命令: 1.数据定义语言(DDL) 2.数据操纵语言(DML) 3.事务控制语言(TCL) 4.数据控制语言(DCL)               下面是这四种SQL语言的详细笔记: Oracle学习笔记三 SQL命令(二):SQL操作语言类别 Oracle数据类型 创建表时,必须为各个列指定数据类型 以下是 Oracle 数据类型的类别: 字符数据类型 CHAR类型 当需要固定长度的字符串时,使用 CHAR 数据类型. CHAR 数据类型存储字母数字值. CH

Silverlight动画学习笔记(三):缓动函数

(一)定义: 缓动函数:可以将自定义算术公式应用于动画 (二)为什么要用缓动函数: 您可能希望某一对象逼真地弹回或其行为像弹簧一样.您可以使用关键帧动画甚至 From/To/By 动画来大致模拟这些效果,但可能需要执行大量的工作,并且与使用算术公式相比动画的精确性将降低. (三)实例讲解: 1 <UserControl x:Class="AnimationStudy.EasingFunctionAnimation" 2 xmlns="http://schemas.mic

马程序员学习笔记——红黑树解析二

---------------------- ASP.Net+Unity开发..Net培训.期待与您交流! ---------------------- 四.树中删除元素 1.先找到需要删除的元素. 2. 2.1如果被删元素没有子元素,那么直接用NIL节点代替他: 2.2如果被删元素只有一个子元素,那么直接用这个子元素代替他: 2.3如果被删元素有两个子元素,那么就用左子元素中的最大元素或者右子元素的最小元素代替他. 比如说原来要删除的元素是N,N有两个分支,其中P是N左分支中的最大元素,那么就