Utils.py 25 KB

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