Exemple #1
0
def buzzy_title_based_sim_dfs(
        treat_strength,
        con_strength,
        noise_level,
        setting="simple",
        seed=0,
        base_output_dir='../dat/sim/peerread_buzzytitle_based/'):

    labeler = make_buzzy_based_simulated_labeler(treat_strength,
                                                 con_strength,
                                                 noise_level,
                                                 setting=setting,
                                                 seed=seed)

    num_splits = 10
    dev_splits = [0]
    test_splits = [0]

    # data_file = '../dat/reddit/proc.tf_record'
    # vocab_file = "../../bert/pre-trained/uncased_L-12_H-768_A-12/vocab.txt"
    tokenizer = tokenization.FullTokenizer(vocab_file=vocab_file,
                                           do_lower_case=True)

    input_dataset_from_filenames = make_input_fn_from_file(
        data_file,
        250,
        num_splits,
        dev_splits,
        test_splits,
        tokenizer,
        is_training=False,
        filter_test=False,
        shuffle_buffer_size=25000,
        seed=seed,
        labeler=labeler)

    output_df = dataset_fn_to_df(input_dataset_from_filenames)
    output_df = output_df.rename(index=str,
                                 columns={'theorem_referenced': 'treatment'})

    output_dir = os.path.join(base_output_dir, "mode{}".format(setting))
    os.makedirs(output_dir, exist_ok=True)
    output_path = os.path.join(
        output_dir,
        "beta0{}.beta1{}.gamma{}.tsv".format(treat_strength, con_strength,
                                             noise_level))

    output_df.to_csv(output_path, '\t')
