You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

339 lines
11 KiB

  1. # The new class FASTsearch. Every DB can be represented in Lists. The Brain actually is constituted from lists. Access to all Documents almost the same moment.
  2. # TODO GPU Multithreading has to be implemented.
  3. # USAGE: Learn scikit-learn count vectorizer on a database of lines or docs.
  4. from sklearn.externals import joblib
  5. from sklearn.feature_extraction.text import CountVectorizer
  6. import numpy as np
  7. import scipy as sc
  8. import tensorflow as tf
  9. import _pickle as cPickle
  10. import hickle as hkl
  11. import os
  12. # Define function to convert scipy csr matrix to tf tensor for working on gpu
  13. def convert_sparse_matrix_to_sparse_tensor(X):
  14. coo = sc.sparse.coo_matrix(X)
  15. indices = np.mat([coo.row, coo.col]).transpose()
  16. return tf.SparseTensorValue(indices, coo.data, coo.shape)
  17. # The whole class is initialized with input of the database in [['word','word2'],[],[],[]] List format, 2 dimensional, the index of the list in the matrix defines its id
  18. ## in every list element of the input, each document is represented by one string
  19. # This list must be saved as a hkl dump and then loaded into the database.
  20. def my_tokenizer(s):
  21. return s.split('\+')
  22. class FASTsearch(object):
  23. def __init__(self, DatabaseDir):
  24. self.DatabaseDir = DatabaseDir[:-4]
  25. database = []
  26. hkl_load = hkl.load(DatabaseDir)
  27. for element in hkl_load:
  28. #print('element',element)
  29. #print('joined element', ' '.join(element))
  30. database.append(' '.join(element))
  31. # input has to be hkl format
  32. self.database = database
  33. def Gen_BoW_Model(self, max_features, analyzer, punctuation = False):
  34. print("Creating the bag of words...\n")
  35. from sklearn.feature_extraction.text import CountVectorizer
  36. # Initialize the "CountVectorizer" object, which is scikit-learn's
  37. # bag of words tool.
  38. if punctuation == False:
  39. vectorizer = CountVectorizer(analyzer = analyzer, \
  40. tokenizer = None, \
  41. preprocessor = None, \
  42. stop_words = None, \
  43. max_features = max_features)
  44. if punctuation == True:
  45. vectorizer = CountVectorizer(analyzer = analyzer, \
  46. tokenizer = my_tokenizer, \
  47. preprocessor = None, \
  48. stop_words = None, \
  49. max_features = max_features)
  50. # token_pattern = r'(?u)\w')
  51. # fit_transform() does two functions: First, it fits the model
  52. # and learns the vocabulary; second, it transforms our training data
  53. # into feature vectors. The input to fit_transform should be a list of
  54. # strings.
  55. train_data_features = vectorizer.fit_transform(self.database)
  56. joblib.dump(vectorizer, 'bagofwords' + self.DatabaseDir + '.pkl')
  57. print('dumping the data to hkl format..')
  58. hkl.dump(train_data_features, 'DataBaseOneZeros' + self.DatabaseDir + '.hkl', mode='w', compression='gzip')
  59. print('done')
  60. return vectorizer
  61. def Load_BoW_Model(self, BoWModelDir, DatabaseOneZerosDir):
  62. # input has to be pkl format
  63. self.vectorizer = joblib.load(BoWModelDir)
  64. self.dbOZ = hkl.load(DatabaseOneZerosDir).astype('float32')
  65. return self.vectorizer
  66. # input: string to search for in the documents, the numberofmatches to get the best n documents
  67. # output the numberofmatches documents with their indexes on the database which is searched, the highest accordance number plus index [index, number]
  68. def search(self, string , numberofmatches):
  69. numberofmatches = numberofmatches
  70. # Convert user input to Zeros and Ones
  71. user_array = []
  72. user_array.append(string)
  73. user_input_OnesZeros = self.vectorizer.transform(user_array)
  74. uOZ = user_input_OnesZeros.toarray()[0].astype(np.float32, copy=False)
  75. uiOZ = uOZ[np.newaxis, :]
  76. uiOZ = uiOZ.transpose()
  77. sess = tf.Session()
  78. with sess.as_default():
  79. uiOZ_tensor = tf.constant(uiOZ)
  80. dbOZ_tensor_sparse = convert_sparse_matrix_to_sparse_tensor(self.dbOZ)
  81. #uiOZ_tensor_sparse =tf.contrib.layers.dense_to_sparse(uiOZ_tensor, eos_token=0, outputs_collections=None, scope=None )
  82. #dbOZ_tensor_sparse =tf.contrib.layers.dense_to_sparse(dbOZ_tensor, eos_token=0, outputs_collections=None, scope=None )
  83. #wordCountDoku = tf.matmul(uiOZ_tensor, dbOZ_tensor)
  84. wordCountDoku = tf.sparse_tensor_dense_matmul(dbOZ_tensor_sparse, uiOZ_tensor)
  85. wCD = np.array(wordCountDoku.eval())
  86. indexedwCD = []
  87. for n in range(len(wCD)):
  88. indexedwCD.append([n,wCD[n][0]])
  89. indexedwCD = sorted(indexedwCD[::-1], key=lambda tup: tup[1], reverse=True)
  90. best_n_documents = []
  91. eq_number = 0
  92. for number in uiOZ:
  93. #print(number)
  94. eq_number += number ** 2
  95. #print(eq_number)
  96. n = 0
  97. done = False
  98. while n < len(indexedwCD) and done == False:
  99. n += 1
  100. if indexedwCD[n][1] == eq_number:
  101. best_n_documents = indexedwCD[n][0]
  102. done = True
  103. if indexedwCD[n][1] < eq_number:
  104. best_n_documents = indexedwCD[n - 1][0]
  105. done = True
  106. #for n in range(numberofmatches):
  107. #best_n_documents.append([indexedwCD[n][0], indexedwCD[n][1]])
  108. return best_n_documents, indexedwCD[0]
  109. def search_with_highest_multiplikation_Output(self, string , numberofmatches):
  110. numberofmatches = numberofmatches
  111. # Convert user input to Zeros and Ones
  112. user_array = []
  113. user_array.append(string)
  114. user_input_OnesZeros = self.vectorizer.transform(user_array)
  115. uOZ = user_input_OnesZeros.toarray()[0].astype(np.float32, copy=False)
  116. uiOZ = uOZ[np.newaxis, :]
  117. uiOZ = uiOZ.transpose()
  118. sess = tf.Session()
  119. with sess.as_default():
  120. uiOZ_tensor = tf.constant(uiOZ)
  121. dbOZ_tensor_sparse = convert_sparse_matrix_to_sparse_tensor(self.dbOZ)
  122. #uiOZ_tensor_sparse =tf.contrib.layers.dense_to_sparse(uiOZ_tensor, eos_token=0, outputs_collections=None, scope=None )
  123. #dbOZ_tensor_sparse =tf.contrib.layers.dense_to_sparse(dbOZ_tensor, eos_token=0, outputs_collections=None, scope=None )
  124. #wordCountDoku = tf.matmul(uiOZ_tensor, dbOZ_tensor)
  125. wordCountDoku = tf.sparse_tensor_dense_matmul(dbOZ_tensor_sparse, uiOZ_tensor)
  126. wCD = np.array(wordCountDoku.eval())
  127. indexedwCD = []
  128. for n in range(len(wCD)):
  129. indexedwCD.append([n,wCD[n][0]])
  130. indexedwCD = sorted(indexedwCD[::-1], key=lambda tup: tup[1], reverse=True)
  131. best_n_documents = []
  132. for n in range(numberofmatches):
  133. best_n_documents.append(indexedwCD[n][0])
  134. return best_n_documents, indexedwCD[0]
  135. def searchPatternMatch(self, string , numberofmatches):
  136. numberofmatches = numberofmatches
  137. # Convert user input to Zeros and Ones
  138. user_array = []
  139. user_array.append(string)
  140. user_input_OnesZeros = self.vectorizer.transform(user_array)
  141. uOZ = user_input_OnesZeros.toarray()[0].astype(np.float32, copy=False)
  142. uiOZ = uOZ[np.newaxis, :]
  143. uiOZ = uiOZ.transpose()
  144. sess = tf.Session()
  145. with sess.as_default():
  146. uiOZ_tensor = tf.constant(uiOZ)
  147. dbOZ_tensor_sparse = convert_sparse_matrix_to_sparse_tensor(self.dbOZ)
  148. #uiOZ_tensor_sparse =tf.contrib.layers.dense_to_sparse(uiOZ_tensor, eos_token=0, outputs_collections=None, scope=None )
  149. #dbOZ_tensor_sparse =tf.contrib.layers.dense_to_sparse(dbOZ_tensor, eos_token=0, outputs_collections=None, scope=None )
  150. #wordCountDoku = tf.matmul(uiOZ_tensor, dbOZ_tensor)
  151. wordCountDoku = tf.sparse_tensor_dense_matmul(dbOZ_tensor_sparse, uiOZ_tensor)
  152. wCD = np.array(wordCountDoku.eval())
  153. indexedwCD = []
  154. for n in range(len(wCD)):
  155. indexedwCD.append([n,wCD[n][0]])
  156. # Sort the biggest matches
  157. indexedwCD = sorted(indexedwCD[::-1], key=lambda tup: tup[1], reverse=True)
  158. best_n_documents = []
  159. best_docs_surrounding = []
  160. # Get the number which is result when same words would be in the document as in one grammar scheme
  161. eq_number = 0
  162. for number in uiOZ:
  163. #print(number)
  164. eq_number += number ** 2
  165. print(eq_number)
  166. # Create new array of closest grammar schemes, I have chosen around 3 (in the matchnumber, not regarding words or so)
  167. n = 0
  168. done = False
  169. while n < len(indexedwCD) and done == False:
  170. n += 1
  171. #print('a',indexedwCD)
  172. #print('oo', indexedwCD[n])
  173. if indexedwCD[n][1] == eq_number:
  174. best_docs_surrounding.append(indexedwCD[n][0])
  175. #if indexedwCD[n][1] < eq_number:
  176. #best_docs_surrounding.append(indexedwCD[n][0])
  177. if indexedwCD[n][1] < eq_number :
  178. done = True
  179. # Count for these docs in surrounding the matches of wordnumbers per word
  180. # would be much faster when using the sparse class
  181. best_docs_surrounding_new = []
  182. for doc in best_docs_surrounding:
  183. dok_BoW = self.dbOZ[doc].toarray()[0].astype(np.float32, copy=False)
  184. Number_equal_words = 0
  185. for n in range(len(uiOZ)):
  186. #print(uiOZ[n])
  187. #print(dok_BoW[n])
  188. #print('dok_BoW',dok_BoW)
  189. if uiOZ[n] == dok_BoW[n]:
  190. Number_equal_words += 1
  191. best_docs_surrounding_new.append([doc , Number_equal_words])
  192. # Sort the result again with the original indexes
  193. best_n_documents = sorted(best_docs_surrounding_new[::-1], key=lambda tup: tup[1], reverse=True)
  194. #for n in range(numberofmatches):
  195. #best_n_documents.append([indexedwCD[n][0], indexedwCD[n][1]])
  196. return best_n_documents