def evaluate(sess, x, y, seq_lens, batch_size): data_len = len(x) batch_eval = batch_iter(x, y, seq_lens, batch_size) total_loss = 0.0 total_acc = 0.0 for x_batch, y_batch, seq_lens_batch in batch_eval: batch_len = len(x_batch) feed_dict = { model.content: x_batch, model.label: y_batch, model.sequence_lengths: seq_lens_batch } loss, acc = sess.run([model.loss, model.accuracy], feed_dict=feed_dict) total_loss += loss * batch_len total_acc += acc * batch_len return total_loss / data_len, total_acc / data_len
def train(): # 配置TensorBoard和Saver print('Configuring TensorBoard and Saver...') saver = tf.train.Saver() if not os.path.exists(save_dir): os.makedirs(save_dir) if not os.path.exists(tensorboard_dir): os.makedirs(tensorboard_dir) tf.summary.scalar('loss', model.loss) tf.summary.scalar('accuracy', model.accuracy) merged_summary = tf.summary.merge_all() writer = tf.summary.FileWriter(tensorboard_dir) # 处理数据 print('Loading training data and validation data...') start_time = time.time() x_train, y_train, seq_lens_train = process_file(train_dir, word_to_id, label_to_id, config.seq_length) x_val, y_val, seq_lens_val = process_file(val_dir, word_to_id, label_to_id, config.seq_length) print('Time usage:', get_time_dif(start_time)) # 创建session session = tf.Session() session.run(tf.global_variables_initializer()) # 将图添加到TensorBoard中 writer.add_graph(session.graph) # 开始训练 print('Start training...') start_time = time.time() best_acc_val = 0.0 total_batch = 0 for epoch in range(config.epoch): batch_train = batch_iter(x_train, y_train, seq_lens_train, config.batch_size) for x_batch, y_batch, seq_lens_batch in batch_train: feed_dict = { model.content: x_batch, model.label: y_batch, model.sequence_lengths: seq_lens_batch } # 将训练结果写如到TensorBoard中 if total_batch % config.save_pre_batch == 0: s = session.run(merged_summary, feed_dict=feed_dict) writer.add_summary(s, total_batch) # 输出训练集和验证集的结果,并保存最好的模型 if total_batch % config.print_pre_batch == 0: loss_train, acc_train = session.run( [model.loss, model.accuracy], feed_dict=feed_dict) loss_val, acc_val = evaluate(session, x_val, y_val, seq_lens_val, config.batch_size) # 每次只保存最好的模型 if acc_val > best_acc_val: best_acc_val = acc_val saver.save(session, save_path) improved_str = '*' else: improved_str = '' time_dif = get_time_dif(start_time) msg = 'Iter: {0:>2}, Train Loss: {1:>2.2f}, Train Acc: {2:>2.2%}, ' \ 'Val Loss: {3:>2.2f}, Val Acc: {4:>2.2%}, Time: {5} {6}' print( msg.format(total_batch, loss_train, acc_train, loss_val, acc_val, time_dif, improved_str)) session.run(model.optimizer, feed_dict=feed_dict) total_batch += 1