Пример #1
0
def test_model_nrms(mind_resource_path):
    train_news_file = os.path.join(mind_resource_path, "train", r"news.tsv")
    train_behaviors_file = os.path.join(mind_resource_path, "train",
                                        r"behaviors.tsv")
    valid_news_file = os.path.join(mind_resource_path, "valid", r"news.tsv")
    valid_behaviors_file = os.path.join(mind_resource_path, "valid",
                                        r"behaviors.tsv")
    wordEmb_file = os.path.join(mind_resource_path, "utils", "embedding.npy")
    userDict_file = os.path.join(mind_resource_path, "utils", "uid2index.pkl")
    wordDict_file = os.path.join(mind_resource_path, "utils", "word_dict.pkl")
    yaml_file = os.path.join(mind_resource_path, "utils", r"nrms.yaml")

    if not os.path.exists(train_news_file):
        download_deeprec_resources(
            r"https://recodatasets.z20.web.core.windows.net/newsrec/",
            os.path.join(mind_resource_path, "train"),
            "MINDdemo_train.zip",
        )
    if not os.path.exists(valid_news_file):
        download_deeprec_resources(
            r"https://recodatasets.z20.web.core.windows.net/newsrec/",
            os.path.join(mind_resource_path, "valid"),
            "MINDdemo_dev.zip",
        )
    if not os.path.exists(yaml_file):
        download_deeprec_resources(
            r"https://recodatasets.z20.web.core.windows.net/newsrec/",
            os.path.join(mind_resource_path, "utils"),
            "MINDdemo_utils.zip",
        )

    hparams = prepare_hparams(
        yaml_file,
        wordEmb_file=wordEmb_file,
        wordDict_file=wordDict_file,
        userDict_file=userDict_file,
        epochs=1,
    )
    assert hparams is not None

    iterator = MINDIterator
    model = NRMSModel(hparams, iterator)

    assert model.run_eval(valid_news_file, valid_behaviors_file) is not None
    assert isinstance(
        model.fit(train_news_file, train_behaviors_file, valid_news_file,
                  valid_behaviors_file),
        BaseModel,
    )
Пример #2
0
def test_nrms_component_definition(mind_resource_path):
    wordEmb_file = os.path.join(mind_resource_path, "utils", "embedding.npy")
    userDict_file = os.path.join(mind_resource_path, "utils", "uid2index.pkl")
    wordDict_file = os.path.join(mind_resource_path, "utils", "word_dict.pkl")
    yaml_file = os.path.join(mind_resource_path, "utils", r"nrms.yaml")

    if not os.path.exists(yaml_file):
        download_deeprec_resources(
            r"https://recodatasets.z20.web.core.windows.net/newsrec/",
            os.path.join(mind_resource_path, "utils"),
            "MINDdemo_utils.zip",
        )

    hparams = prepare_hparams(
        yaml_file,
        wordEmb_file=wordEmb_file,
        wordDict_file=wordDict_file,
        userDict_file=userDict_file,
        epochs=1,
    )
    iterator = MINDIterator
    model = NRMSModel(hparams, iterator)

    assert model.model is not None
    assert model.scorer is not None
    assert model.loss is not None
    assert model.train_optimizer is not None
Пример #3
0
def test_model_nrms(tmp):
    yaml_file = os.path.join(tmp, "nrms.yaml")
    train_file = os.path.join(tmp, "train.txt")
    valid_file = os.path.join(tmp, "test.txt")
    wordEmb_file = os.path.join(tmp, "embedding.npy")

    if not os.path.exists(yaml_file):
        download_deeprec_resources(
            "https://recodatasets.blob.core.windows.net/newsrec/", tmp,
            "nrms.zip")

    hparams = prepare_hparams(yaml_file, wordEmb_file=wordEmb_file, epochs=1)
    assert hparams is not None

    iterator = NewsIterator
    model = NRMSModel(hparams, iterator)

    assert model.run_eval(valid_file) is not None
    assert isinstance(model.fit(train_file, valid_file), BaseModel)
Пример #4
0
def dist_eval(args):
    iterator = MINDIterator
    model = NRMSModel(hparams, iterator, seed=seed)
    model.model.load_weights(
        os.path.join(model_dir, "ckpt_ep{}".format(args.ep)))
    test_news_file = os.path.join(data_path, "valid", 'news.tsv')
    test_behaviors_file = os.path.join(data_path, "valid",
                                       'behaviors.{}.tsv'.format(args.fsplit))

    group_impr_indexes, group_labels, group_preds = model.run_slow_eval(
        test_news_file, test_behaviors_file)

    with open(
            os.path.join(
                data_path,
                'results/nrms-valid-prediction.{}.txt'.format(args.fsplit)),
            'w') as f:
        for labels, preds in tqdm(zip(group_labels, group_preds)):
            label_str = ",".join([str(x) for x in labels])
            pred_str = ",".join([str(x) for x in preds])
            f.write("{}\t{}\n".format(label_str, pred_str))
