def get_model(model_name): if model_name == 'cnn1': model = TextCNN( model_name='CNN', nb_epoch=10, max_len=config.word_maxlen, embed_size=config.embed_size, batch_size=128, lr=0.01, kfold=5, word_embed_weight=config.word_embed_weight, stack_path=config.stack_path, model_dir=config.model_dir, use_pretrained=True, trainable=True, # **kwargs ) if model_name == 'cnn2': model = TextCNN( model_name='CNN2', nb_epoch=10, max_len=config.word_maxlen, embed_size=config.embed_size, batch_size=128, lr=0.01, kfold=5, word_embed_weight=config.word_embed_weight, stack_path=config.stack_path, use_pretrained=True, trainable=True, # **kwargs ) if model_name == 'rnn1': model = TextRNN( model_name='RNN', nb_epoch=10, max_len=config.word_maxlen, embed_size=config.embed_size, batch_size=128, lr=0.01, kfold=5, word_embed_weight=config.word_embed_weight, stack_path=config.stack_path, model_dir=config.model_dir, use_pretrained=True, trainable=True, # **kwargs ) #0.66 if model_name == 'rnn2': model = TextRNN2( model_name='RNN2', nb_epoch=10, max_len=config.word_maxlen, embed_size=config.embed_size, batch_size=128, lr=0.01, kfold=5, word_embed_weight=config.word_embed_weight, stack_path=config.stack_path, model_dir=config.model_dir, use_pretrained=True, trainable=True, # **kwargs ) return model
def train(x_train, y_train, vocabulary, x_dev, y_dev): # Training # ================================================== with tf.Graph().as_default(): session_conf = tf.ConfigProto( allow_soft_placement=FLAGS.allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): cnn = TextCNN( sequence_length=x_train.shape[1], model_path= "/Users/pxu3/Desktop/Spring 2019/Research/Code/updated_pretrained_googlewv.bin", num_classes=y_train.shape[1], embedding_size=FLAGS.embedding_dim, filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), num_filters=FLAGS.num_filters, l2_reg_lambda=FLAGS.l2_reg_lambda) # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer(1e-3) grads_and_vars = optimizer.compute_gradients(cnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) # Keep track of gradient values and sparsity (optional) grad_summaries = [] for g, v in grads_and_vars: if g is not None: grad_hist_summary = tf.summary.histogram( "{}/grad/hist".format(v.name), g) sparsity_summary = tf.summary.scalar( "{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) grad_summaries.append(grad_hist_summary) grad_summaries.append(sparsity_summary) grad_summaries_merged = tf.summary.merge(grad_summaries) # Output directory for models and summaries timestamp = str(int(time.time())) out_dir = os.path.abspath( os.path.join(os.path.curdir, "runs", timestamp)) print("Writing to {}\n".format(out_dir)) # Summaries for loss and accuracy loss_summary = tf.summary.scalar("loss", cnn.loss) acc_summary = tf.summary.scalar("accuracy", cnn.accuracy) # Train Summaries train_summary_op = tf.summary.merge( [loss_summary, acc_summary, grad_summaries_merged]) train_summary_dir = os.path.join(out_dir, "summaries", "train") train_summary_writer = tf.summary.FileWriter( train_summary_dir, sess.graph) # Dev summaries dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) dev_summary_dir = os.path.join(out_dir, "summaries", "dev") dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it checkpoint_dir = os.path.abspath( os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints) # Write vocabulary with open('vocab.json', 'w') as fp: json.dump(vocabulary, fp, sort_keys=True, indent=4) # Initialize all variables sess.run(tf.global_variables_initializer()) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = { cnn.input_x: x_batch, cnn.input_y: y_batch, cnn.dropout_keep_prob: FLAGS.dropout_keep_prob } _, step, summaries, loss, accuracy = sess.run([ train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy ], feed_dict) time_str = datetime.datetime.now().isoformat() print("{}: step {}, loss {:g}, acc {:g}".format( time_str, step, loss, accuracy)) train_summary_writer.add_summary(summaries, step) def dev_step(x_batch, y_batch, writer=None): """ Evaluates model on a dev set """ feed_dict = { cnn.input_x: x_batch, cnn.input_y: y_batch, cnn.dropout_keep_prob: 1.0 } step, summaries, loss, accuracy = sess.run( [global_step, dev_summary_op, cnn.loss, cnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print("{}: step {}, loss {:g}, acc {:g}".format( time_str, step, loss, accuracy)) if writer: writer.add_summary(summaries, step) # Generate batches batches = get_data.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) # Training loop. For each batch... for batch in batches: x_batch, y_batch = zip(*batch) train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if current_step % FLAGS.evaluate_every == 0: print("\nEvaluation:") dev_step(x_dev, y_dev, writer=dev_summary_writer) print("") if current_step % FLAGS.checkpoint_every == 0: path = saver.save(sess, checkpoint_prefix, global_step=current_step) print("Saved model checkpoint to {}\n".format(path))
sents, labels = data_helper.load_data('./data/train.txt') test_sents, test_labels = data_helper.load_data('./data/test.txt') max_len = 1024 vocab = data_helper.read_vocab() data = data_helper.sent2idx(sents, vocab, max_len) test_data = data_helper.sent2idx(test_sents, vocab, max_len) epoch = 100 with tf.Graph().as_default(): session_conf = tf.ConfigProto() sess = tf.Session(config=session_conf) with sess.as_default(): cnn = TextCNN(vocab_size=len(vocab), seq_len=max_len, embedding_size=256, num_classes=2, filter_sizes=[3, 4, 5], num_filters=256) # 指定优化器(梯度下降) optimizer = tf.train.AdamOptimizer(1e-3) # 梯度 train_op = optimizer.minimize(cnn.loss) # 全局初始化 Initialize all variables sess.run(tf.global_variables_initializer()) train(cnn, data, labels, test_data, test_labels, epoch, sess, train_op)
y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:] del x, y, x_shuffled, y_shuffled #starting the traning session with tf.Graph().as_default(): session_conf = tf.ConfigProto( allow_soft_placement=FLAGS.allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): cnn = TextCNN(sequence_length=x_train.shape[1], num_classes=y_train.shape[1], vocab_size=len(vocab_processor.vocabulary_), embedding_size=FLAGS.embedding_dim, filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), num_filters=FLAGS.num_filters, l2_reg_lambda=FLAGS.l2_reg_lambda) # Defining the procedure global_step = tf.Variable(0, name="global_step", trainable=True) optimizer = tf.train.AdamOptimizer(1e-3) grads_and_vars = optimizer.compute_gradients(cnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) # Keep track of gradient values and sparsity (optional) grad_summaries = [] for g, v in grads_and_vars: if g is not None:
##### +code added until here (see functions in the helpers file) ##### # Training # ================================================== with tf.Graph().as_default(): session_conf = tf.ConfigProto( allow_soft_placement=FLAGS.allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): cnn = TextCNN(sequence_length=x_train.shape[1], num_classes=2, vocab_size=len(d_vocab), embedding_size=FLAGS.embedding_dim, filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), num_filters=FLAGS.num_filters, initW=initW, l2_reg_lambda=FLAGS.l2_reg_lambda) # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate) grads_and_vars = optimizer.compute_gradients(cnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) # Keep track of gradient values and sparsity (optional) grad_summaries = [] for g, v in grads_and_vars: