knn算法(2)

1.下载测试数据地址

https://www.manning.com/books/machine-learning-in-action

中的 sourcecode


2.使用matplotlib绘制散点图

需要的函数  

1)figure 

   属于matplotlib.pyplot命名空间,用于获取一个主窗口,可以设置窗口的名称和尺寸

plt.figure(num='astronaut',figsize=(8,8))

2)add_subplot

     配置figure函数用于创建子窗口


import matplotlib
import matplotlib.pyplot as plt
from numpy import  *

x=[1,2,3]
y=[1,2,3]

fig=plt.figure()

ax=fig.add_subplot(111)

ax.plot(x,y)

plt.show()

knn算法(2)


3)绘制数据的散点图

  为了寻找规律,可以绘制散点图


 


from numpy import *
import operator
import pandas as pd
import matplotlib.pyplot as plt
from pandas import DataFrame,Series
def getDataSet():

    groups=array([[1.0,1.1],[0.8,0.8],[0.2,0.2],[0.4,0.4]])

    labels=['A','A','B','B']

    return groups,labels

'''
实现knn算法分类

'''

#读取文件中的数据

def file2matrix(filepath):

    try:

        fd=open(filepath,'r',encoding='utf-8')

        lines=fd.readlines()

        resultMatrix = zeros((len(lines), 3))#zeros((a,b))

        labelList = []

        index = 0

        for line in lines:
            line = line.strip()
            items = line.split('\t')
            resultMatrix[index] = items[:3]
            labelList.append(int(items[-1]))
            index += 1
        return resultMatrix, labelList




    except Exception as e:

        print("exception",e)
    finally:
        fd.close()



#自动规整
def autoUniform(dataset):

    #获取列的最大值和最小值
    minVal=dataset.min(0)
    maxVal=dataset.max(0)
    rangeVal=maxVal-minVal
    #初始化结果矩阵
    resultMatrix=zeros((dataset.shape[0],dataset.shape[1]))
    #输入矩阵的每个值减去最小值
    resultMatrix=dataset-tile(minVal,(dataset.shape[0],1))
    #上面结果每个值除以最大值和最小值的范围
    resultMatrix=resultMatrix/tile(rangeVal,(dataset.shape[0],1))
    return resultMatrix,rangeVal,minVal

def classify0(Intx,DataSet,Labels,k):
     #计算每行的数据跟测试数据之间的距离
     #为了使用矩阵运算,先扩展测试数据,由原来的a[1,n] 扩展到a[size,n]
     rowSize=DataSet.shape[0]
     print('rowsize=',rowSize)
     extendIntx=tile(Intx,(rowSize,1))
     print(DataSet-extendIntx)
     # ((a1-b1)^2+(a2-b2)^2)^(1/2)

     distances=(DataSet-extendIntx)**2

     print(distances)

     print(distances.sum(1))
     distances=(distances.sum(1))**0.5
     print(distances)
     #排序
     distancesIndex=distances.argsort()
     print(distancesIndex)
     #取前k个距离最近的,对应的标签,统计出现的次数
     counts={}
     for i in range(k):

         label=Labels[distancesIndex[i]]


         '''
         if  not label in counts:
             counts[label]=1
         else:
             counts[label] = counts[label]+1
         '''
         counts[label]=counts.get(label,0)+1

     print(counts)
     afterSorted=sorted(counts.items(),key=operator.itemgetter(1),reverse=True)

     #print(afterSorted[0][0])

     return afterSorted[0][0]



 

import knn
import os
from numpy import *
filepath='/python/machinelearninginaction/Ch02/datingTestSet2.txt'

resultMatrix, labelList=knn.file2matrix(filepath)

resultMatrix,rangeVal,minVal=knn.autoUniform(resultMatrix)

print(resultMatrix)

Indx=[14488,7.153469,1.673904]

autoUniformIndx=(Indx-minVal)/rangeVal

resultClass=knn.classify0(autoUniformIndx,resultMatrix,labelList,3)

print(resultClass)

  

 

引入其它模块中的内容:


同一个文件夹下:

import xx

xx.method()

不同路径下:

import sys  

sys.path.append(r'E:\PythonProject\winycg')  

'''''python import模块时, 是在sys.path里按顺序查找的。 

sys.path是一个列表,里面以字符串的形式存储了许多路径。 

使用A.py文件中的函数需要先将他的文件路径放到sys.path'


出自《机器学习实战》:


knn算法的优缺点:

knn算法(2)