Пример #5
0
def test(args):
    iterator = MINDIterator
    model = NRMSModel(hparams, iterator, seed=seed, test_mode=True)
    model.model.load_weights(
        os.path.join(model_dir, "ckpt_ep{}".format(args.ep)))
    test_news_file = os.path.join(data_path, "test", 'news.tsv')
    test_behaviors_file = os.path.join(data_path, "test",
                                       'behaviors.{}.tsv'.format(args.fsplit))

    group_impr_indexes, group_labels, group_preds = model.run_slow_eval(
        test_news_file, test_behaviors_file)

    with open(
            os.path.join(
                data_path,
                'results/nrms-test-prediction.{}.txt'.format(args.fsplit)),
            'w') as f:
        for impr_index, preds in tqdm(zip(group_impr_indexes, group_preds)):
            impr_index += 1
            pred_rank = (np.argsort(np.argsort(preds)[::-1]) + 1).tolist()
            pred_rank = '[' + ','.join([str(i) for i in pred_rank]) + ']'
            f.write(' '.join([str(impr_index), pred_rank]) + '\n')
Пример #6
0
def test_nrms_component_definition(tmp):
    yaml_file = os.path.join(tmp, "nrms.yaml")
    wordEmb_file = os.path.join(tmp, "embedding.npy")

    if not os.path.exists(yaml_file):
        download_deeprec_resources(
            "https://recodatasets.blob.core.windows.net/newsrec/", tmp,
            "nrms.zip")

    hparams = prepare_hparams(yaml_file, wordEmb_file=wordEmb_file, epochs=1)
    iterator = NewsIterator
    model = NRMSModel(hparams, iterator)

    assert model.model is not None
    assert model.scorer is not None
    assert model.loss is not None
    assert model.train_optimizer is not None
Пример #7
0
userDict_file = os.path.join(data_path, "utils", "uid2index.pkl")
wordDict_file = os.path.join(data_path, "utils", "word_dict_all.pkl")
yaml_file = os.path.join(data_path, "utils", r'nrms.yaml')
entityDict_file = os.path.join(data_path, "utils", "entity_dict_all.pkl")
entity_embedding_file = os.path.join(data_path, "utils", "entity_embeddings_5w_100_all.npy")
context_embedding_file = os.path.join(data_path, "utils", "context_embeddings_5w_100_all.npy")

hparams = prepare_hparams(yaml_file, wordEmb_file=wordEmb_file, \
                          wordDict_file=wordDict_file, userDict_file=userDict_file, \
                          epochs=epochs, entityEmb_file=entity_embedding_file, contextEmb_file=context_embedding_file, \
                          entityDict_file=entityDict_file,
                          show_step=10)
print(hparams)

iterator = MINDIterator
model = NRMSModel(hparams, iterator, seed=seed)
model_path = os.path.join(data_path, "model")
model.model.load_weights(os.path.join(model_path, "my_nrms_ckpt"))
f = open(test_behaviors_file)
print('total test samples:', len(f.readlines()))
f.close()

group_impr_indexes, group_labels, group_preds = model.run_fast_eval(test_news_file, test_behaviors_file, test=1)

import numpy as np
from tqdm import tqdm

with open(os.path.join(data_path, 'my_prediction.txt'), 'w') as f:
    for impr_index, preds in tqdm(zip(group_impr_indexes, group_preds)):
        impr_index += 1
        pred_rank = (np.argsort(np.argsort(preds)[::-1]) + 1).tolist()
Пример #8
0
    download_deeprec_resources(mind_url, os.path.join(data_path, 'train'),
                               mind_train_dataset)

if not os.path.exists(valid_news_file):
    download_deeprec_resources(mind_url, \
                               os.path.join(data_path, 'valid'), mind_dev_dataset)
if not os.path.exists(yaml_file):
    download_deeprec_resources(r'https://recodatasets.blob.core.windows.net/newsrec/', \
                               os.path.join(data_path, 'utils'), mind_utils)

hparams = prepare_hparams(yaml_file, wordEmb_file=wordEmb_file, \
                          wordDict_file=wordDict_file, userDict_file=userDict_file, \
                          epochs=epochs,
                          show_step=10)
print("[NRMS] Config,", hparams)

iterator = MINDIterator
model = NRMSModel(hparams, iterator, seed=seed)

print("[NRMS] First run:",
      model.run_eval(valid_news_file, fast_valid_behaviors_file))

model.fit(train_news_file,
          train_behaviors_file,
          valid_news_file,
          fast_valid_behaviors_file,
          model_save_path=model_dir)