def main(_):
    print("this program started")
    tf.enable_eager_execution()  # for debugging
    tf.set_random_seed(FLAGS.seed)

    tf.logging.set_verbosity(tf.logging.INFO)

    if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:
        raise ValueError(
            "At least one of `do_train`, `do_eval` or `do_predict' must be True.")

    bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)

    if FLAGS.max_seq_length > bert_config.max_position_embeddings:
        raise ValueError(
            "Cannot use sequence length %d because the BERT model "
            "was only trained up to sequence length %d" %
            (FLAGS.max_seq_length, bert_config.max_position_embeddings))

    tf.gfile.MakeDirs(FLAGS.output_dir)

    tokenizer = tokenization.FullTokenizer(
        vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)

    tpu_cluster_resolver = None
    if FLAGS.use_tpu and FLAGS.tpu_name:
        tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
            FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)

    is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
    run_config = tf.contrib.tpu.RunConfig(
        cluster=tpu_cluster_resolver,
        master=FLAGS.master,
        model_dir=FLAGS.output_dir,
        save_checkpoints_steps=FLAGS.save_checkpoints_steps,
        keep_checkpoint_max=FLAGS.keep_checkpoints,
        # save_checkpoints_steps=None,
        # save_checkpoints_secs=None,
        save_summary_steps=10,
        tpu_config=tf.contrib.tpu.TPUConfig(
            iterations_per_loop=FLAGS.iterations_per_loop,
            num_shards=FLAGS.num_tpu_cores,
            per_host_input_for_training=is_per_host))

    # Estimator and data pipeline setup

    label_dict = \
        {'accepted': 2,
         'abstract_contains_deep': 2,
         'abstract_contains_neural': 2,
         'abstract_contains_embedding': 2,
         'abstract_contains_outperform': 2,
         'abstract_contains_novel': 2,
         'abstract_contains_state_of_the_art': 2,
         'abstract_contains_state-of-the-art': 2,
         'title_contains_deep': 2,
         'title_contains_neural': 2,
         'title_contains_embedding': 2,
         'contains_appendix': 2,
         'theorem_referenced': 2,
         'equation_referenced': 2,
         'year': 11,
         'venue': 9,
         'arxiv': 3}

    params = {'target_name': FLAGS.label, 'num_labels': label_dict[FLAGS.label]}
    dev_splits = [int(s) for s in str.split(FLAGS.dev_splits)]
    test_splits = [int(s) for s in str.split(FLAGS.test_splits)]

    num_train_steps = FLAGS.num_train_steps
    num_warmup_steps = FLAGS.num_warmup_steps

    model_fn = multiclass_model_fn_builder(
        bert_config=bert_config,
        init_checkpoint=FLAGS.init_checkpoint,
        learning_rate=FLAGS.learning_rate,
        num_train_steps=num_train_steps,
        num_warmup_steps=num_warmup_steps,
        use_tpu=FLAGS.use_tpu,
        use_one_hot_embeddings=FLAGS.use_tpu,
        label_pred=FLAGS.label_pred,
        unsupervised=FLAGS.unsupervised,
        polyak=False)

    # If TPU is not available, this will fall back to normal Estimator on CPU
    # or GPU.
    estimator = tf.contrib.tpu.TPUEstimator(
        use_tpu=FLAGS.use_tpu,
        model_fn=model_fn,
        config=run_config,
        train_batch_size=FLAGS.train_batch_size,
        eval_batch_size=FLAGS.eval_batch_size,
        predict_batch_size=FLAGS.predict_batch_size,
        params=params)

    if FLAGS.do_train:
        input_files_or_glob = FLAGS.input_files_or_glob

        tf.logging.info("***** Running training *****")
        tf.logging.info("  Batch size = %d", FLAGS.train_batch_size)
        tf.logging.info("  Num steps = %d", num_train_steps)

        # subsample and process the data
        with tf.name_scope("training_data"):
            train_input_fn = make_input_fn_from_file(
                input_files_or_glob=input_files_or_glob,
                seq_length=FLAGS.max_seq_length,
                num_splits=FLAGS.num_splits,
                dev_splits=dev_splits,
                test_splits=test_splits,
                tokenizer=tokenizer,
                is_training=True,
                shuffle_buffer_size=25000,  # note: bert hardcoded this, and I'm following suit
                seed=FLAGS.seed)

        # additional logging
        hooks = []
        if FLAGS.label_pred:
            hooks += [
                tf.train.LoggingTensorHook({
                    # 'token_ids': 'token_ids',
                    # 'token_mask': 'token_mask',
                    # 'label_ids': 'label_ids',
                    # 'pred_in': 'summary/in_split/predictions',
                    # 'pred_out': 'summary/out_split/predictions',
                    # 'ra_in': 'summary/in_split/labels/kappa/batch_random_agreement/random_agreement',
                    # 'ra_out': 'summary/out_split/labels/kappa/batch_random_agreement/random_agreement',
                },
                    every_n_iter=1000)
            ]

        estimator.train(input_fn=train_input_fn, max_steps=num_train_steps, hooks=hooks)

    if FLAGS.do_train and (FLAGS.do_eval or FLAGS.do_predict):
        # reload the model to get rid of dropout and input token masking
        trained_model_checkpoint = tf.train.latest_checkpoint(FLAGS.output_dir)
        model_fn = multiclass_model_fn_builder(
            bert_config=bert_config,
            init_checkpoint=trained_model_checkpoint,
            learning_rate=FLAGS.learning_rate,
            num_train_steps=num_train_steps,
            num_warmup_steps=num_warmup_steps,
            use_tpu=FLAGS.use_tpu,
            use_one_hot_embeddings=FLAGS.use_tpu,
            label_pred=True,
            unsupervised=False,
            polyak=False
        )

        estimator = tf.contrib.tpu.TPUEstimator(
            use_tpu=FLAGS.use_tpu,
            model_fn=model_fn,
            config=run_config,
            train_batch_size=FLAGS.train_batch_size,
            eval_batch_size=FLAGS.eval_batch_size,
            predict_batch_size=FLAGS.predict_batch_size,
            params=params)

    if FLAGS.do_eval:

        tf.logging.info("***** Running evaluation *****")
        # tf.logging.info("  Num examples = %d", len(eval_examples))
        tf.logging.info("  Batch size = %d", FLAGS.eval_batch_size)

        # This tells the estimator to run through the entire set.
        eval_steps = None
        # However, if running eval on the TPU, you will need to specify the
        # number of steps.
        if FLAGS.use_tpu:
            # Eval will be slightly WRONG on the TPU because it will truncate
            # the last batch.
            pass
            # eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size)

        eval_drop_remainder = True if FLAGS.use_tpu else False
        eval_input_fn = make_input_fn_from_file(
                input_files_or_glob=FLAGS.input_files_or_glob,
                seq_length=FLAGS.max_seq_length,
                num_splits=FLAGS.num_splits,
                dev_splits=dev_splits,
                test_splits=test_splits,
                tokenizer=tokenizer,
                is_training=False,
                filter_test=False,
                seed=FLAGS.seed)

        result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)

        output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
        with tf.gfile.GFile(output_eval_file, "w") as writer:
            tf.logging.info("***** Eval results *****")
            for key in sorted(result.keys()):
                tf.logging.info("  %s = %s", key, str(result[key]))
                writer.write("%s = %s\n" % (key, str(result[key])))

    if FLAGS.do_predict:
        tf.logging.info("***** Running prediction*****")

        if FLAGS.use_tpu:
            # Warning: According to tpu_estimator.py Prediction on TPU is an
            # experimental feature and hence not supported here
            raise ValueError("Prediction in TPU not supported")

        predict_input_fn = make_input_fn_from_file(
                input_files_or_glob=FLAGS.input_files_or_glob,
                seq_length=FLAGS.max_seq_length,
                num_splits=FLAGS.num_splits,
                dev_splits=dev_splits,
                test_splits=test_splits,
                tokenizer=tokenizer,
                is_training=False,
                filter_test=False,
                seed=FLAGS.seed)

        result = estimator.predict(input_fn=predict_input_fn)

        output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
        with tf.gfile.GFile(output_predict_file, "w") as writer:
            tf.logging.info("***** Predict results *****")

            attribute_names = ['in_test',
                               'treatment_probability',
                               'expected_outcome_st_treatment', 'expected_outcome_st_no_treatment',
                               'outcome', 'treatment']

            header = "\t".join(
                attribute_name for attribute_name in attribute_names) + "\n"
            writer.write(header)
            for prediction in result:
                output_line = "\t".join(
                    str(prediction[attribute_name]) for attribute_name in attribute_names) + "\n"
                writer.write(output_line)
