test_model_fjs.py 22 KB

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