def exe(word_vectors_file, vector_preloaded_path, test_path, sent, hidden_sizes, maxlen, mix): global word_vectors, vocabs if not maxlen: maxlen = properties.maxlen if word_vectors is None or vocabs is None: word_vectors, vocabs = utils.loadWordVectors(word_vectors_file, vector_preloaded_path) if sent: if sent: test_x = [utils.make_sentence_idx(vocabs, sent.lower(), maxlen)] test_y = [1] else: #auto test path_file test_x, test_y = utils.load_file(test_path) if mix is 'Y': combined = LSTM_CNN(word_vectors, hidden_sizes=hidden_sizes) errors = combined.build_test_model((test_x, test_y, maxlen)) else: lstm = Model(word_vectors, hidden_sizes=hidden_sizes) errors = lstm.build_test_model((test_x, test_y, maxlen)) if sent: pred = errors if pred: print "sentiment is positive" else: print "sentiment is negative" elif errors: print("Accuracy of test is: %.5f %" % (1 - errors) * 100)
def exe(word_vectors_file, vector_preloaded_path, train_path, dev_path, test_path, hsi, hso, maxlen, pep, fep, ppat, fpat, plr, flr, mix): global word_vectors, vocabs if os.path.exists(train_path) and os.path.exists( dev_path) and os.path.exists(test_path): train = utils.load_file(train_path) dev = utils.load_file(dev_path) test = utils.load_file(test_path) else: raise NotImplementedError() if word_vectors is None or vocabs is None: word_vectors, vocabs = utils.loadWordVectors(word_vectors_file, vector_preloaded_path) if not maxlen: maxlen = properties.maxlen lstm = Model(word_vectors, hidden_sizes=[hsi, hso], epochs=pep, patience=ppat, learning_rate=plr) lstm_params = lstm.train(train, dev, test, maxlen) if mix is 'Y': combined = LSTM_CNN(word_vectors, hidden_sizes=[hsi, hso], epochs=fep, lstm_params=lstm_params) combined.train(train, dev, test, maxlen)
# Training # ================================================== with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) sess = tf.Session(config=session_conf) with sess.as_default(): # embed() if (MODEL_TO_RUN == 0): model = CNN_LSTM(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim, filter_sizes, num_filters, l2_reg_lambda) elif (MODEL_TO_RUN == 1): model = LSTM_CNN(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim, filter_sizes, num_filters, l2_reg_lambda) elif (MODEL_TO_RUN == 2): model = CNN(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim, filter_sizes, num_filters, l2_reg_lambda) elif (MODEL_TO_RUN == 3): model = LSTM(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim) else: print "PLEASE CHOOSE A VALID MODEL!\n0 = CNN_LSTM\n1 = LSTM_CNN\n2 = CNN\n3 = LSTM\n" exit() # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False)
with open("train_large.txt") as train_fnames: for line in train_fnames: train_f.append(line.split(" ")[0]) with open("test_large.txt") as test_fnames: for line in test_fnames: test_f.append(line.split(" ")[0]) # setup model lstm_model = Basic_LSTM(num_units=80, learning_rate=0.001, dropout_rate=0.5, debug=False) lstm_cnn_model = LSTM_CNN(num_units=100, learning_rate=0.001, dropout_rate=0.5, cnn_args={ 'filter_size': 30, 'filter_num': 48 }, debug=False) bilstm_model = BiLSTM(learning_rate=0.001, dropout_rate=0.5, debug=False) deep_cnn_lstm_model = DeepCNN_LSTM(dropout_rate=0.0, reg_constant=0.01) deeper_cnn_lstm_model = DeeperCNN_LSTM(dropout_rate=0.0, reg_constant=0.01) # select which one to use model = deep_cnn_lstm_model # data config D_config = { "batch_size": 90, "shuffle": False, "balance": False,
dev_sample_index = -1 * int(config.dev_size * float(len(y))) x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[ dev_sample_index:] y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[ dev_sample_index:] print("Vocabulary Size: {:d}".format(len(vocabulary))) print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev))) # model build print('{}'.format('#' * 30)) print('model build') model = LSTM_CNN( sequence_length=8, num_classes=10, # 여기서 class 개수를 수정해야 한다 vocab_size=803087, embedding_size=config.embedding_dim, filter_sizes=list(map(int, config.filter_sizes.split(","))), num_filters=config.num_filters, l2_reg_lambda=config.l2_reg_lambda, num_hidden=config.hiddensize) # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer(config.lr) grads_and_vars = optimizer.compute_gradients(model.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) print('{}'.format('#' * 30)) print('sess open') sesstime = time.time()
with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) sess = tf.Session(config=session_conf) with sess.as_default(): #embed() if (MODEL_TO_RUN == 0): model = CNN_LSTM(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim, filter_sizes, num_filters, l2_reg_lambda) elif (MODEL_TO_RUN == 1): model = LSTM_CNN(max_seq_legth, 1, n_symbols, embedding_dim, filter_sizes, num_filters, l2_reg_lambda, weight=embedding_weights) elif (MODEL_TO_RUN == 2): model = CNN(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim, filter_sizes, num_filters, l2_reg_lambda) elif (MODEL_TO_RUN == 3): model = LSTM(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim) else: print( "PLEASE CHOOSE A VALID MODEL!\n0 = CNN_LSTM\n1 = LSTM_CNN\n2 = CNN\n3 = LSTM\n" ) exit()
print(y_train.shape) # Training # ================================================== with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) sess = tf.Session(config=session_conf) with sess.as_default(): # embed() if (MODEL_TO_RUN == 0): model = CNN_LSTM(x_train.shape[1], y_train.shape[1], embedding_dim, filter_sizes, num_filters, num_hidden) elif (MODEL_TO_RUN == 1): model = LSTM_CNN(x_train.shape[1], y_train.shape[1], 21, embedding_dim, filter_sizes, num_filters, l2_reg_lambda) elif (MODEL_TO_RUN == 2): model = CNN(x_train.shape[1], y_train.shape[1], 26, embedding_dim, filter_sizes, num_filters, l2_reg_lambda) elif (MODEL_TO_RUN == 3): model = LSTM(x_train.shape[1], y_train.shape[1], 26, embedding_dim) else: print "PLEASE CHOOSE A VALID MODEL!\n0 = CNN_LSTM\n1 = LSTM_CNN\n2 = CNN\n3 = LSTM\n" exit() # 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(model.loss)
def train(x_train, y_train, vocab_processor, x_dev, y_dev, embedding): # 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=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) lstm_cnn = LSTM_CNN(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim = 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(lstm_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", lstm_cnn.loss) acc_summary = tf.summary.scalar("accuracy", lstm_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 vocab_processor.save(os.path.join(out_dir, "vocab")) # Initialize all variables init = tf.global_variables_initializer() sess.run(lstm_cnn.embedding_init, feed_dict={lstm_cnn.embedding_placeholder: embedding}) sess.run(init) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = { lstm_cnn.input_x: x_batch, lstm_cnn.input_y: y_batch, lstm_cnn.dropout_keep_prob: FLAGS.dropout_keep_prob } _, step, summaries, loss, accuracy = sess.run( [train_op, global_step, train_summary_op, lstm_cnn.loss, lstm_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 = { lstm_cnn.input_x: x_batch, lstm_cnn.input_y: y_batch, lstm_cnn.dropout_keep_prob: 1.0 } step, summaries, loss, accuracy = sess.run( [global_step, dev_summary_op, lstm_cnn.loss, lstm_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 = data_helpers.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))
y_tr = y_train[train_index].astype(np.int32) y_val = y_train[val_index].astype(np.int32) print("Validation shape: {}".format(X_val.shape)) print("Training shape: {}".format(X_tr.shape)) with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) sess = tf.Session(config=session_conf) with sess.as_default(): #embed() if (MODEL_TO_RUN == 0): model = CNN_LSTM(seq_legth, num_classes, embedding_dim, filter_sizes, num_filters) elif (MODEL_TO_RUN == 1): model = LSTM_CNN(seq_legth, num_classes, embedding_dim, filter_sizes, num_filters, num_hidden) # elif (MODEL_TO_RUN == 2): # model = CNN(x_train.shape[1],y_train.shape[1],len(vocab_processor.vocabulary_), # embedding_dim,filter_sizes,num_filters,l2_reg_lambda) # elif (MODEL_TO_RUN == 3): # model = LSTM(x_train.shape[1],y_train.shape[1],len(vocab_processor.vocabulary_),embedding_dim) else: print( "PLEASE CHOOSE A VALID MODEL!\n0 = CNN_LSTM\n1 = LSTM_CNN\n2 = CNN\n3 = LSTM\n" ) exit() # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer() grads_and_vars = optimizer.compute_gradients(model.loss)
x_shuffled = x[shuffle_indices] y_shuffled = y[shuffle_indices] dev_sample_index = -1 * int(config.DEV_SIZE * float(len(y))) x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:] y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:] logger.info("Vocabulary Size: {:d}".format(len(vocab_processor.vocabulary_))) logger.info("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev))) with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) sess = tf.Session(config=session_conf) with sess.as_default(): model = LSTM_CNN(x_train.shape[1], y_train.shape[1], len(vocab_processor.vocabulary_), embedding_dim, config.FILTER_SIZE, config.NUM_FILTERS, config.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(model.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)