Utils.py 25 KB

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