#!/usr/bin/env python
# coding: utf-8
'''
Created on Nov 19,2018
Author: Shanjianwu
GitHub: https://github.com/shanjianwu/kNN---/new/master
'''

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): #四个输入参数：用于分类的输入向量inX, 输入的训练集
    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.items(), #错误1：python3中没有iteritems，用items代替
                              key = operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

#处理输入格式问题,将文本记录转换为NumPy的解析程序
def file2matrix(filename):
    fr = open(filename)
    arrayOLines = fr.readlines()
    numberOfLines = len(arrayOLines) #得到文件行数
    returnMat = zeros((numberOfLines, 3)) #创建返回的Numpy矩阵
    classLabelVector = []
    index = 0
    for line in arrayOLines:  #解析文件数据到列表
        line = line.strip()  #截取掉所有的回车字符
        listFromLine = line.split('\t')
        returnMat[index, :] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat, classLabelVector

#归一化函数，自动将数字特征值转化为0到1之间的区间
def autoNorm(dataSet):
    minVals = dataSet.min(0)
    maxVals = dataSet.max(0)
    ranges = maxVals - minVals
    normDataSet = zeros(shape(dataSet))
    m = dataSet.shape[0]
    normDataSet = dataSet - tile(minVals, (m,1)) #在列方向上重复minVals一次，在行方向上重复m次
    normDataSet = normDataSet/tile(ranges, (m,1))
    return normDataSet, range, minVals

#分类器，测试算法
def datingClassTest():
    hoRatio = 0.10
    datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
    normMat, ranges, minVals = autoNorm(datingDataMat)
    m = normMat.shape[0] #计算测试向量的数量
    numTestVecs = int(m*hoRatio)
    errorCount = 0.0
    for i in range(numTestVecs):
        classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],
                                     datingLabels[numTestVecs:m],3)
        print('the classifier came back with :%d,the real answer is:%d'%(classifierResult,datingLabels[i]))
        if (classifierResult != datingLabels[i]):
            errorCount += 1.0
    print('the total error rate is:%f'%(errorCount/float(numTestVecs)))

#使用算法
def classifyPerson():
    resultList = ['not at all', 'in small dosses', 'in large doses']
    percentTats = float(input("percentage of time spent playing video games?"))
    ffMiles = float(input('frequent filter miles earned per year?'))
    iceCream = float(input('liters of ice cream consumed per year?'))
    datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
    normMat,ranges, minVals = autoNorm(datingDataMat)
    inArr = array([ffMiles, percentTats, iceCream])
    classifierResult = classify0(int(inArr-minVals)/int(ranges), normMat, datingLabels, 3)
    print('You will probably like this person:',resultList[classifierResult - 1])
