test_model_fjs.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. import sys
  2. import psycopg2
  3. from keras.models import Model
  4. from keras.layers import Input, LSTM, Dense
  5. import numpy as np
  6. import pandas as pd
  7. from matplotlib import pyplot
  8. from BiddingKG.dl.common.models import *
  9. from sklearn.metrics import classification_report
  10. from BiddingKG.dl.interface.predictor import h5_to_graph
  11. sys.path.append(os.path.abspath("../.."))
  12. model_file = "model_person_classify_fjs.model.hdf5"
  13. def getSeq2seqModel():
  14. # Batch size for training.
  15. batch_size = 64
  16. # Number of epochs to train for.
  17. epochs = 100
  18. # Latent dimensionality of the encoding space.
  19. latent_dim = 256
  20. # Number of samples to train on.
  21. num_samples = 10000
  22. # Path to the data txt file on disk.
  23. data_path = 'fra-eng/fra.txt'
  24. # Vectorize the data.
  25. input_texts = []
  26. target_texts = []
  27. # Set方便去重
  28. input_characters = set()
  29. target_characters = set()
  30. with open(data_path, 'r', encoding='utf-8') as f:
  31. lines = f.read().split('\n')
  32. for line in lines[: min(num_samples, len(lines) - 1)]:
  33. input_text, target_text, _ = line.split('\t')
  34. # 句子开始符:\t 句子终止符:\n
  35. # We use "tab" as the "start sequence" character
  36. # for the targets, and "\n" as "end sequence" character.
  37. target_text = '\t' + target_text + '\n'
  38. input_texts.append(input_text)
  39. target_texts.append(target_text)
  40. for char in input_text:
  41. if char not in input_characters:
  42. input_characters.add(char)
  43. for char in target_text:
  44. if char not in target_characters:
  45. target_characters.add(char)
  46. # 将字符排序
  47. input_characters = sorted(list(input_characters))
  48. target_characters = sorted(list(target_characters))
  49. # Encoder的输入类别长度:字符表长度
  50. # Decoder的输出类别长度:字符表长度
  51. num_encoder_tokens = len(input_characters)
  52. num_decoder_tokens = len(target_characters)
  53. # Encoder的输入最大长度:最长的句子的长度
  54. # Decoder的输入最大长度:最长的句子的长度
  55. max_encoder_seq_length = max([len(txt) for txt in input_texts])
  56. max_decoder_seq_length = max([len(txt) for txt in target_texts])
  57. print('Number of samples:', len(input_texts))
  58. print('Number of unique input tokens:', num_encoder_tokens)
  59. print('Number of unique output tokens:', num_decoder_tokens)
  60. print('Max sequence length for inputs:', max_encoder_seq_length)
  61. print('Max sequence length for outputs:', max_decoder_seq_length)
  62. # 为每个字符与下标组成一个字典
  63. input_token_index = dict(
  64. [(char, i) for i, char in enumerate(input_characters)])
  65. target_token_index = dict(
  66. [(char, i) for i, char in enumerate(target_characters)])
  67. # 初始化Encoder输入矩阵
  68. # 第一维为句子条数,即RNN循环次数
  69. # 第二维为Encoder最大输入长度
  70. # 第三维为Encoder的输入类别长度
  71. encoder_input_data = np.zeros(
  72. (len(input_texts), max_encoder_seq_length, num_encoder_tokens),
  73. dtype='float32')
  74. # 初始化Decoder输入矩阵(Encoder输出)
  75. # 第一维为句子条数,即RNN循环次数
  76. # 第二维为Decoder最大输入长度
  77. # 第三维为Decoder的输入类别长度
  78. decoder_input_data = np.zeros(
  79. (len(input_texts), max_decoder_seq_length, num_decoder_tokens),
  80. dtype='float32')
  81. # 初始化Decoder输出矩阵
  82. # 第一维为句子条数,即RNN循环次数
  83. # 第二维为Decoder最大输入长度
  84. # 第三维为Decoder的输入类别长度
  85. decoder_target_data = np.zeros(
  86. (len(input_texts), max_decoder_seq_length, num_decoder_tokens),
  87. dtype='float32')
  88. # 将input和target打包成一对,如[input, target]
  89. for i, (input_text, target_text) in enumerate(zip(input_texts, target_texts)):
  90. for t, char in enumerate(input_text):
  91. encoder_input_data[i, t, input_token_index[char]] = 1.
  92. encoder_input_data[i, t + 1:, input_token_index[' ']] = 1.
  93. for t, char in enumerate(target_text):
  94. # decoder_target_data is ahead of decoder_input_data by one timestep
  95. decoder_input_data[i, t, target_token_index[char]] = 1.
  96. if t > 0:
  97. # decoder_target_data will be ahead by one timestep
  98. # and will not include the start character.
  99. decoder_target_data[i, t - 1, target_token_index[char]] = 1.
  100. decoder_input_data[i, t + 1:, target_token_index[' ']] = 1.
  101. decoder_target_data[i, t:, target_token_index[' ']] = 1.
  102. # Define an input sequence and process it.
  103. encoder_inputs = Input(shape=(None, num_encoder_tokens))
  104. encoder = LSTM(latent_dim, return_state=True)
  105. encoder_outputs, state_h, state_c = encoder(encoder_inputs)
  106. # We discard `encoder_outputs` and only keep the states.
  107. encoder_states = [state_h, state_c]
  108. # Set up the decoder, using `encoder_states` as initial state.
  109. decoder_inputs = Input(shape=(None, num_decoder_tokens))
  110. # We set up our decoder to return full output sequences,
  111. # and to return internal states as well. We don't use the
  112. # return states in the training model, but we will use them in inference.
  113. decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
  114. decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
  115. initial_state=encoder_states)
  116. decoder_dense = Dense(num_decoder_tokens, activation='softmax')
  117. decoder_outputs = decoder_dense(decoder_outputs)
  118. # Define the model that will turn
  119. # `encoder_input_data` & `decoder_input_data` into `decoder_target_data`
  120. model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
  121. # Run training
  122. model.compile(optimizer='rmsprop', loss='categorical_crossentropy',
  123. metrics=['accuracy'])
  124. model.fit([encoder_input_data, decoder_input_data], decoder_target_data,
  125. batch_size=batch_size,
  126. epochs=epochs,
  127. validation_split=0.2)
  128. # Save model
  129. model.save('s2s.h5')
  130. # Next: inference mode (sampling).
  131. # Here's the drill:
  132. # 1) encode input and retrieve initial decoder state
  133. # 2) run one step of decoder with this initial state
  134. # and a "start of sequence" token as target.
  135. # Output will be the next target token
  136. # 3) Repeat with the current target token and current states
  137. # Define sampling models
  138. encoder_model = Model(encoder_inputs, encoder_states)
  139. decoder_state_input_h = Input(shape=(latent_dim,))
  140. decoder_state_input_c = Input(shape=(latent_dim,))
  141. decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
  142. decoder_outputs, state_h, state_c = decoder_lstm(
  143. decoder_inputs, initial_state=decoder_states_inputs)
  144. decoder_states = [state_h, state_c]
  145. decoder_outputs = decoder_dense(decoder_outputs)
  146. decoder_model = Model(
  147. [decoder_inputs] + decoder_states_inputs,
  148. [decoder_outputs] + decoder_states)
  149. # Reverse-lookup token index to decode sequences back to
  150. # something readable.
  151. reverse_input_char_index = dict(
  152. (i, char) for char, i in input_token_index.items())
  153. reverse_target_char_index = dict(
  154. (i, char) for char, i in target_token_index.items())
  155. def decode_sequence(input_seq):
  156. # Encode the input as state vectors.
  157. states_value = encoder_model.predict(input_seq)
  158. # Generate empty target sequence of length 1.
  159. target_seq = np.zeros((1, 1, num_decoder_tokens))
  160. # Populate the first character of target sequence with the start character.
  161. target_seq[0, 0, target_token_index['\t']] = 1.
  162. # Sampling loop for a batch of sequences
  163. # (to simplify, here we assume a batch of size 1).
  164. stop_condition = False
  165. decoded_sentence = ''
  166. while not stop_condition:
  167. output_tokens, h, c = decoder_model.predict(
  168. [target_seq] + states_value)
  169. # Sample a token
  170. sampled_token_index = np.argmax(output_tokens[0, -1, :])
  171. sampled_char = reverse_target_char_index[sampled_token_index]
  172. decoded_sentence += sampled_char
  173. # Exit condition: either hit max length
  174. # or find stop character.
  175. if (sampled_char == '\n' or
  176. len(decoded_sentence) > max_decoder_seq_length):
  177. stop_condition = True
  178. # Update the target sequence (of length 1).
  179. target_seq = np.zeros((1, 1, num_decoder_tokens))
  180. target_seq[0, 0, sampled_token_index] = 1.
  181. # Update states
  182. states_value = [h, c]
  183. return decoded_sentence
  184. for seq_index in range(100):
  185. # Take one sequence (part of the training set)
  186. # for trying out decoding.
  187. input_seq = encoder_input_data[seq_index: seq_index + 1]
  188. decoded_sentence = decode_sequence(input_seq)
  189. print('-')
  190. print('Input sentence:', input_texts[seq_index])
  191. print('Decoded sentence:', decoded_sentence)
  192. def getBiLSTM_Dropout():
  193. '''
  194. @summary: 获得模型
  195. '''
  196. input_shape = (2, 35, 128)
  197. # input_shape = (1, 70, 128)
  198. output_shape = [5]
  199. L_input = layers.Input(shape=input_shape[1:], dtype="float32")
  200. R_input = layers.Input(shape=input_shape[1:], dtype="float32")
  201. lstm_0 = layers.Bidirectional(layers.LSTM(32, dropout=0.5, recurrent_dropout=0.5, return_sequences=True))(L_input)
  202. avg_0 = layers.GlobalAveragePooling1D()(lstm_0)
  203. lstm_2 = layers.Bidirectional(layers.LSTM(32, dropout=0.5, recurrent_dropout=0.5, return_sequences=True))(R_input)
  204. avg_2 = layers.GlobalAveragePooling1D()(lstm_2)
  205. concat = layers.merge([avg_0, avg_2], mode="concat")
  206. output = layers.Dense(output_shape[0], activation="softmax")(concat)
  207. model = models.Model(inputs=[L_input, R_input], outputs=output)
  208. model.compile(optimizer=optimizers.Adam(lr=0.0005), loss=losses.binary_crossentropy, metrics=[precision, recall, f1_score])
  209. return model
  210. def getBiRNN_Dropout():
  211. '''
  212. @summary: 获得模型
  213. '''
  214. input_shape = (2, 10, 128)
  215. output_shape = [5]
  216. L_input = layers.Input(shape=input_shape[1:], dtype="float32")
  217. R_input = layers.Input(shape=input_shape[1:], dtype="float32")
  218. lstm_0 = layers.Bidirectional(layers.SimpleRNN(32, dropout=0.65, recurrent_dropout=0.65, return_sequences=True))(L_input)
  219. avg_0 = layers.GlobalAveragePooling1D()(lstm_0)
  220. lstm_2 = layers.Bidirectional(layers.SimpleRNN(32, dropout=0.65, recurrent_dropout=0.65, return_sequences=True))(R_input)
  221. avg_2 = layers.GlobalAveragePooling1D()(lstm_2)
  222. concat = layers.merge([avg_0, avg_2], mode="concat")
  223. output = layers.Dense(output_shape[0], activation="softmax")(concat)
  224. model = models.Model(inputs=[L_input, R_input], outputs=output)
  225. model.compile(optimizer=optimizers.Adam(lr=0.0005), loss=losses.binary_crossentropy, metrics=[precision, recall, f1_score])
  226. return model
  227. def getBiGRU_Dropout():
  228. '''
  229. @summary: 获得模型
  230. '''
  231. input_shape = (2, 35, 128)
  232. # input_shape = (1, 70, 128)
  233. output_shape = [5]
  234. L_input = layers.Input(shape=input_shape[1:], dtype="float32")
  235. R_input = layers.Input(shape=input_shape[1:], dtype="float32")
  236. lstm_0 = layers.Bidirectional(layers.GRU(32, dropout=0.4, recurrent_dropout=0.4, return_sequences=True))(L_input)
  237. avg_0 = layers.GlobalAveragePooling1D()(lstm_0)
  238. lstm_2 = layers.Bidirectional(layers.GRU(32, dropout=0.4, recurrent_dropout=0.4, return_sequences=True))(R_input)
  239. avg_2 = layers.GlobalAveragePooling1D()(lstm_2)
  240. concat = layers.merge([avg_0, avg_2], mode="concat")
  241. output = layers.Dense(output_shape[0], activation="softmax")(concat)
  242. model = models.Model(inputs=[L_input, R_input], outputs=output)
  243. model.compile(optimizer=optimizers.Adam(lr=0.0005), loss=losses.binary_crossentropy, metrics=[precision, recall, f1_score])
  244. return model
  245. def getLSTM_Dropout():
  246. '''
  247. @summary: 获得模型
  248. '''
  249. input_shape = (2, 10, 128)
  250. output_shape = [5]
  251. input = layers.Input(shape=input_shape[1:], dtype="float32")
  252. lstm = layers.LSTM(32, dropout=0.2, recurrent_dropout=0.2, return_sequences=True)(input)
  253. avg = layers.GlobalAveragePooling1D()(lstm)
  254. output = layers.Dense(output_shape[0], activation="softmax")(avg)
  255. model = models.Model(inputs=input, outputs=output)
  256. model.compile(optimizer=optimizers.Adam(lr=0.0005), loss=losses.binary_crossentropy, metrics=[precision, recall, f1_score])
  257. return model
  258. def getGRUModel_Dropout():
  259. '''
  260. @summary: 获得模型
  261. '''
  262. # input_shape = (2, 10, 128)
  263. input_shape = (1, 70, 128)
  264. output_shape = [5]
  265. input = layers.Input(shape=input_shape[1:], dtype="float32")
  266. gru = layers.GRU(32, dropout=0.15, recurrent_dropout=0.15, return_sequences=True)(input)
  267. avg = layers.GlobalAveragePooling1D()(gru)
  268. output = layers.Dense(output_shape[0], activation="softmax")(avg)
  269. model = models.Model(inputs=input, outputs=output)
  270. model.compile(optimizer=optimizers.Adam(lr=0.0005), loss=losses.binary_crossentropy, metrics=[precision, recall, f1_score])
  271. return model
  272. def getRNNModel_Dropout():
  273. '''
  274. @summary: 获得模型
  275. '''
  276. input_shape = (2, 10, 128)
  277. output_shape = [5]
  278. input = layers.Input(shape=input_shape[1:], dtype="float32")
  279. rnn = layers.SimpleRNN(32, dropout=0.5, recurrent_dropout=0.5, return_sequences=True)(input)
  280. avg = layers.GlobalAveragePooling1D()(rnn)
  281. output = layers.Dense(output_shape[0], activation="softmax")(avg)
  282. model = models.Model(inputs=input, outputs=output)
  283. model.compile(optimizer=optimizers.Adam(lr=0.0005), loss=losses.binary_crossentropy, metrics=[precision, recall, f1_score])
  284. return model
  285. def getGCNModel():
  286. return
  287. def getData3(isTrain = True):
  288. '''
  289. :return:返回训练数据或测试数据的词嵌入,分前后两个句子,不包含中心词
  290. '''
  291. df = pd.read_csv("C:\\Users\\admin\\Desktop\\Person_Sentence_Notest_new.csv")
  292. df1 = pd.read_csv("C:\\Users\\admin\\Desktop\\test2000_new.csv")
  293. test_data_len = df.shape[0] * 0.2
  294. if isTrain:
  295. test_data_len = 0
  296. else:
  297. test_data_len = 3700
  298. df = df1
  299. df = df.reset_index()
  300. input_shape = (2, 35, 128)
  301. output_shape = [5]
  302. allLimit = 250000
  303. all = 0
  304. data_x = []
  305. data_y = []
  306. data_context = []
  307. for index, row in df.iterrows():
  308. if isTrain:
  309. if index < test_data_len:
  310. continue
  311. else:
  312. if index >= test_data_len:
  313. break
  314. if all >= allLimit:
  315. break
  316. tokens_list_front = []
  317. tokens_list_behind = []
  318. tokens_list_all = []
  319. sss = row["Sentence"].split("||")
  320. front = sss[0]
  321. behind = sss[2]
  322. ss_front = front.split(" ")
  323. ss_behind = behind.split(" ")
  324. for s in ss_front:
  325. tokens_list_front.append(s)
  326. for s in ss_behind:
  327. tokens_list_behind.append(s)
  328. tokens_list_all.append(tokens_list_front)
  329. tokens_list_all.append(tokens_list_behind)
  330. # print(np.array(tokens_list_all).shape)
  331. item_x = embedding(tokens_list_all, shape=input_shape)
  332. item_y = np.zeros(output_shape)
  333. item_y[row[3]] = 1
  334. all += 1
  335. data_x.append(item_x)
  336. data_y.append(item_y)
  337. data_x1, data_y1 = getDataFromPG((2, 35, 128), [5])
  338. data_x = data_x + data_x1
  339. data_y = data_y + data_y1
  340. print(np.array(data_x).shape, np.array(data_y).shape)
  341. return np.transpose(np.array(data_x), (1, 0, 2, 3)), np.array(data_y), data_context
  342. def getDataFromPG(input_shape, output_shape):
  343. conn = psycopg2.connect(dbname="BiddingKG", user="postgres", password="postgres",
  344. host="192.168.2.101")
  345. cursor = conn.cursor()
  346. sql = "select B.tokens,A.begin_index,A.end_index,C.label,A.entity_id " \
  347. "from train_entity_copy A,train_sentences_copy B,hand_label_person C " \
  348. "where A.doc_id=B.doc_id and A.sentence_index=B.sentence_index " \
  349. "and A.entity_type='person' and A.entity_id=C.entity_id and C.label!=0 " \
  350. "and C.label!=3;"
  351. cursor.execute(sql)
  352. print(sql)
  353. data_x = []
  354. data_y = []
  355. rows = cursor.fetchmany(1000)
  356. allLimit = 250000
  357. all = 0
  358. i = 0
  359. while(rows):
  360. for row in rows:
  361. if all >= allLimit:
  362. break
  363. item_x = embedding(spanWindow(tokens=row[0], begin_index=row[1], end_index=row[2],
  364. size=input_shape[1]), shape=input_shape)
  365. # item_x = encodeInput(spanWindow(tokens=row[0],begin_index=row[1],end_index=row[2],size=10), word_len=50, word_flag=True,userFool=False)
  366. # _span = spanWindow(tokens=row[0],begin_index=row[1],end_index=row[2],size=10,word_flag=False)
  367. # item_x = encodeInput(_span, word_len=10, word_flag=False,userFool=False)
  368. item_y = np.zeros(output_shape)
  369. item_y[row[3]] = 1
  370. all += 1
  371. data_x.append(item_x)
  372. data_y.append(item_y)
  373. i += 1
  374. rows = cursor.fetchmany(1000)
  375. return data_x, data_y
  376. def getData2(isTrain = True):
  377. '''
  378. :return:返回训练数据或测试数据的词嵌入,前后连成一个句子,包含中心词
  379. '''
  380. df = pd.read_csv("C:\\Users\\admin\\Desktop\\Person_Sentence_Notest.csv")
  381. df1 = pd.read_csv("C:\\Users\\admin\\Desktop\\test2000.csv")
  382. test_data_len = df.shape[0] * 0.2
  383. if isTrain:
  384. test_data_len = 0
  385. else:
  386. test_data_len = 3700
  387. df = df1
  388. df = df.reset_index()
  389. input_shape = (1, 70, 128)
  390. output_shape = [5]
  391. allLimit = 250000
  392. all = 0
  393. data_x = []
  394. data_y = []
  395. data_context = []
  396. for index, row in df.iterrows():
  397. if isTrain:
  398. if index < test_data_len:
  399. continue
  400. else:
  401. if index >= test_data_len:
  402. break
  403. if all >= allLimit:
  404. break
  405. tokens_list = []
  406. tokens_list_all = []
  407. ss = row["Sentence"].split(" ")
  408. for s in ss:
  409. tokens_list.append(s)
  410. tokens_list_all.append(tokens_list)
  411. item_x = embedding(tokens_list_all, shape=input_shape)
  412. item_y = np.zeros(output_shape)
  413. item_y[row[3]] = 1
  414. all += 1
  415. data_x.append(item_x)
  416. data_y.append(item_y)
  417. print(np.array(data_x).shape, np.array(data_y).shape)
  418. return np.transpose(np.array(data_x), (1, 0, 2, 3)), np.array(data_y), data_context
  419. def getData(isTrain = True):
  420. '''
  421. :return:返回训练数据或测试数据的词嵌入
  422. '''
  423. df = pd.read_csv("C:\\Users\\admin\\Desktop\\Person_Sentence_Notest.csv")
  424. df1 = pd.read_csv("C:\\Users\\admin\\Desktop\\test2000.csv")
  425. test_data_len = df.shape[0] * 0.2
  426. if isTrain:
  427. test_data_len = 0
  428. else:
  429. test_data_len = 3700
  430. df = df1
  431. df = df.reset_index()
  432. input_shape = (2, 35, 128)
  433. output_shape = [5]
  434. allLimit = 250000
  435. all = 0
  436. data_x = []
  437. data_y = []
  438. data_context = []
  439. for index, row in df.iterrows():
  440. if isTrain:
  441. if index < test_data_len:
  442. continue
  443. else:
  444. if index >= test_data_len:
  445. break
  446. if all >= allLimit:
  447. break
  448. print(np.array(spanWindow(tokens=row["Sentence"], begin_index=row["begin_index"], end_index=row["end_index"], size=input_shape[1])).shape)
  449. item_x = embedding(spanWindow(tokens=row["Sentence"], begin_index=row["begin_index"], end_index=row["end_index"], size=input_shape[1]), shape=input_shape)
  450. item_y = np.zeros(output_shape)
  451. item_y[row[3]] = 1
  452. all += 1
  453. data_x.append(item_x)
  454. data_y.append(item_y)
  455. print(np.array(data_x).shape, np.array(data_y).shape)
  456. # print(data_x, data_y, data_context)
  457. return np.transpose(np.array(data_x), (1, 0, 2, 3)), np.array(data_y), data_context
  458. def train():
  459. '''
  460. @summary: 训练模型
  461. '''
  462. model = getBiGRU_Dropout()
  463. model.summary()
  464. train_x, train_y, _ = getData3(isTrain=True)
  465. test_x, test_y, test_context = getData3(isTrain=False)
  466. # 回调checkpoint,保存loss最小的模型
  467. checkpoint = ModelCheckpoint(model_file, monitor="val_loss", verbose=1, save_best_only=True, mode='min')
  468. history_model = model.fit(x=[train_x[0], train_x[1]], class_weight='auto',
  469. y=train_y, validation_data=([test_x[0], test_x[1]], test_y),
  470. epochs=25, batch_size=256, shuffle=True, callbacks=[checkpoint])
  471. # history_model = model.fit(x=[train_x[0], train_x[0]], y=train_y, validation_data=([test_x[0], test_x[0]], test_y), class_weight='auto', epochs=100, batch_size=256, shuffle=True, callbacks=[checkpoint])
  472. # history_model = model.fit(x=[train_x[0], train_x[0]], y=train_y, validation_split=0.2, class_weight='auto', epochs=200, batch_size=256, shuffle=True, callbacks=[checkpoint])
  473. # 单向模型
  474. # history_model = model.fit(x=train_x[0], y=train_y, validation_data=([test_x[0], test_y]), class_weight='auto', epochs=200, batch_size=256, shuffle=True, callbacks=[checkpoint])
  475. # history_model = model.fit(x=train_x[0], y=train_y, validation_split=0.2, class_weight='auto', epochs=200, batch_size=256, shuffle=True, callbacks=[checkpoint])
  476. # history_model = model.fit(x=[train_x[0], train_x[1]], y=train_y, validation_split=0.2, epochs=100, class_weight='auto', batch_size=256, shuffle=True, callbacks=[checkpoint])
  477. # history_model = model.fit(x=[train_x[0], train_x[1]], y=train_y, validation_split=0.2, epochs=250, batch_size=256, shuffle=True, callbacks=[checkpoint])
  478. plotTrainTestLoss(history_model)
  479. def predict():
  480. model = models.load_model(model_file, custom_objects={'precision': precision, 'recall': recall, 'f1_score': f1_score})
  481. test_x, test_y, test_context = getData3(isTrain=False)
  482. predict_y = model.predict([test_x[0], test_x[1]])
  483. # predict_y = model.predict([test_x[0], test_x[0]])
  484. # predict_y = model.predict([test_x[0]])
  485. targets_name = ['人名', '招标联系人', '代理联系人', '联系人', '评审专家']
  486. print(classification_report(np.argmax(test_y, axis=1), np.argmax(predict_y, axis=1), target_names=targets_name))
  487. return predict_y
  488. def predict2Csv():
  489. df = pd.DataFrame(np.argmax(predict(), axis=1))
  490. df1 = pd.read_csv("C:\\Users\\admin\\Desktop\\test2000_new.csv")
  491. # df1 = pd.read_csv("C:\\Users\\admin\\Desktop\\Person_Sentence_Notest_new.csv")
  492. df1 = df1[0:3700]
  493. df1["predict_Label"] = df
  494. df1.to_csv("C:\\Users\\admin\\Desktop\\result3.csv")
  495. def plotTrainTestLoss(history_model):
  496. pyplot.plot(history_model.history['loss'])
  497. pyplot.plot(history_model.history['val_loss'])
  498. pyplot.title('model train vs validation loss')
  499. pyplot.ylabel('loss')
  500. pyplot.xlabel('epoch')
  501. pyplot.legend(['train', 'validation'], loc='upper right')
  502. pyplot.show()
  503. def hdf52savemodel():
  504. filepath = 'model_person_classify_fjs.model.hdf5'
  505. with tf.Graph().as_default() as graph:
  506. time_model = models.load_model(filepath, custom_objects={'precision': precision, 'recall': recall, 'f1_score': f1_score})
  507. with tf.Session() as sess:
  508. sess.run(tf.global_variables_initializer())
  509. h5_to_graph(sess, graph, filepath)
  510. tf.saved_model.simple_save(sess,
  511. "./person_savedmodel_new/",
  512. inputs={"input0":time_model.input[0],
  513. "input1":time_model.input[1]},
  514. outputs={"outputs":time_model.output})
  515. if __name__ == "__main__":
  516. # getData()
  517. # train()
  518. # predict()
  519. # predict2Csv()
  520. hdf52savemodel()
  521. # getData3()
  522. # x, y = getDataFromPG((2, 35, 128), [5])
  523. # print(x)
  524. # print(y)