# res_syn = model.run_eval(valid_news_file, valid_behaviors_file)
# print(res_syn)
Пример #9
0
                               os.path.join(data_path, 'test'), mind_test_dataset)
if not os.path.exists(yaml_file):
    download_deeprec_resources(r'https://recodatasets.blob.core.windows.net/newsrec/', \
                               os.path.join(data_path, 'utils'), mind_utils)

hparams = prepare_hparams(yaml_file, 
                          wordEmb_file=wordEmb_file,
                          wordDict_file=wordDict_file, 
                          userDict_file=userDict_file,
                          batch_size=batch_size,
                          epochs=epochs,
                          show_step=10)
print(hparams)

iterator = MINDIterator
model = NRMSModel(hparams, iterator, seed=seed)

# print(model.run_eval(valid_news_file, valid_behaviors_file))

model.fit(train_news_file, train_behaviors_file, valid_news_file, valid_behaviors_file)
# res_syn = model.run_eval(valid_news_file, valid_behaviors_file)
# print(res_syn)

# pm.record("res_syn", res_syn)

model_path = os.path.join(model_path, "model")
os.makedirs(model_path, exist_ok=True)

model.model.save_weights(os.path.join(model_path, "nrms_ckpt"))

group_impr_indexes, group_labels, group_preds = model.run_slow_eval(test_news_file, test_behaviors_file)
Пример #10
0
                          wordDict_file=wordDict_file, 
                          userDict_file=userDict_file,
                          vertDict_file=vertDict_file,
                          subvertDict_file=subvertDict_file,
                          batch_size=batch_size,
                          epochs=epochs,
                          show_step=10)
logging.info(hparams)


# ## Train the NRMS model


if model_type == 'nrms':
    iterator = MINDIterator
    model = NRMSModel(hparams, iterator, seed=seed)
elif model_type == 'naml':
    iterator = MINDAllIterator
    model = NAMLModel(hparams, iterator, seed=seed)
elif model_type == 'npa':
    iterator = MINDIterator
    model = NPAModel(hparams, iterator, seed=seed)
elif model_type == 'nrmma':
    iterator = MINDAllIterator
    model = NRMMAModel(hparams, iterator, seed=seed)

else:
    raise NotImplementedError(f"{exp_name} is not implemented")

# In[8]:
model_path = os.path.join(exp_path, model_type)
Пример #11
0
    download_deeprec_resources(
        r'https://recodatasets.blob.core.windows.net/newsrec/',
        os.path.join(data_root, 'utils'), mind_utils)

hparams = prepare_hparams(yaml_file,
                          wordEmb_file=wordEmb_file,
                          wordDict_file=wordDict_file,
                          userDict_file=userDict_file,
                          batch_size=batch_size,
                          epochs=epochs,
                          show_step=10)
logger.debug(f"hparams: {hparams}")

iterator = MINDIterator

model = NRMSModel(hparams, iterator, seed=seed)

logger.info(model.run_eval(valid_news_file, valid_behaviors_file))

model.fit(train_news_file, train_behaviors_file, valid_news_file,
          valid_behaviors_file)

res_syn = model.run_eval(valid_news_file, valid_behaviors_file)
logger.debug(f"res_syn: {res_syn}")

sb.glue("res_syn", res_syn)

model_path = os.path.join(BASE_DIR, "ckpt")
os.makedirs(model_path, exist_ok=True)

model.model.save_weights(os.path.join(model_path, "nrms_ckpt"))
Пример #12
0
# subvertDict_file = os.path.join(data_path, "utils", "subvert_dict.pkl")
# vertDict_file = os.path.join(data_path, "utils", "vert_dict.pkl")
yaml_file = os.path.join(data_path, "utils", '{}.yaml'.format(opt.model_name))

hparams = prepare_hparams(yaml_file,
                          wordEmb_file=wordEmb_file,
                          wordDict_file=wordDict_file,
                          userDict_file=userDict_file,
                          batch_size=batch_size,
                          epochs=epochs,
                          show_step=10)
print(hparams)

iterator = MINDIterator
if opt.model_name == 'nrms':
    model = NRMSModel(hparams, iterator, seed=seed)
elif opt.model_name == 'npa':  # model can not save
    model = NPAModel(hparams, iterator, seed=seed)
elif opt.model_name == 'lstur':
    model = LSTURModel(hparams, iterator, seed=seed)
elif opt.model_name == 'naml':  # problematic
    model = NAMLModel(hparams, iterator, seed=seed)

# print(model.run_slow_eval(news_file, valid_behaviors_file))

model.fit(news_file, train_behaviors_file, news_file, valid_behaviors_file)

# model_path = os.path.join(model_path, "model")
# os.makedirs(model_path, exist_ok=True)

# model.model.save_weights(os.path.join(model_path, "nrms_ckpt"))