Esempio n. 1
0
def start(data_file_name, model_file_name):
    """Saves trained paragraph vectors to a csv file in the *data* directory.

    Parameters
    ----------
    data_file_name: str
        Name of a file in the *data* directory that was used during training.

    model_file_name: str
        Name of a file in the *models* directory (a model trained on
        the *data_file_name* dataset).
    """
    dataset = load_dataset(data_file_name)
    model = _load_model(model_file_name,
                        num_docs=len(dataset),
                        num_words=len(dataset.fields['text'].vocab) - 1)

    def qm(str_):
        return '\"' + str_ + '\"'

    result_lines = []
    with open(join(DATA_DIR, data_file_name)) as file:
        lines = csv.reader(file)
        for i, line in enumerate(lines):
            result_line = [qm(x) if not x.isnumeric() else x for x in line[1:]]
            result_line += [str(x) for x in model._D[i, :].data.tolist()]
            result_lines.append(','.join(result_line) + '\n')

    result_file_name = model_file_name[:-7] + 'csv'
    with open(join(DATA_DIR, result_file_name), 'w') as f:
        f.writelines(result_lines)
Esempio n. 2
0
def start(data_file_name, model_file_name):
    """Saves trained paragraph vectors to a csv file in the *data* directory.

    Parameters
    ----------
    data_file_name: str
        Name of a file in the *data* directory that was used during training.

    model_file_name: str
        Name of a file in the *models* directory (a model trained on
        the *data_file_name* dataset).
    """
    dataset = load_dataset(data_file_name)
    model = _load_model(
        model_file_name,
        num_docs=len(dataset),
        num_words=len(dataset.fields['text'].vocab) - 1)

    def qm(str_): return '\"' + str_ + '\"'

    result_lines = []

    with open(join(DATA_DIR, data_file_name)) as file:
        lines = csv.reader(file)
        for i, line in enumerate(lines):
            result_line = [qm(x) if not x.isnumeric() else x for x in line[1:]]
            result_line += [str(x) for x in model.get_paragraph_vector(i)]
            result_lines.append(','.join(result_line) + '\n')

    result_file_name = model_file_name[:-7] + 'csv'

    with open(join(DATA_DIR, result_file_name), 'w') as f:
        f.writelines(result_lines)
def start(data_file_name, model_file_name):
    """Saves trained paragraph vectors to a csv file in the *data* directory.

    Parameters
    ----------
    data_file_name: str
        Name of a file in the *data* directory that was used during training.

    model_file_name: str
        Name of a file in the *models* directory (a model trained on
        the *data_file_name* dataset).
    """
    dataset = load_dataset(data_file_name)

    vec_dim = int(re.search('_vecdim\.(\d+)_', model_file_name).group(1))

    model = _load_model(model_file_name,
                        vec_dim,
                        num_docs=len(dataset),
                        num_words=len(dataset.fields['text'].vocab) - 1)

    _write_to_file(data_file_name, model_file_name, model, vec_dim)
Esempio n. 4
0
 def setUp(self):
     self.dataset = load_dataset('example.csv')
Esempio n. 5
0
def start(data_file_name,
          context_size,
          num_noise_words,
          vec_dim,
          num_epochs,
          batch_size,
          lr,
          model_ver='dm',
          vec_combine_method='sum',
          save_all=False,
          max_generated_batches=5,
          num_workers=1):
    """Trains a new model. The latest checkpoint and the best performing
    model are saved in the *models* directory.

    Parameters
    ----------
    data_file_name: str
        Name of a file in the *data* directory.

    context_size: int
        Half the size of a neighbourhood of target words (i.e. how many
        words left and right are regarded as context).

    num_noise_words: int
        Number of noise words to sample from the noise distribution.

    vec_dim: int
        Dimensionality of vectors to be learned (for paragraphs and words).

    num_epochs: int
        Number of iterations to train the model (i.e. number
        of times every example is seen during training).

    batch_size: int
        Number of examples per single gradient update.

    lr: float
        Learning rate of the Adam optimizer.

    model_ver: str, one of ('dm', 'dbow'), default='dm'
        Version of the model as proposed by Q. V. Le et al., Distributed
        Representations of Sentences and Documents. 'dm' stands for
        Distributed Memory, 'dbow' stands for Distributed Bag Of Words.
        Currently only the 'dm' version is implemented.

        But according to [doc2vec paper](http://proceedings.mlr.press/v32/le14.pdf) and [empirical analysis](https://arxiv.org/pdf/1607.05368.pdf), 'dbow' is running better

    vec_combine_method: str, one of ('sum', 'concat'), default='sum'
        Method for combining paragraph and word vectors in the 'dm' model.
        Currently only the 'sum' operation is implemented.

    save_all: bool, default=False
        Indicates whether a checkpoint is saved after each epoch.
        If false, only the best performing model is saved.

    max_generated_batches: int, default=5
        Maximum number of pre-generated batches.

    num_workers: int, default=1
        Number of batch generator jobs to run in parallel. If value is set
        to -1 number of machine cores are used.
    """
    assert model_ver in ('dm', 'dbow')
    assert vec_combine_method in ('sum', 'concat')

    init_logging('../experiments/experiments.{0}.id={1}.log'.format(
        'doc2vec', time.strftime('%Y%m%d-%H%M%S',
                                 time.localtime(time.time()))))

    dataset = load_dataset(data_file_name)
    nce_data = NCEData(dataset, batch_size, context_size, num_noise_words,
                       max_generated_batches, num_workers)
    nce_data.start()

    try:
        _run(nce_data, data_file_name, dataset, nce_data.get_batch(),
             len(nce_data), nce_data.vocabulary_size(),
             nce_data.number_examples, context_size, num_noise_words, vec_dim,
             num_epochs, batch_size, lr, model_ver, vec_combine_method,
             save_all)
    except KeyboardInterrupt:
        nce_data.stop()
