Utils.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. else:
  378. result += Decimal(getUnifyMoney(subMoneys[0]))*(getMultipleFactor(factorUnit))
  379. if len(subMoneys)>1:
  380. if re.search(re.compile("^(\d+(,)?)+(\.\d+)?[百千万亿]?\s?(元)?$"),subMoneys[1]) is not None:
  381. result += Decimal(subMoneys[1])
  382. elif len(subMoneys[1])==1:
  383. if re.search(re.compile("^[%s]$"%("".join(chnDigits))),subMoneys[1]) is not None:
  384. result += Decimal(getDigitsDic(subMoneys[1]))
  385. else:
  386. result += Decimal(getUnifyMoney(subMoneys[1]))
  387. break
  388. except Exception as e:
  389. return Decimal(0)
  390. return result
  391. def getModel_w2v():
  392. '''
  393. @summary:加载词向量
  394. '''
  395. global model_w2v,lock_model_w2v
  396. with lock_model_w2v:
  397. if model_w2v is None:
  398. model_w2v = gensim.models.KeyedVectors.load_word2vec_format(getw2vfilepath(),binary=True)
  399. return model_w2v
  400. def getModel_word():
  401. '''
  402. @summary:加载字向量
  403. '''
  404. global model_word,lock_model_w2v
  405. with lock_model_word:
  406. if model_word is None:
  407. model_word = gensim.models.KeyedVectors.load_word2vec_format(model_word_file,binary=True)
  408. return model_word
  409. # getModel_w2v()
  410. # getModel_word()
  411. def findAllIndex(substr,wholestr):
  412. '''
  413. @summary: 找到字符串的子串的所有begin_index
  414. @param:
  415. substr:子字符串
  416. wholestr:子串所在完整字符串
  417. @return: list,字符串的子串的所有begin_index
  418. '''
  419. copystr = wholestr
  420. result = []
  421. indexappend = 0
  422. while(True):
  423. index = copystr.find(substr)
  424. if index<0:
  425. break
  426. else:
  427. result.append(indexappend+index)
  428. indexappend += index+len(substr)
  429. copystr = copystr[index+len(substr):]
  430. return result
  431. def spanWindow(tokens,begin_index,end_index,size,center_include=False,word_flag = False,use_text = False,text = None):
  432. '''
  433. @summary:取得某个实体的上下文词汇
  434. @param:
  435. tokens:句子分词list
  436. begin_index:实体的开始index
  437. end_index:实体的结束index
  438. size:左右两边各取多少个词
  439. center_include:是否包含实体
  440. word_flag:词/字,默认是词
  441. @return: list,实体的上下文词汇
  442. '''
  443. if use_text:
  444. assert text is not None
  445. length_tokens = len(tokens)
  446. if begin_index>size:
  447. begin = begin_index-size
  448. else:
  449. begin = 0
  450. if end_index+size<length_tokens:
  451. end = end_index+size+1
  452. else:
  453. end = length_tokens
  454. result = []
  455. if not word_flag:
  456. result.append(tokens[begin:begin_index])
  457. if center_include:
  458. if use_text:
  459. result.append(text)
  460. else:
  461. result.append(tokens[begin_index:end_index+1])
  462. result.append(tokens[end_index+1:end])
  463. else:
  464. result.append("".join(tokens[begin:begin_index]))
  465. if center_include:
  466. if use_text:
  467. result.append(text)
  468. else:
  469. result.append("".join(tokens[begin_index:end_index+1]))
  470. result.append("".join(tokens[end_index+1:end]))
  471. #print(result)
  472. return result
  473. #根据规则补全编号或名称两边的符号
  474. def fitDataByRule(data):
  475. symbol_dict = {"(":")",
  476. "(":")",
  477. "[":"]",
  478. "【":"】",
  479. ")":"(",
  480. ")":"(",
  481. "]":"[",
  482. "】":"【"}
  483. leftSymbol_pattern = re.compile("[\((\[【]")
  484. rightSymbol_pattern = re.compile("[\))\]】]")
  485. leftfinds = re.findall(leftSymbol_pattern,data)
  486. rightfinds = re.findall(rightSymbol_pattern,data)
  487. result = data
  488. if len(leftfinds)+len(rightfinds)==0:
  489. return data
  490. elif len(leftfinds)==len(rightfinds):
  491. return data
  492. elif abs(len(leftfinds)-len(rightfinds))==1:
  493. if len(leftfinds)>len(rightfinds):
  494. if symbol_dict.get(data[0]) is not None:
  495. result = data[1:]
  496. else:
  497. #print(symbol_dict.get(leftfinds[0]))
  498. result = data+symbol_dict.get(leftfinds[0])
  499. else:
  500. if symbol_dict.get(data[-1]) is not None:
  501. result = data[:-1]
  502. else:
  503. result = symbol_dict.get(rightfinds[0])+data
  504. result = re.sub("[。]","",result)
  505. return result
  506. 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}))")
  507. def timeFormat(_time):
  508. current_year = time.strftime("%Y",time.localtime())
  509. all_match = re.finditer(time_format_pattern,_time)
  510. for _match in all_match:
  511. if len(_match.group())>0:
  512. legal = True
  513. year = ""
  514. month = ""
  515. day = ""
  516. for k,v in _match.groupdict().items():
  517. if k=="year":
  518. year = v
  519. if k=="month":
  520. month = v
  521. if k=="day":
  522. day = v
  523. if year!="":
  524. if len(year)==2:
  525. year = "20"+year
  526. if int(year)>int(current_year):
  527. legal = False
  528. else:
  529. legal = False
  530. if month!="":
  531. if int(month)>12:
  532. legal = False
  533. else:
  534. legal = False
  535. if day!="":
  536. if int(day)>31:
  537. legal = False
  538. else:
  539. legal = False
  540. if legal:
  541. return "%s-%s-%s"%(year,month.rjust(2,"0"),day.rjust(2,"0"))
  542. return ""
  543. def embedding(datas,shape):
  544. '''
  545. @summary:查找词汇对应的词向量
  546. @param:
  547. datas:词汇的list
  548. shape:结果的shape
  549. @return: array,返回对应shape的词嵌入
  550. '''
  551. model_w2v = getModel_w2v()
  552. embed = np.zeros(shape)
  553. length = shape[1]
  554. out_index = 0
  555. #print(datas)
  556. for data in datas:
  557. index = 0
  558. for item in data:
  559. item_not_space = re.sub("\s*","",item)
  560. if index>=length:
  561. break
  562. if item_not_space in model_w2v.vocab:
  563. embed[out_index][index] = model_w2v[item_not_space]
  564. index += 1
  565. else:
  566. #embed[out_index][index] = model_w2v['unk']
  567. index += 1
  568. out_index += 1
  569. return embed
  570. def embedding_word(datas,shape):
  571. '''
  572. @summary:查找词汇对应的词向量
  573. @param:
  574. datas:词汇的list
  575. shape:结果的shape
  576. @return: array,返回对应shape的词嵌入
  577. '''
  578. model_w2v = getModel_word()
  579. embed = np.zeros(shape)
  580. length = shape[1]
  581. out_index = 0
  582. #print(datas)
  583. for data in datas:
  584. index = 0
  585. for item in str(data)[-shape[1]:]:
  586. if index>=length:
  587. break
  588. if item in model_w2v.vocab:
  589. embed[out_index][index] = model_w2v[item]
  590. index += 1
  591. else:
  592. # embed[out_index][index] = model_w2v['unk']
  593. index += 1
  594. out_index += 1
  595. return embed
  596. def formEncoding(text,shape=(100,60),expand=False):
  597. embedding = np.zeros(shape)
  598. word_model = getModel_word()
  599. for i in range(len(text)):
  600. if i>=shape[0]:
  601. break
  602. if text[i] in word_model.vocab:
  603. embedding[i] = word_model[text[i]]
  604. if expand:
  605. embedding = np.expand_dims(embedding,0)
  606. return embedding
  607. def partMoney(entity_text,input2_shape = [7]):
  608. '''
  609. @summary:对金额分段
  610. @param:
  611. entity_text:数值金额
  612. input2_shape:分类数
  613. @return: array,分段之后的独热编码
  614. '''
  615. money = float(entity_text)
  616. parts = np.zeros(input2_shape)
  617. if money<100:
  618. parts[0] = 1
  619. elif money<1000:
  620. parts[1] = 1
  621. elif money<10000:
  622. parts[2] = 1
  623. elif money<100000:
  624. parts[3] = 1
  625. elif money<1000000:
  626. parts[4] = 1
  627. elif money<10000000:
  628. parts[5] = 1
  629. else:
  630. parts[6] = 1
  631. return parts
  632. def recall(y_true, y_pred):
  633. '''
  634. 计算召回率
  635. @Argus:
  636. y_true: 正确的标签
  637. y_pred: 模型预测的标签
  638. @Return
  639. 召回率
  640. '''
  641. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  642. c3 = K.sum(K.round(K.clip(y_true, 0, 1)))
  643. if c3 == 0:
  644. return 0
  645. recall = c1 / c3
  646. return recall
  647. def f1_score(y_true, y_pred):
  648. '''
  649. 计算F1
  650. @Argus:
  651. y_true: 正确的标签
  652. y_pred: 模型预测的标签
  653. @Return
  654. F1值
  655. '''
  656. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  657. c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))
  658. c3 = K.sum(K.round(K.clip(y_true, 0, 1)))
  659. precision = c1 / c2
  660. if c3 == 0:
  661. recall = 0
  662. else:
  663. recall = c1 / c3
  664. f1_score = 2 * (precision * recall) / (precision + recall)
  665. return f1_score
  666. def precision(y_true, y_pred):
  667. '''
  668. 计算精确率
  669. @Argus:
  670. y_true: 正确的标签
  671. y_pred: 模型预测的标签
  672. @Return
  673. 精确率
  674. '''
  675. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  676. c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))
  677. precision = c1 / c2
  678. return precision
  679. # def print_metrics(history):
  680. # '''
  681. # 制作每次迭代的各metrics变化图片
  682. #
  683. # @Arugs:
  684. # history: 模型训练迭代的历史记录
  685. # '''
  686. # import matplotlib.pyplot as plt
  687. #
  688. # # loss图
  689. # loss = history.history['loss']
  690. # val_loss = history.history['val_loss']
  691. # epochs = range(1, len(loss) + 1)
  692. # plt.subplot(2, 2, 1)
  693. # plt.plot(epochs, loss, 'bo', label='Training loss')
  694. # plt.plot(epochs, val_loss, 'b', label='Validation loss')
  695. # plt.title('Training and validation loss')
  696. # plt.xlabel('Epochs')
  697. # plt.ylabel('Loss')
  698. # plt.legend()
  699. #
  700. # # f1图
  701. # f1 = history.history['f1_score']
  702. # val_f1 = history.history['val_f1_score']
  703. # plt.subplot(2, 2, 2)
  704. # plt.plot(epochs, f1, 'bo', label='Training f1')
  705. # plt.plot(epochs, val_f1, 'b', label='Validation f1')
  706. # plt.title('Training and validation f1')
  707. # plt.xlabel('Epochs')
  708. # plt.ylabel('F1')
  709. # plt.legend()
  710. #
  711. # # precision图
  712. # prec = history.history['precision']
  713. # val_prec = history.history['val_precision']
  714. # plt.subplot(2, 2, 3)
  715. # plt.plot(epochs, prec, 'bo', label='Training precision')
  716. # plt.plot(epochs, val_prec, 'b', label='Validation pecision')
  717. # plt.title('Training and validation precision')
  718. # plt.xlabel('Epochs')
  719. # plt.ylabel('Precision')
  720. # plt.legend()
  721. #
  722. # # recall图
  723. # recall = history.history['recall']
  724. # val_recall = history.history['val_recall']
  725. # plt.subplot(2, 2, 4)
  726. # plt.plot(epochs, recall, 'bo', label='Training recall')
  727. # plt.plot(epochs, val_recall, 'b', label='Validation recall')
  728. # plt.title('Training and validation recall')
  729. # plt.xlabel('Epochs')
  730. # plt.ylabel('Recall')
  731. # plt.legend()
  732. #
  733. # plt.show()
  734. if __name__=="__main__":
  735. # print(fool_char_to_id[">"])
  736. print(getUnifyMoney('陆万捌仟柒佰贰拾元'))
  737. # model = getModel_w2v()
  738. # vocab,matrix = getVocabAndMatrix(model, Embedding_size=128)
  739. # save([vocab,matrix],"vocabMatrix_words.pk")