letter_recog.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #!/usr/bin/env python
  2. '''
  3. The sample demonstrates how to train Random Trees classifier
  4. (or Boosting classifier, or MLP, or Knearest, or Support Vector Machines) using the provided dataset.
  5. We use the sample database letter-recognition.data
  6. from UCI Repository, here is the link:
  7. Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998).
  8. UCI Repository of machine learning databases
  9. [http://www.ics.uci.edu/~mlearn/MLRepository.html].
  10. Irvine, CA: University of California, Department of Information and Computer Science.
  11. The dataset consists of 20000 feature vectors along with the
  12. responses - capital latin letters A..Z.
  13. The first 10000 samples are used for training
  14. and the remaining 10000 - to test the classifier.
  15. ======================================================
  16. USAGE:
  17. letter_recog.py [--model <model>]
  18. [--data <data fn>]
  19. [--load <model fn>] [--save <model fn>]
  20. Models: RTrees, KNearest, Boost, SVM, MLP
  21. '''
  22. # Python 2/3 compatibility
  23. from __future__ import print_function
  24. import numpy as np
  25. import cv2 as cv
  26. def load_base(fn):
  27. a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
  28. samples, responses = a[:,1:], a[:,0]
  29. return samples, responses
  30. class LetterStatModel(object):
  31. class_n = 26
  32. train_ratio = 0.5
  33. def load(self, fn):
  34. self.model = self.model.load(fn)
  35. def save(self, fn):
  36. self.model.save(fn)
  37. def unroll_samples(self, samples):
  38. sample_n, var_n = samples.shape
  39. new_samples = np.zeros((sample_n * self.class_n, var_n+1), np.float32)
  40. new_samples[:,:-1] = np.repeat(samples, self.class_n, axis=0)
  41. new_samples[:,-1] = np.tile(np.arange(self.class_n), sample_n)
  42. return new_samples
  43. def unroll_responses(self, responses):
  44. sample_n = len(responses)
  45. new_responses = np.zeros(sample_n*self.class_n, np.int32)
  46. resp_idx = np.int32( responses + np.arange(sample_n)*self.class_n )
  47. new_responses[resp_idx] = 1
  48. return new_responses
  49. class RTrees(LetterStatModel):
  50. def __init__(self):
  51. self.model = cv.ml.RTrees_create()
  52. def train(self, samples, responses):
  53. self.model.setMaxDepth(20)
  54. self.model.train(samples, cv.ml.ROW_SAMPLE, responses.astype(int))
  55. def predict(self, samples):
  56. _ret, resp = self.model.predict(samples)
  57. return resp.ravel()
  58. class KNearest(LetterStatModel):
  59. def __init__(self):
  60. self.model = cv.ml.KNearest_create()
  61. def train(self, samples, responses):
  62. self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
  63. def predict(self, samples):
  64. _retval, results, _neigh_resp, _dists = self.model.findNearest(samples, k = 10)
  65. return results.ravel()
  66. class Boost(LetterStatModel):
  67. def __init__(self):
  68. self.model = cv.ml.Boost_create()
  69. def train(self, samples, responses):
  70. _sample_n, var_n = samples.shape
  71. new_samples = self.unroll_samples(samples)
  72. new_responses = self.unroll_responses(responses)
  73. var_types = np.array([cv.ml.VAR_NUMERICAL] * var_n + [cv.ml.VAR_CATEGORICAL, cv.ml.VAR_CATEGORICAL], np.uint8)
  74. self.model.setWeakCount(15)
  75. self.model.setMaxDepth(10)
  76. self.model.train(cv.ml.TrainData_create(new_samples, cv.ml.ROW_SAMPLE, new_responses.astype(int), varType = var_types))
  77. def predict(self, samples):
  78. new_samples = self.unroll_samples(samples)
  79. _ret, resp = self.model.predict(new_samples)
  80. return resp.ravel().reshape(-1, self.class_n).argmax(1)
  81. class SVM(LetterStatModel):
  82. def __init__(self):
  83. self.model = cv.ml.SVM_create()
  84. def train(self, samples, responses):
  85. self.model.setType(cv.ml.SVM_C_SVC)
  86. self.model.setC(1)
  87. self.model.setKernel(cv.ml.SVM_RBF)
  88. self.model.setGamma(.1)
  89. self.model.train(samples, cv.ml.ROW_SAMPLE, responses.astype(int))
  90. def predict(self, samples):
  91. _ret, resp = self.model.predict(samples)
  92. return resp.ravel()
  93. class MLP(LetterStatModel):
  94. def __init__(self):
  95. self.model = cv.ml.ANN_MLP_create()
  96. def train(self, samples, responses):
  97. _sample_n, var_n = samples.shape
  98. new_responses = self.unroll_responses(responses).reshape(-1, self.class_n)
  99. layer_sizes = np.int32([var_n, 100, 100, self.class_n])
  100. self.model.setLayerSizes(layer_sizes)
  101. self.model.setTrainMethod(cv.ml.ANN_MLP_BACKPROP)
  102. self.model.setBackpropMomentumScale(0.0)
  103. self.model.setBackpropWeightScale(0.001)
  104. self.model.setTermCriteria((cv.TERM_CRITERIA_COUNT, 20, 0.01))
  105. self.model.setActivationFunction(cv.ml.ANN_MLP_SIGMOID_SYM, 2, 1)
  106. self.model.train(samples, cv.ml.ROW_SAMPLE, np.float32(new_responses))
  107. def predict(self, samples):
  108. _ret, resp = self.model.predict(samples)
  109. return resp.argmax(-1)
  110. def main():
  111. import getopt
  112. import sys
  113. models = [RTrees, KNearest, Boost, SVM, MLP] # NBayes
  114. models = dict( [(cls.__name__.lower(), cls) for cls in models] )
  115. args, dummy = getopt.getopt(sys.argv[1:], '', ['model=', 'data=', 'load=', 'save='])
  116. args = dict(args)
  117. args.setdefault('--model', 'svm')
  118. args.setdefault('--data', 'letter-recognition.data')
  119. datafile = cv.samples.findFile(args['--data'])
  120. print('loading data %s ...' % datafile)
  121. samples, responses = load_base(datafile)
  122. Model = models[args['--model']]
  123. model = Model()
  124. train_n = int(len(samples)*model.train_ratio)
  125. if '--load' in args:
  126. fn = args['--load']
  127. print('loading model from %s ...' % fn)
  128. model.load(fn)
  129. else:
  130. print('training %s ...' % Model.__name__)
  131. model.train(samples[:train_n], responses[:train_n])
  132. print('testing...')
  133. train_rate = np.mean(model.predict(samples[:train_n]) == responses[:train_n].astype(int))
  134. test_rate = np.mean(model.predict(samples[train_n:]) == responses[train_n:].astype(int))
  135. print('train rate: %f test rate: %f' % (train_rate*100, test_rate*100))
  136. if '--save' in args:
  137. fn = args['--save']
  138. print('saving model to %s ...' % fn)
  139. model.save(fn)
  140. print('Done')
  141. if __name__ == '__main__':
  142. print(__doc__)
  143. main()
  144. cv.destroyAllWindows()