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.

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