Peter Harrington, Machine learning, note,K最近邻(k-Nearest Neighbor,KNN)分类算法

最近开始看《机器学习实战》,作为python小白做一些笔记

语言: python2.7

IDE: pycharm

k近邻算法-程序清单

#!/usr/bin/python
# -*- coding:utf8 -*-
from numpy import *
import operator

def createDataSet():
    group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
    labels = ['A', 'A', 'B', 'B']
    return group, labels

def classify0(inX,dataSet,labels,k):
    dataSetSize=dataSet.shape[0]
    # 以下三行 距离计算
    diffMat=tile(inX,(dataSetSize,1))-dataSet
    sqDiffMat=diffMat**2
    sqDistances=sqDiffMat.sum(axis=1)
    distances=sqDistances**0.5
    sortedDistIndicies=distances.argsort()
    classCount={}
    # 以下两行 选择距离最小的k个点
    for i in range(k):
        voteIlabel=labels[sortedDistIndicies[i]]
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
        sortedClassCount=sorted(classCount.iteritems(),
        # 排序
        key=operator.itemgetter(1),reverse=True)
    return sortedClassCount[0][0]

sortedClassCount为[(类别,频数), (类别,频数), (类别,频数), ... ],按频数降序排列,类别见labels,频数为distance最小的k个值中某一label出现次数

sortedClassCount[0][0]返回最高频率类别

1.对numpy中shape的理解

from numpy import *
dataSet = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
print dataSet
dataSetSize=dataSet.shape[0]
print dataSet.shape[0]
print type(dataSet.shape[0])
print dataSet.shape[1]
print type(dataSet.shape[1])
print dataSet.shape
print type(dataSet.shape)
print (dataSetSize,1)
print type((dataSetSize,1))

运行结果

[[1.  1.1]
 [1.  1. ]
 [0.  0. ]
 [0.  0.1]]
4
<type 'long'>
2
<type 'long'>
(4L, 2L)
<type 'tuple'>
(4L, 1)
<type 'tuple'>

其中,对于tuple

>>> tup1=(1,2,0)
>>> tup2=(1)
>>> (tup1,2)
((1, 2, 0), 2)
>>> (tup2,2)
(1, 2)


2.numpy中的tile函数

import numpy
print numpy.tile([1,2],(3,4)) # [1,2]在行重复3次,列重复4次

运行结果

[[1 2 1 2 1 2 1 2]
 [1 2 1 2 1 2 1 2]
 [1 2 1 2 1 2 1 2]]

3.numpy中的sum函数

numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False)
print dataSet
print dataSet.sum(axis=0)
print dataSet.sum(axis=1)
# 当axis为0时,是压缩行,即将每一列的元素相加
# 当axis为1时,是压缩列,即将每一行的元素相加

运行结果

[[1.  1.1]
 [1.  1. ]
 [0.  0. ]
 [0.  0.1]]
[2.  2.2]
[2.1 2.  0.  0.1]

4.numpy中的argsort函数

返回升序下标

import numpy
help(numpy.argsort)

argsort(a, axis=-1, kind='quicksort', order=None)
    Returns the indices that would sort an array.
>>> x = np.array([[0, 3], [2, 2]])
    >>> x
    array([[0, 3],
           [2, 2]])
    
    >>> np.argsort(x, axis=0)  # sorts along first axis (down)
    array([[0, 1],
           [1, 0]])
    
    >>> np.argsort(x, axis=1)  # sorts along last axis (across)
    array([[0, 1],
           [0, 1]])

5.operator模块

>>> import operator
>>> help(operator)

6.字典的get函数

Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

dict.get(key, default=None)

>>> dict_data
	       
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> dict_data.get(1)
	       
'one'
>>> dict_data.get(5)
	       
>>> dict_data.get(5,0)
	       
0
>>> dict_data.get(5,'none')
	       
'none'

7.字典的items(),iteritems()

dict1 = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}

for key, values in dict1.items():
    print key, values

for key, values in dict1.iteritems():
    print key, values
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com

生成器


8.sorted()函数

sort 与 sorted 区别

sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作


9.operator.itemgetter函数

python中的operator.itemgetter函数

>>> score = [('john', 'A', 15), ('jane', 'C', 12), ('dave', 'B', 10),('alice','B',13),('kate', 'E', 2),('alice', 'D', 8)]
>>> sorted(score, key=operator.itemgetter(0),reverse=True)
[('kate', 'E', 2), ('john', 'A', 15), ('jane', 'C', 12), ('dave', 'B', 10), ('alice', 'B', 13), ('alice', 'D', 8)]
>>> sorted(score, key=operator.itemgetter(1),reverse=True)
[('kate', 'E', 2), ('alice', 'D', 8), ('jane', 'C', 12), ('dave', 'B', 10), ('alice', 'B', 13), ('john', 'A', 15)]
>>> sorted(score, key=operator.itemgetter(0,1),reverse=True)
[('kate', 'E', 2), ('john', 'A', 15), ('jane', 'C', 12), ('dave', 'B', 10), ('alice', 'D', 8), ('alice', 'B', 13)]
# 注意Alice

10.其它

>>> classCount={}
>>> type(classCount)
<class 'dict'>
>>> len(classCount)
0
>>> classCount
{}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值