Esempio n. 6
0
def start(data_file_name,
          context_size,
          num_noise_words,
          vec_dim,
          num_epochs,
          batch_size,
          lr,
          model_ver='dm',
          vec_combine_method='sum',
          save_all=False,
          max_generated_batches=5,
          num_workers=1):
    """Trains a new model. The latest checkpoint and the best performing
    model are saved in the *models* directory.

    Parameters
    ----------
    data_file_name: str
        Name of a file in the *data* directory.

    context_size: int
        Half the size of a neighbourhood of target words (i.e. how many
        words left and right are regarded as context).

    num_noise_words: int
        Number of noise words to sample from the noise distribution.

    vec_dim: int
        Dimensionality of vectors to be learned (for paragraphs and words).

    num_epochs: int
        Number of iterations to train the model (i.e. number
        of times every example is seen during training).

    batch_size: int
        Number of examples per single gradient update.

    lr: float
        Learning rate of the Adam optimizer.

    model_ver: str, one of ('dm', 'dbow'), default='dm'
        Version of the model as proposed by Q. V. Le et al., Distributed
        Representations of Sentences and Documents. 'dm' stands for
        Distributed Memory, 'dbow' stands for Distributed Bag Of Words.
        Currently only the 'dm' version is implemented.

        But according to [doc2vec paper](http://proceedings.mlr.press/v32/le14.pdf) and [empirical analysis](https://arxiv.org/pdf/1607.05368.pdf), 'dbow' is running better

    vec_combine_method: str, one of ('sum', 'concat'), default='sum'
        Method for combining paragraph and word vectors in the 'dm' model.
        Currently only the 'sum' operation is implemented.

    save_all: bool, default=False
        Indicates whether a checkpoint is saved after each epoch.
        If false, only the best performing model is saved.

    max_generated_batches: int, default=5
        Maximum number of pre-generated batches.

    num_workers: int, default=1
        Number of batch generator jobs to run in parallel. If value is set
        to -1 number of machine cores are used.
    """
    assert model_ver in ('dm', 'dbow')
    assert vec_combine_method in ('sum', 'concat')

    init_logging('../experiments/experiments.{0}.id={1}.log'.format('doc2vec', time.strftime('%Y%m%d-%H%M%S', time.localtime(time.time()))))

    dataset = load_dataset(data_file_name)
    nce_data = NCEData(
        dataset,
        batch_size,
        context_size,
        num_noise_words,
        max_generated_batches,
        num_workers)
    nce_data.start()

    try:
        _run(nce_data, data_file_name, dataset, nce_data.get_batch(), len(nce_data),
             nce_data.vocabulary_size(), nce_data.number_examples, context_size, num_noise_words, vec_dim,
             num_epochs, batch_size, lr, model_ver, vec_combine_method,
             save_all)
    except KeyboardInterrupt:
        nce_data.stop()
