test_letter_recog.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. Models: RTrees, KNearest, Boost, SVM, MLP
  17. '''
  18. # Python 2/3 compatibility
  19. from __future__ import print_function
  20. import numpy as np
  21. import cv2 as cv
  22. def load_base(fn):
  23. a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
  24. samples, responses = a[:,1:], a[:,0]
  25. return samples, responses
  26. class LetterStatModel(object):
  27. class_n = 26
  28. train_ratio = 0.5
  29. def load(self, fn):
  30. self.model.load(fn)
  31. def save(self, fn):
  32. self.model.save(fn)
  33. def unroll_samples(self, samples):
  34. sample_n, var_n = samples.shape
  35. new_samples = np.zeros((sample_n * self.class_n, var_n+1), np.float32)
  36. new_samples[:,:-1] = np.repeat(samples, self.class_n, axis=0)
  37. new_samples[:,-1] = np.tile(np.arange(self.class_n), sample_n)
  38. return new_samples
  39. def unroll_responses(self, responses):
  40. sample_n = len(responses)
  41. new_responses = np.zeros(sample_n*self.class_n, np.int32)
  42. resp_idx = np.int32( responses + np.arange(sample_n)*self.class_n )
  43. new_responses[resp_idx] = 1
  44. return new_responses
  45. class RTrees(LetterStatModel):
  46. def __init__(self):
  47. self.model = cv.ml.RTrees_create()
  48. def train(self, samples, responses):
  49. #sample_n, var_n = samples.shape
  50. self.model.setMaxDepth(20)
  51. self.model.train(samples, cv.ml.ROW_SAMPLE, responses.astype(int))
  52. def predict(self, samples):
  53. _ret, resp = self.model.predict(samples)
  54. return resp.ravel()
  55. class KNearest(LetterStatModel):
  56. def __init__(self):
  57. self.model = cv.ml.KNearest_create()
  58. def train(self, samples, responses):
  59. self.model.train(samples, cv.ml.ROW_SAMPLE, responses)
  60. def predict(self, samples):
  61. _retval, results, _neigh_resp, _dists = self.model.findNearest(samples, k = 10)
  62. return results.ravel()
  63. class Boost(LetterStatModel):
  64. def __init__(self):
  65. self.model = cv.ml.Boost_create()
  66. def train(self, samples, responses):
  67. _sample_n, var_n = samples.shape
  68. new_samples = self.unroll_samples(samples)
  69. new_responses = self.unroll_responses(responses)
  70. var_types = np.array([cv.ml.VAR_NUMERICAL] * var_n + [cv.ml.VAR_CATEGORICAL, cv.ml.VAR_CATEGORICAL], np.uint8)
  71. self.model.setWeakCount(15)
  72. self.model.setMaxDepth(10)
  73. self.model.train(cv.ml.TrainData_create(new_samples, cv.ml.ROW_SAMPLE, new_responses.astype(int), varType = var_types))
  74. def predict(self, samples):
  75. new_samples = self.unroll_samples(samples)
  76. _ret, resp = self.model.predict(new_samples)
  77. return resp.ravel().reshape(-1, self.class_n).argmax(1)
  78. class SVM(LetterStatModel):
  79. def __init__(self):
  80. self.model = cv.ml.SVM_create()
  81. def train(self, samples, responses):
  82. self.model.setType(cv.ml.SVM_C_SVC)
  83. self.model.setC(1)
  84. self.model.setKernel(cv.ml.SVM_RBF)
  85. self.model.setGamma(.1)
  86. self.model.train(samples, cv.ml.ROW_SAMPLE, responses.astype(int))
  87. def predict(self, samples):
  88. _ret, resp = self.model.predict(samples)
  89. return resp.ravel()
  90. class MLP(LetterStatModel):
  91. def __init__(self):
  92. self.model = cv.ml.ANN_MLP_create()
  93. def train(self, samples, responses):
  94. _sample_n, var_n = samples.shape
  95. new_responses = self.unroll_responses(responses).reshape(-1, self.class_n)
  96. layer_sizes = np.int32([var_n, 100, 100, self.class_n])
  97. self.model.setLayerSizes(layer_sizes)
  98. self.model.setTrainMethod(cv.ml.ANN_MLP_BACKPROP)
  99. self.model.setBackpropMomentumScale(0)
  100. self.model.setBackpropWeightScale(0.001)
  101. self.model.setTermCriteria((cv.TERM_CRITERIA_COUNT, 20, 0.01))
  102. self.model.setActivationFunction(cv.ml.ANN_MLP_SIGMOID_SYM, 2, 1)
  103. self.model.train(samples, cv.ml.ROW_SAMPLE, np.float32(new_responses))
  104. def predict(self, samples):
  105. _ret, resp = self.model.predict(samples)
  106. return resp.argmax(-1)
  107. from tests_common import NewOpenCVTests
  108. class letter_recog_test(NewOpenCVTests):
  109. def test_letter_recog(self):
  110. eps = 0.01
  111. models = [RTrees, KNearest, Boost, SVM, MLP]
  112. models = dict( [(cls.__name__.lower(), cls) for cls in models] )
  113. testErrors = {RTrees: (98.930000, 92.390000), KNearest: (94.960000, 92.010000),
  114. Boost: (85.970000, 74.920000), SVM: (99.780000, 95.680000), MLP: (90.060000, 87.410000)}
  115. for model in models:
  116. Model = models[model]
  117. classifier = Model()
  118. samples, responses = load_base(self.repoPath + '/samples/data/letter-recognition.data')
  119. train_n = int(len(samples)*classifier.train_ratio)
  120. classifier.train(samples[:train_n], responses[:train_n])
  121. train_rate = np.mean(classifier.predict(samples[:train_n]) == responses[:train_n].astype(int))
  122. test_rate = np.mean(classifier.predict(samples[train_n:]) == responses[train_n:].astype(int))
  123. self.assertLess(train_rate - testErrors[Model][0], eps)
  124. self.assertLess(test_rate - testErrors[Model][1], eps)
  125. if __name__ == '__main__':
  126. NewOpenCVTests.bootstrap()