Exemple #3
0
def propensity_sim_ground_truth_and_naive_from_dataset(
        beta0=0.25,
        beta1=0.0,
        gamma=0.0,
        exogenous_confounding=0.0,
        setting='simple',
        tfrecord_file='../dat/PeerRead/proc/arxiv-all.tf_record',
        vocab_file="../../bert/pre-trained/uncased_L-12_H-768_A-12/vocab.txt",
        base_propensities_path='logs/peerread/arxiv/joint_dragon/seed0/o_accepted_t_buzzy_title/split0/predict/test_results.tsv',
        seed=0):
    """
    This is a helper function that computes the ground truth and naive estimates
    by creating a tf dataset and 'sampling' the required observed data.
    This is necessary because we simulate outcomes on the fly using tf's dataset abstraction.

    :return:
    """

    output = pd.read_csv(base_propensities_path, '\t')
    base_propensity_scores = output['treatment_probability'].values
    # print(base_propensity_scores)
    example_indices = output['index'].values

    labeler = make_propensity_based_simulated_labeler(
        treat_strength=beta0,
        con_strength=beta1,
        noise_level=gamma,
        base_propensity_scores=base_propensity_scores,
        example_indices=example_indices,
        exogeneous_con=exogenous_confounding,
        setting=setting,
        seed=seed)

    tokenizer = tokenization.FullTokenizer(vocab_file=vocab_file,
                                           do_lower_case=True)

    input_fn = make_input_fn_from_file(tfrecord_file,
                                       250,
                                       num_splits=10,
                                       dev_splits=[0],
                                       test_splits=[0],
                                       tokenizer=tokenizer,
                                       is_training=True,
                                       filter_test=False,
                                       shuffle_buffer_size=25000,
                                       labeler=labeler,
                                       seed=0)

    # input_fn = make_input_fn_from_tfrecord(tokenizer=tokenizer, tfrecord=tfrecord_file)

    params = {'batch_size': 4096}

    dataset = input_fn(params)
    sampler = dataset.make_one_shot_iterator()
    sample = sampler.get_next()

    with tf.Session() as sess:
        # confounding = sess.run(sample['confounding'])
        y, y0, y1, t = sess.run([
            sample['outcome'], sample['y0'], sample['y1'], sample['treatment']
        ])

    tf.reset_default_graph()

    ground_truth = y1.mean() - y0.mean()
    very_naive = y1[t == 1].mean() - y0[t == 0].mean()

    return {'ground_truth': ground_truth, 'noiseless_very_naive': very_naive}
Exemple #4
0
def buzzy_sim_ground_truth_and_naive_from_dataset(
        beta0=0.25,
        beta1=0.0,
        gamma=0.0,
        setting='simple',
        tfrecord_file='../dat/PeerRead/proc/arxiv-all.tf_record',
        vocab_file="../../bert/pre-trained/uncased_L-12_H-768_A-12/vocab.txt",
        seed=0):
    """
    This is a helper function that computes the ground truth and naive estimates
    by creating a tf dataset and 'sampling' the required observed data.
    This is necessary because we simulate outcomes on the fly using tf's dataset abstraction.


    :return:
    """

    tokenizer = tokenization.FullTokenizer(vocab_file=vocab_file,
                                           do_lower_case=True)
    labeler = make_buzzy_based_simulated_labeler(treat_strength=beta0,
                                                 con_strength=beta1,
                                                 noise_level=gamma,
                                                 setting=setting,
                                                 seed=seed)

    input_fn = make_input_fn_from_file(tfrecord_file,
                                       250,
                                       num_splits=10,
                                       dev_splits=[0],
                                       test_splits=[0],
                                       tokenizer=tokenizer,
                                       is_training=True,
                                       filter_test=False,
                                       shuffle_buffer_size=25000,
                                       labeler=labeler,
                                       seed=0)

    # input_fn = make_input_fn_from_tfrecord(tokenizer=tokenizer, tfrecord=tfrecord_file)

    params = {'batch_size': 4096}

    dataset = input_fn(params)
    sampler = dataset.make_one_shot_iterator()
    sample = sampler.get_next()

    with tf.Session() as sess:
        # confounding = sess.run(sample['confounding'])
        y, y0, y1, t = sess.run([
            sample['outcome'], sample['y0'], sample['y1'],
            sample['theorem_referenced']
        ])

    tf.reset_default_graph()

    # print(y0[t==0].mean())
    # print(y1[t==1].mean())

    ground_truth = y1.mean() - y0.mean()
    noiseless_naive = y1[t == 1].mean() - y0[t == 0].mean()
    very_naive = y[t == 1].mean() - y[t == 0].mean()

    return {
        'ground_truth': ground_truth,
        'very_naive': very_naive,
        'noiseless_naive': noiseless_naive
    }