def start(data_file_name,
          num_noise_words,
          vec_dim,
          num_epochs,
          batch_size,
          lr,
          model_ver='dbow',
          context_size=0,
          vec_combine_method='sum',
          save_all=False,
          generate_plot=True,
          max_generated_batches=5,
          num_workers=1):
    """Trains a new model. The latest checkpoint and the best performing
    model are saved in the *models* directory.

    Parameters
    ----------
    data_file_name: str
        Name of a file in the *data* directory.

    model_ver: str, one of ('dm', 'dbow'), default='dbow'
        Version of the model as proposed by Q. V. Le et al., Distributed
        Representations of Sentences and Documents. 'dbow' stands for
        Distributed Bag Of Words, 'dm' stands for Distributed Memory.

    vec_combine_method: str, one of ('sum', 'concat'), default='sum'
        Method for combining paragraph and word vectors when model_ver='dm'.
        Currently only the 'sum' operation is implemented.

    context_size: int, default=0
        Half the size of a neighbourhood of target words when model_ver='dm'
        (i.e. how many words left and right are regarded as context). When
        model_ver='dm' context_size has to greater than 0, when
        model_ver='dbow' context_size has to be 0.

    num_noise_words: int
        Number of noise words to sample from the noise distribution.

    vec_dim: int
        Dimensionality of vectors to be learned (for paragraphs and words).

    num_epochs: int
        Number of iterations to train the model (i.e. number
        of times every example is seen during training).

    batch_size: int
        Number of examples per single gradient update.

    lr: float
        Learning rate of the Adam optimizer.

    save_all: bool, default=False
        Indicates whether a checkpoint is saved after each epoch.
        If false, only the best performing model is saved.

    generate_plot: bool, default=True
        Indicates whether a diagnostic plot displaying loss value over
        epochs is generated after each epoch.

    max_generated_batches: int, default=5
        Maximum number of pre-generated batches.

    num_workers: int, default=1
        Number of batch generator jobs to run in parallel. If value is set
        to -1 number of machine cores are used.
    """
    if model_ver not in ('dm', 'dbow'):
        raise ValueError("Invalid version of the model")

    model_ver_is_dbow = model_ver == 'dbow'

    if model_ver_is_dbow and context_size != 0:
        raise ValueError("Context size has to be zero when using dbow")
    if not model_ver_is_dbow:
        if vec_combine_method not in ('sum', 'concat'):
            raise ValueError("Invalid method for combining paragraph and word "
                             "vectors when using dm")
        if context_size <= 0:
            raise ValueError("Context size must be positive when using dm")

    dataset = load_dataset(data_file_name)
    nce_data = NCEData(dataset, batch_size, context_size, num_noise_words,
                       max_generated_batches, num_workers)
    nce_data.start()

    try:
        _run(data_file_name, dataset, nce_data.get_generator(), len(nce_data),
             nce_data.vocabulary_size(), context_size, num_noise_words,
             vec_dim, num_epochs, batch_size, lr, model_ver,
             vec_combine_method, save_all, generate_plot, model_ver_is_dbow)
    except KeyboardInterrupt:
        nce_data.stop()
Esempio n. 8
0
def start(data_file_name,
          context_size,
          num_noise_words,
          vec_dim,
          num_epochs,
          batch_size,
          lr,
          model_ver='dm',
          vec_combine_method='sum',
          save_all=False,
          max_generated_batches=5,
          num_workers=1):
    """Trains a new model. The latest checkpoint and the best performing
    model are saved in the *models* directory.

    Parameters
    ----------
    data_file_name: str
        Name of a file in the *data* directory.

    context_size: int
        Half the size of a neighbourhood of target words (i.e. how many
        words left and right are regarded as context).

    num_noise_words: int
        Number of noise words to sample from the noise distribution.

    vec_dim: int
        Dimensionality of vectors to be learned (for paragraphs and words).

    num_epochs: int
        Number of iterations to train the model (i.e. number
        of times every example is seen during training).

    batch_size: int
        Number of examples per single gradient update.

    lr: float
        Learning rate of the SGD optimizer (uses 0.9 nesterov momentum).

    model_ver: str, one of ('dm', 'dbow'), default='dm'
        Version of the model as proposed by Q. V. Le et al., Distributed
        Representations of Sentences and Documents. 'dm' stands for
        Distributed Memory, 'dbow' stands for Distributed Bag Of Words.
        Currently only the 'dm' version is implemented.

    vec_combine_method: str, one of ('sum', 'concat'), default='sum'
        Method for combining paragraph and word vectors in the 'dm' model.
        Currently only the 'sum' operation is implemented.

    save_all: bool, default=False
        Indicates whether a checkpoint is saved after each epoch.
        If false, only the best performing model is saved.

    max_generated_batches: int, default=5
        Maximum number of pre-generated batches.

    num_workers: int, default=1
        Number of batch generator jobs to run in parallel. If value is set
        to -1 number of machine cores are used.
    """
    assert model_ver in ('dm', 'dbow')
    assert vec_combine_method in ('sum', 'concat')

    dataset = load_dataset(data_file_name)
    nce_data = NCEData(
        dataset,
        batch_size,
        context_size,
        num_noise_words,
        max_generated_batches,
        num_workers)
    nce_data.start()

    try:
        _run(data_file_name, dataset, nce_data.get_generator(), len(nce_data),
             nce_data.vocabulary_size(), context_size, num_noise_words, vec_dim,
             num_epochs, batch_size, lr, model_ver, vec_combine_method,
             save_all)
    except KeyboardInterrupt:
        nce_data.stop()
Esempio n. 9
0
 def setUp(self):
     self.dataset = load_dataset('example.csv')