+/OCR
character recognition demo
git clone https://git.julia.blue/+/OCR
10501ef
master
1from collections import Counter 2 3 4def load (fileName ): 5f = open (fileName ) 6lines = [[int (i )for i in l .rstrip ('\n' ).replace (" " ,"" ).split ("," )]for l in f ] 7f .close () 8return lines 9 10 11def euclideanDistance (a ,b ): 12return sum ([(a [i ]- b [i ])** 2 for i in range (len (a ))])** .5 13 14 15def euclideanDistanceWeighted (a ,b ,w ): 16return sum ([(a [i ]- b [i ])** 2 * w [i ]for i in range (len (a ))])** .5 17 18 19def getNeighborData (dataSet ,instance ): 20return sorted ([(euclideanDistance (instance ,i ),i )for i in dataSet ])[0 ][- 1 ] 21 22 23def getNeighborDataWeighted (dataSet ,instance ,weights ): 24return sorted ([(euclideanDistance (instance ,i ,weights ),i )for i in dataSet ])[0 ][- 1 ] 25 26 27def getNeighbors (dataSet ,instance ,k ): 28return sorted ([(euclideanDistance (instance ,i ),i [- 1 ])for i in dataSet ])[:k ] 29 30 31def getNeighborsWeighted (dataSet ,instance ,k ,weights ): 32return sorted ([(euclideanDistanceWeighted (instance ,i ,weights ),i [- 1 ])for i in dataSet ])[:k ] 33 34 35def predictLabel (dataSet ,instance ,k ): 36return Counter ([i [- 1 ]for i in getNeighbors (dataSet ,instance ,k )]).most_common ()[0 ][0 ] 37 38 39def predictLabelWeighted (dataSet ,instance ,k ,weights ): 40return Counter ([i [- 1 ]for i in getNeighborsWeighted (dataSet ,instance ,k ,weights )]).most_common ()[0 ][0 ]