Utils.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. '''
  2. Created on 2018年12月20日
  3. @author: User
  4. '''
  5. import numpy as np
  6. import re
  7. import gensim
  8. from keras import backend as K
  9. import os,sys
  10. import time
  11. from threading import RLock
  12. # from pai_tf_predict_proto import tf_predict_pb2
  13. import requests
  14. model_w2v = None
  15. lock_model_w2v = RLock()
  16. USE_PAI_EAS = False
  17. Lazy_load = False
  18. def getCurrent_date(format="%Y-%m-%d %H:%M:%S"):
  19. _time = time.strftime(format,time.localtime())
  20. return _time
  21. def getw2vfilepath():
  22. filename = "wiki_128_word_embedding_new.vector"
  23. w2vfile = getFileFromSysPath(filename)
  24. if w2vfile is not None:
  25. return w2vfile
  26. return filename
  27. def getLazyLoad():
  28. global Lazy_load
  29. return Lazy_load
  30. def getFileFromSysPath(filename):
  31. for _path in sys.path:
  32. if os.path.isdir(_path):
  33. for _file in os.listdir(_path):
  34. _abspath = os.path.join(_path,_file)
  35. if os.path.isfile(_abspath):
  36. if _file==filename:
  37. return _abspath
  38. return None
  39. model_word_file = os.path.dirname(__file__)+"/../singlew2v_model.vector"
  40. model_word = None
  41. lock_model_word = RLock()
  42. from decimal import Decimal
  43. import logging
  44. logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  45. logger = logging.getLogger(__name__)
  46. import pickle
  47. import os
  48. import json
  49. #自定义jsonEncoder
  50. class MyEncoder(json.JSONEncoder):
  51. def __init__(self):
  52. import numpy as np
  53. global np
  54. def default(self, obj):
  55. if isinstance(obj, np.ndarray):
  56. return obj.tolist()
  57. elif isinstance(obj, bytes):
  58. return str(obj, encoding='utf-8')
  59. elif isinstance(obj, (np.float_, np.float16, np.float32,
  60. np.float64)):
  61. return float(obj)
  62. elif isinstance(obj,(np.int64,np.int32)):
  63. return int(obj)
  64. return json.JSONEncoder.default(self, obj)
  65. vocab_word = None
  66. vocab_words = None
  67. file_vocab_word = "vocab_word.pk"
  68. file_vocab_words = "vocab_words.pk"
  69. selffool_authorization = "NjlhMWFjMjVmNWYyNzI0MjY1OGQ1M2Y0ZmY4ZGY0Mzg3Yjc2MTVjYg=="
  70. selffool_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/selffool_gpu"
  71. selffool_seg_authorization = "OWUwM2Q0ZmE3YjYxNzU4YzFiMjliNGVkMTA3MzJkNjQ2MzJiYzBhZg=="
  72. selffool_seg_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/selffool_seg_gpu"
  73. codename_authorization = "Y2M5MDUxMzU1MTU4OGM3ZDk2ZmEzYjkxYmYyYzJiZmUyYTgwYTg5NA=="
  74. codename_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/codename_gpu"
  75. form_item_authorization = "ODdkZWY1YWY0NmNhNjU2OTI2NWY4YmUyM2ZlMDg1NTZjOWRkYTVjMw=="
  76. form_item_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/form"
  77. person_authorization = "N2I2MDU2N2Q2MGQ0ZWZlZGM3NDkyNTA1Nzc4YmM5OTlhY2MxZGU1Mw=="
  78. person_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/person"
  79. role_authorization = "OWM1ZDg5ZDEwYTEwYWI4OGNjYmRlMmQ1NzYwNWNlZGZkZmRmMjE4OQ=="
  80. role_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/role"
  81. money_authorization = "MDQyNjc2ZDczYjBhYmM4Yzc4ZGI4YjRmMjc3NGI5NTdlNzJiY2IwZA=="
  82. money_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/money"
  83. codeclasses_authorization = "MmUyNWIxZjQ2NjAzMWJlMGIzYzkxMjMzNWY5OWI3NzJlMWQ1ZjY4Yw=="
  84. codeclasses_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/codeclasses"
  85. def viterbi_decode(score, transition_params):
  86. """Decode the highest scoring sequence of tags outside of TensorFlow.
  87. This should only be used at test time.
  88. Args:
  89. score: A [seq_len, num_tags] matrix of unary potentials.
  90. transition_params: A [num_tags, num_tags] matrix of binary potentials.
  91. Returns:
  92. viterbi: A [seq_len] list of integers containing the highest scoring tag
  93. indices.
  94. viterbi_score: A float containing the score for the Viterbi sequence.
  95. """
  96. trellis = np.zeros_like(score)
  97. backpointers = np.zeros_like(score, dtype=np.int32)
  98. trellis[0] = score[0]
  99. for t in range(1, score.shape[0]):
  100. v = np.expand_dims(trellis[t - 1], 1) + transition_params
  101. trellis[t] = score[t] + np.max(v, 0)
  102. backpointers[t] = np.argmax(v, 0)
  103. viterbi = [np.argmax(trellis[-1])]
  104. for bp in reversed(backpointers[1:]):
  105. viterbi.append(bp[viterbi[-1]])
  106. viterbi.reverse()
  107. viterbi_score = np.max(trellis[-1])
  108. return viterbi, viterbi_score
  109. def limitRun(sess,list_output,feed_dict,MAX_BATCH=1024):
  110. len_sample = 0
  111. if len(feed_dict.keys())>0:
  112. len_sample = len(feed_dict[list(feed_dict.keys())[0]])
  113. if len_sample>MAX_BATCH:
  114. list_result = [[] for _ in range(len(list_output))]
  115. _begin = 0
  116. while(_begin<len_sample):
  117. new_dict = dict()
  118. for _key in feed_dict.keys():
  119. if isinstance(feed_dict[_key],(float,int,np.int32,np.float_,np.float16,np.float32,np.float64)):
  120. new_dict[_key] = feed_dict[_key]
  121. else:
  122. new_dict[_key] = feed_dict[_key][_begin:_begin+MAX_BATCH]
  123. _output = sess.run(list_output,feed_dict=new_dict)
  124. for _index in range(len(list_output)):
  125. list_result[_index].extend(_output[_index])
  126. _begin += MAX_BATCH
  127. else:
  128. list_result = sess.run(list_output,feed_dict=feed_dict)
  129. return list_result
  130. def get_values(response,output_name):
  131. """
  132. Get the value of a specified output tensor
  133. :param output_name: name of the output tensor
  134. :return: the content of the output tensor
  135. """
  136. output = response.outputs[output_name]
  137. if output.dtype == tf_predict_pb2.DT_FLOAT:
  138. _value = output.float_val
  139. elif output.dtype == tf_predict_pb2.DT_INT8 or output.dtype == tf_predict_pb2.DT_INT16 or \
  140. output.dtype == tf_predict_pb2.DT_INT32:
  141. _value = output.int_val
  142. elif output.dtype == tf_predict_pb2.DT_INT64:
  143. _value = output.int64_val
  144. elif output.dtype == tf_predict_pb2.DT_DOUBLE:
  145. _value = output.double_val
  146. elif output.dtype == tf_predict_pb2.DT_STRING:
  147. _value = output.string_val
  148. elif output.dtype == tf_predict_pb2.DT_BOOL:
  149. _value = output.bool_val
  150. return np.array(_value).reshape(response.outputs[output_name].array_shape.dim)
  151. def vpc_requests(url,authorization,request_data,list_outputs):
  152. headers = {"Authorization": authorization}
  153. dict_outputs = dict()
  154. response = tf_predict_pb2.PredictResponse()
  155. resp = requests.post(url, data=request_data, headers=headers)
  156. if resp.status_code != 200:
  157. print(resp.status_code,resp.content)
  158. log("调用pai-eas接口出错,authorization:"+str(authorization))
  159. return None
  160. else:
  161. response = tf_predict_pb2.PredictResponse()
  162. response.ParseFromString(resp.content)
  163. for _output in list_outputs:
  164. dict_outputs[_output] = get_values(response, _output)
  165. return dict_outputs
  166. def encodeInput(data,word_len,word_flag=True,userFool=False):
  167. result = []
  168. out_index = 0
  169. for item in data:
  170. if out_index in [0]:
  171. list_word = item[-word_len:]
  172. else:
  173. list_word = item[:word_len]
  174. temp = []
  175. if word_flag:
  176. for word in list_word:
  177. if userFool:
  178. temp.append(getIndexOfWord_fool(word))
  179. else:
  180. temp.append(getIndexOfWord(word))
  181. list_append = []
  182. temp_len = len(temp)
  183. while(temp_len<word_len):
  184. if userFool:
  185. list_append.append(0)
  186. else:
  187. list_append.append(getIndexOfWord("<pad>"))
  188. temp_len += 1
  189. if out_index in [0]:
  190. temp = list_append+temp
  191. else:
  192. temp = temp+list_append
  193. else:
  194. for words in list_word:
  195. temp.append(getIndexOfWords(words))
  196. list_append = []
  197. temp_len = len(temp)
  198. while(temp_len<word_len):
  199. list_append.append(getIndexOfWords("<pad>"))
  200. temp_len += 1
  201. if out_index in [0,1]:
  202. temp = list_append+temp
  203. else:
  204. temp = temp+list_append
  205. result.append(temp)
  206. out_index += 1
  207. return result
  208. def encodeInput_form(input,MAX_LEN=30):
  209. x = np.zeros([MAX_LEN])
  210. for i in range(len(input)):
  211. if i>=MAX_LEN:
  212. break
  213. x[i] = getIndexOfWord(input[i])
  214. return x
  215. def getVocabAndMatrix(model,Embedding_size = 60):
  216. '''
  217. @summary:获取子向量的词典和子向量矩阵
  218. '''
  219. vocab = ["<pad>"]+model.index2word
  220. embedding_matrix = np.zeros((len(vocab),Embedding_size))
  221. for i in range(1,len(vocab)):
  222. embedding_matrix[i] = model[vocab[i]]
  223. return vocab,embedding_matrix
  224. def getIndexOfWord(word):
  225. global vocab_word,file_vocab_word
  226. if vocab_word is None:
  227. if os.path.exists(file_vocab_word):
  228. vocab = load(file_vocab_word)
  229. vocab_word = dict((w, i) for i, w in enumerate(np.array(vocab)))
  230. else:
  231. model = getModel_word()
  232. vocab,_ = getVocabAndMatrix(model, Embedding_size=60)
  233. vocab_word = dict((w, i) for i, w in enumerate(np.array(vocab)))
  234. save(vocab,file_vocab_word)
  235. if word in vocab_word.keys():
  236. return vocab_word[word]
  237. else:
  238. return vocab_word['<pad>']
  239. def changeIndexFromWordToWords(tokens,word_index):
  240. '''
  241. @summary:转换某个字的字偏移为词偏移
  242. '''
  243. before_index = 0
  244. after_index = 0
  245. for i in range(len(tokens)):
  246. after_index = after_index+len(tokens[i])
  247. if before_index<=word_index and after_index>word_index:
  248. return i
  249. before_index = after_index
  250. def getIndexOfWords(words):
  251. global vocab_words,file_vocab_words
  252. if vocab_words is None:
  253. if os.path.exists(file_vocab_words):
  254. vocab = load(file_vocab_words)
  255. vocab_words = dict((w, i) for i, w in enumerate(np.array(vocab)))
  256. else:
  257. model = getModel_w2v()
  258. vocab,_ = getVocabAndMatrix(model, Embedding_size=128)
  259. vocab_words = dict((w, i) for i, w in enumerate(np.array(vocab)))
  260. save(vocab,file_vocab_words)
  261. if words in vocab_words.keys():
  262. return vocab_words[words]
  263. else:
  264. return vocab_words["<pad>"]
  265. def log(msg):
  266. '''
  267. @summary:打印信息
  268. '''
  269. logger.info(msg)
  270. def debug(msg):
  271. '''
  272. @summary:打印信息
  273. '''
  274. logger.debug(msg)
  275. def save(object_to_save, path):
  276. '''
  277. 保存对象
  278. @Arugs:
  279. object_to_save: 需要保存的对象
  280. @Return:
  281. 保存的路径
  282. '''
  283. with open(path, 'wb') as f:
  284. pickle.dump(object_to_save, f)
  285. def load(path):
  286. '''
  287. 读取对象
  288. @Arugs:
  289. path: 读取的路径
  290. @Return:
  291. 读取的对象
  292. '''
  293. with open(path, 'rb') as f:
  294. object1 = pickle.load(f)
  295. return object1
  296. fool_char_to_id = load(os.path.dirname(__file__)+"/fool_char_to_id.pk")
  297. def getIndexOfWord_fool(word):
  298. if word in fool_char_to_id.keys():
  299. return fool_char_to_id[word]
  300. else:
  301. return fool_char_to_id["[UNK]"]
  302. def find_index(list_tofind,text):
  303. '''
  304. @summary: 查找所有词汇在字符串中第一次出现的位置
  305. @param:
  306. list_tofind:待查找词汇
  307. text:字符串
  308. @return: list,每个词汇第一次出现的位置
  309. '''
  310. result = []
  311. for item in list_tofind:
  312. index = text.find(item)
  313. if index>=0:
  314. result.append(index)
  315. else:
  316. result.append(-1)
  317. return result
  318. def combine(list1,list2):
  319. '''
  320. @summary:将两个list中的字符串两两拼接
  321. @param:
  322. list1:字符串list
  323. list2:字符串list
  324. @return:拼接结果list
  325. '''
  326. result = []
  327. for item1 in list1:
  328. for item2 in list2:
  329. result.append(str(item1)+str(item2))
  330. return result
  331. def getDigitsDic(unit):
  332. '''
  333. @summary:拿到中文对应的数字
  334. '''
  335. DigitsDic = {"零":0, "壹":1, "贰":2, "叁":3, "肆":4, "伍":5, "陆":6, "柒":7, "捌":8, "玖":9,
  336. "〇":0, "一":1, "二":2, "三":3, "四":4, "五":5, "六":6, "七":7, "八":8, "九":9}
  337. return DigitsDic.get(unit)
  338. def getMultipleFactor(unit):
  339. '''
  340. @summary:拿到单位对应的值
  341. '''
  342. MultipleFactor = {"兆":Decimal(1000000000000),"亿":Decimal(100000000),"万":Decimal(10000),"仟":Decimal(1000),"千":Decimal(1000),"佰":Decimal(100),"百":Decimal(100),"拾":Decimal(10),"十":Decimal(10),"元":Decimal(1),"圆":Decimal(1),"角":round(Decimal(0.1),1),"分":round(Decimal(0.01),2)}
  343. return MultipleFactor.get(unit)
  344. def getUnifyMoney(money):
  345. '''
  346. @summary:将中文金额字符串转换为数字金额
  347. @param:
  348. money:中文金额字符串
  349. @return: decimal,数据金额
  350. '''
  351. MAX_MONEY = 1000000000000
  352. MAX_NUM = 12
  353. #去掉逗号
  354. money = re.sub("[,,]","",money)
  355. money = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]","",money)
  356. result = Decimal(0)
  357. chnDigits = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]
  358. # chnFactorUnits = ["兆", "亿", "万", "仟", "佰", "拾","圆","元","角","分"]
  359. chnFactorUnits = ["兆", "亿", "万", "仟", "佰", "拾", "圆", "元", "角", "分", '十', '百', '千']
  360. LowMoneypattern = re.compile("^[\d,]+(\.\d+)?$")
  361. BigMoneypattern = re.compile("^零?(?P<BigMoney>[%s])$"%("".join(chnDigits)))
  362. try:
  363. if re.search(LowMoneypattern,money) is not None:
  364. return Decimal(money)
  365. elif re.search(BigMoneypattern,money) is not None:
  366. return getDigitsDic(re.search(BigMoneypattern,money).group("BigMoney"))
  367. for factorUnit in chnFactorUnits:
  368. if re.search(re.compile(".*%s.*"%(factorUnit)),money) is not None:
  369. subMoneys = re.split(re.compile("%s(?!.*%s.*)"%(factorUnit,factorUnit)),money)
  370. if re.search(re.compile("^(\d+)(\.\d+)?$"),subMoneys[0]) is not None:
  371. if MAX_MONEY/getMultipleFactor(factorUnit)<Decimal(subMoneys[0]):
  372. return Decimal(0)
  373. result += Decimal(subMoneys[0])*(getMultipleFactor(factorUnit))
  374. elif len(subMoneys[0])==1:
  375. if re.search(re.compile("^[%s]$"%("".join(chnDigits))),subMoneys[0]) is not None:
  376. result += Decimal(getDigitsDic(subMoneys[0]))*(getMultipleFactor(factorUnit))
  377. # subMoneys[0]中无金额单位,不可再拆分
  378. elif re.search(re.compile("[%s]"%("".join(chnFactorUnits))),subMoneys[0]) is None:
  379. subMoneys[0] = subMoneys[0][0]
  380. result += Decimal(getDigitsDic(subMoneys[0])) * (getMultipleFactor(factorUnit))
  381. else:
  382. result += Decimal(getUnifyMoney(subMoneys[0]))*(getMultipleFactor(factorUnit))
  383. if len(subMoneys)>1:
  384. if re.search(re.compile("^(\d+(,)?)+(\.\d+)?[百千万亿]?\s?(元)?$"),subMoneys[1]) is not None:
  385. result += Decimal(subMoneys[1])
  386. elif len(subMoneys[1])==1:
  387. if re.search(re.compile("^[%s]$"%("".join(chnDigits))),subMoneys[1]) is not None:
  388. result += Decimal(getDigitsDic(subMoneys[1]))
  389. else:
  390. result += Decimal(getUnifyMoney(subMoneys[1]))
  391. break
  392. except Exception as e:
  393. return Decimal(0)
  394. return result
  395. def getModel_w2v():
  396. '''
  397. @summary:加载词向量
  398. '''
  399. global model_w2v,lock_model_w2v
  400. with lock_model_w2v:
  401. if model_w2v is None:
  402. model_w2v = gensim.models.KeyedVectors.load_word2vec_format(getw2vfilepath(),binary=True)
  403. return model_w2v
  404. def getModel_word():
  405. '''
  406. @summary:加载字向量
  407. '''
  408. global model_word,lock_model_w2v
  409. with lock_model_word:
  410. if model_word is None:
  411. model_word = gensim.models.KeyedVectors.load_word2vec_format(model_word_file,binary=True)
  412. return model_word
  413. # getModel_w2v()
  414. # getModel_word()
  415. def findAllIndex(substr,wholestr):
  416. '''
  417. @summary: 找到字符串的子串的所有begin_index
  418. @param:
  419. substr:子字符串
  420. wholestr:子串所在完整字符串
  421. @return: list,字符串的子串的所有begin_index
  422. '''
  423. copystr = wholestr
  424. result = []
  425. indexappend = 0
  426. while(True):
  427. index = copystr.find(substr)
  428. if index<0:
  429. break
  430. else:
  431. result.append(indexappend+index)
  432. indexappend += index+len(substr)
  433. copystr = copystr[index+len(substr):]
  434. return result
  435. def spanWindow(tokens,begin_index,end_index,size,center_include=False,word_flag = False,use_text = False,text = None):
  436. '''
  437. @summary:取得某个实体的上下文词汇
  438. @param:
  439. tokens:句子分词list
  440. begin_index:实体的开始index
  441. end_index:实体的结束index
  442. size:左右两边各取多少个词
  443. center_include:是否包含实体
  444. word_flag:词/字,默认是词
  445. @return: list,实体的上下文词汇
  446. '''
  447. if use_text:
  448. assert text is not None
  449. length_tokens = len(tokens)
  450. if begin_index>size:
  451. begin = begin_index-size
  452. else:
  453. begin = 0
  454. if end_index+size<length_tokens:
  455. end = end_index+size+1
  456. else:
  457. end = length_tokens
  458. result = []
  459. if not word_flag:
  460. result.append(tokens[begin:begin_index])
  461. if center_include:
  462. if use_text:
  463. result.append(text)
  464. else:
  465. result.append(tokens[begin_index:end_index+1])
  466. result.append(tokens[end_index+1:end])
  467. else:
  468. result.append("".join(tokens[begin:begin_index]))
  469. if center_include:
  470. if use_text:
  471. result.append(text)
  472. else:
  473. result.append("".join(tokens[begin_index:end_index+1]))
  474. result.append("".join(tokens[end_index+1:end]))
  475. #print(result)
  476. return result
  477. #根据规则补全编号或名称两边的符号
  478. def fitDataByRule(data):
  479. symbol_dict = {"(":")",
  480. "(":")",
  481. "[":"]",
  482. "【":"】",
  483. ")":"(",
  484. ")":"(",
  485. "]":"[",
  486. "】":"【"}
  487. leftSymbol_pattern = re.compile("[\((\[【]")
  488. rightSymbol_pattern = re.compile("[\))\]】]")
  489. leftfinds = re.findall(leftSymbol_pattern,data)
  490. rightfinds = re.findall(rightSymbol_pattern,data)
  491. result = data
  492. if len(leftfinds)+len(rightfinds)==0:
  493. return data
  494. elif len(leftfinds)==len(rightfinds):
  495. return data
  496. elif abs(len(leftfinds)-len(rightfinds))==1:
  497. if len(leftfinds)>len(rightfinds):
  498. if symbol_dict.get(data[0]) is not None:
  499. result = data[1:]
  500. else:
  501. #print(symbol_dict.get(leftfinds[0]))
  502. result = data+symbol_dict.get(leftfinds[0])
  503. else:
  504. if symbol_dict.get(data[-1]) is not None:
  505. result = data[:-1]
  506. else:
  507. result = symbol_dict.get(rightfinds[0])+data
  508. result = re.sub("[。]","",result)
  509. return result
  510. time_format_pattern = re.compile("((?P<year>\d{4}|\d{2})\s*[-\/年\.]\s*(?P<month>\d{1,2})\s*[-\/月\.]\s*(?P<day>\d{1,2}))")
  511. def timeFormat(_time):
  512. current_year = time.strftime("%Y",time.localtime())
  513. all_match = re.finditer(time_format_pattern,_time)
  514. for _match in all_match:
  515. if len(_match.group())>0:
  516. legal = True
  517. year = ""
  518. month = ""
  519. day = ""
  520. for k,v in _match.groupdict().items():
  521. if k=="year":
  522. year = v
  523. if k=="month":
  524. month = v
  525. if k=="day":
  526. day = v
  527. if year!="":
  528. if len(year)==2:
  529. year = "20"+year
  530. if int(year)>int(current_year):
  531. legal = False
  532. else:
  533. legal = False
  534. if month!="":
  535. if int(month)>12:
  536. legal = False
  537. else:
  538. legal = False
  539. if day!="":
  540. if int(day)>31:
  541. legal = False
  542. else:
  543. legal = False
  544. if legal:
  545. return "%s-%s-%s"%(year,month.rjust(2,"0"),day.rjust(2,"0"))
  546. return ""
  547. def embedding(datas,shape):
  548. '''
  549. @summary:查找词汇对应的词向量
  550. @param:
  551. datas:词汇的list
  552. shape:结果的shape
  553. @return: array,返回对应shape的词嵌入
  554. '''
  555. model_w2v = getModel_w2v()
  556. embed = np.zeros(shape)
  557. length = shape[1]
  558. out_index = 0
  559. #print(datas)
  560. for data in datas:
  561. index = 0
  562. for item in data:
  563. item_not_space = re.sub("\s*","",item)
  564. if index>=length:
  565. break
  566. if item_not_space in model_w2v.vocab:
  567. embed[out_index][index] = model_w2v[item_not_space]
  568. index += 1
  569. else:
  570. #embed[out_index][index] = model_w2v['unk']
  571. index += 1
  572. out_index += 1
  573. return embed
  574. def embedding_word(datas,shape):
  575. '''
  576. @summary:查找词汇对应的词向量
  577. @param:
  578. datas:词汇的list
  579. shape:结果的shape
  580. @return: array,返回对应shape的词嵌入
  581. '''
  582. model_w2v = getModel_word()
  583. embed = np.zeros(shape)
  584. length = shape[1]
  585. out_index = 0
  586. #print(datas)
  587. for data in datas:
  588. index = 0
  589. for item in str(data)[-shape[1]:]:
  590. if index>=length:
  591. break
  592. if item in model_w2v.vocab:
  593. embed[out_index][index] = model_w2v[item]
  594. index += 1
  595. else:
  596. # embed[out_index][index] = model_w2v['unk']
  597. index += 1
  598. out_index += 1
  599. return embed
  600. def embedding_word_forward(datas,shape):
  601. '''
  602. @summary:查找词汇对应的词向量
  603. @param:
  604. datas:词汇的list
  605. shape:结果的shape
  606. @return: array,返回对应shape的词嵌入
  607. '''
  608. model_w2v = getModel_word()
  609. embed = np.zeros(shape)
  610. length = shape[1]
  611. out_index = 0
  612. #print(datas)
  613. for data in datas:
  614. index = 0
  615. for item in str(data)[:shape[1]]:
  616. if index>=length:
  617. break
  618. if item in model_w2v.vocab:
  619. embed[out_index][index] = model_w2v[item]
  620. index += 1
  621. else:
  622. # embed[out_index][index] = model_w2v['unk']
  623. index += 1
  624. out_index += 1
  625. return embed
  626. def formEncoding(text,shape=(100,60),expand=False):
  627. embedding = np.zeros(shape)
  628. word_model = getModel_word()
  629. for i in range(len(text)):
  630. if i>=shape[0]:
  631. break
  632. if text[i] in word_model.vocab:
  633. embedding[i] = word_model[text[i]]
  634. if expand:
  635. embedding = np.expand_dims(embedding,0)
  636. return embedding
  637. def partMoney(entity_text,input2_shape = [7]):
  638. '''
  639. @summary:对金额分段
  640. @param:
  641. entity_text:数值金额
  642. input2_shape:分类数
  643. @return: array,分段之后的独热编码
  644. '''
  645. money = float(entity_text)
  646. parts = np.zeros(input2_shape)
  647. if money<100:
  648. parts[0] = 1
  649. elif money<1000:
  650. parts[1] = 1
  651. elif money<10000:
  652. parts[2] = 1
  653. elif money<100000:
  654. parts[3] = 1
  655. elif money<1000000:
  656. parts[4] = 1
  657. elif money<10000000:
  658. parts[5] = 1
  659. else:
  660. parts[6] = 1
  661. return parts
  662. def recall(y_true, y_pred):
  663. '''
  664. 计算召回率
  665. @Argus:
  666. y_true: 正确的标签
  667. y_pred: 模型预测的标签
  668. @Return
  669. 召回率
  670. '''
  671. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  672. c3 = K.sum(K.round(K.clip(y_true, 0, 1)))
  673. if c3 == 0:
  674. return 0
  675. recall = c1 / c3
  676. return recall
  677. def f1_score(y_true, y_pred):
  678. '''
  679. 计算F1
  680. @Argus:
  681. y_true: 正确的标签
  682. y_pred: 模型预测的标签
  683. @Return
  684. F1值
  685. '''
  686. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  687. c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))
  688. c3 = K.sum(K.round(K.clip(y_true, 0, 1)))
  689. precision = c1 / c2
  690. if c3 == 0:
  691. recall = 0
  692. else:
  693. recall = c1 / c3
  694. f1_score = 2 * (precision * recall) / (precision + recall)
  695. return f1_score
  696. def precision(y_true, y_pred):
  697. '''
  698. 计算精确率
  699. @Argus:
  700. y_true: 正确的标签
  701. y_pred: 模型预测的标签
  702. @Return
  703. 精确率
  704. '''
  705. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  706. c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))
  707. precision = c1 / c2
  708. return precision
  709. # def print_metrics(history):
  710. # '''
  711. # 制作每次迭代的各metrics变化图片
  712. #
  713. # @Arugs:
  714. # history: 模型训练迭代的历史记录
  715. # '''
  716. # import matplotlib.pyplot as plt
  717. #
  718. # # loss图
  719. # loss = history.history['loss']
  720. # val_loss = history.history['val_loss']
  721. # epochs = range(1, len(loss) + 1)
  722. # plt.subplot(2, 2, 1)
  723. # plt.plot(epochs, loss, 'bo', label='Training loss')
  724. # plt.plot(epochs, val_loss, 'b', label='Validation loss')
  725. # plt.title('Training and validation loss')
  726. # plt.xlabel('Epochs')
  727. # plt.ylabel('Loss')
  728. # plt.legend()
  729. #
  730. # # f1图
  731. # f1 = history.history['f1_score']
  732. # val_f1 = history.history['val_f1_score']
  733. # plt.subplot(2, 2, 2)
  734. # plt.plot(epochs, f1, 'bo', label='Training f1')
  735. # plt.plot(epochs, val_f1, 'b', label='Validation f1')
  736. # plt.title('Training and validation f1')
  737. # plt.xlabel('Epochs')
  738. # plt.ylabel('F1')
  739. # plt.legend()
  740. #
  741. # # precision图
  742. # prec = history.history['precision']
  743. # val_prec = history.history['val_precision']
  744. # plt.subplot(2, 2, 3)
  745. # plt.plot(epochs, prec, 'bo', label='Training precision')
  746. # plt.plot(epochs, val_prec, 'b', label='Validation pecision')
  747. # plt.title('Training and validation precision')
  748. # plt.xlabel('Epochs')
  749. # plt.ylabel('Precision')
  750. # plt.legend()
  751. #
  752. # # recall图
  753. # recall = history.history['recall']
  754. # val_recall = history.history['val_recall']
  755. # plt.subplot(2, 2, 4)
  756. # plt.plot(epochs, recall, 'bo', label='Training recall')
  757. # plt.plot(epochs, val_recall, 'b', label='Validation recall')
  758. # plt.title('Training and validation recall')
  759. # plt.xlabel('Epochs')
  760. # plt.ylabel('Recall')
  761. # plt.legend()
  762. #
  763. # plt.show()
  764. if __name__=="__main__":
  765. # print(fool_char_to_id[">"])
  766. print(getUnifyMoney('壹拾柒万元'))
  767. # model = getModel_w2v()
  768. # vocab,matrix = getVocabAndMatrix(model, Embedding_size=128)
  769. # save([vocab,matrix],"vocabMatrix_words.pk")