python knn自我实践
#得到分类数据和测试数据 import pymysql import struct from numpy import * a=['']*20 #存图像 分类数据 b=[[0]*76800]*20#存图像 分类数据 c=[0]*76800#存图像 测试数据 def connectSql_1(): conn = pymysql.connect(host='192.168.9.163', user='hlyxtmi', passwd='19560530', db='tmi-ds', charset="latin1") cur = conn.cursor() cur.execute("select type,imagedata from knn_test where type != ''") results = cur.fetchall() i=0 for row in results: d = [0] * 76800 a[i] = row[0] imagedata = row[1] for num in range(76800): str = imagedata[(num+4)*2:(num+5)*2] d[num] = struct.unpack('h', str) b[i]=d i+=1 cur.close() conn.close() def connectSql_2(): conn = pymysql.connect(host='192.168.9.163', user='hlyxtmi', passwd='19560530', db='tmi-ds', charset="latin1") cur = conn.cursor() cur.execute("select imagedata from knn_test where type = ''") results = cur.fetchall() for row in results: imagedata = row[0] for num in range(76800): str = imagedata[(num+4)*2:(num+5)*2] c[num] = struct.unpack('h', str) cur.close() conn.close() def classify(): s=[0]*20 #存距离 for num in range(20): for i in range(76800): aTmp = b[num][i][0] bTmp = c[i][0] cTmp = aTmp - bTmp s[num]+= abs(cTmp) print(num) sortedDisIndex = argsort(s) classCount={} for i in range(19): voteLabel = a[sortedDisIndex[i]] classCount[voteLabel] = classCount.get(voteLabel,0) + 1 maxCount = 0 for key,value in classCount.items(): if value > maxCount: maxCount = value classes = key return classes if __name__ == '__main__': connectSql_1() connectSql_2() output = classify() print("分类结果为:",output)