Spec-Zone.ru › TensorFlow 2.3

tf.nn.nce_loss

Просмотреть исходный код на GitHub

Вычисляет и возвращает обучающую потерю оценки шума-контраста.

tf.nn.nce_loss(
    weights, biases, labels, inputs, num_sampled, num_classes, num_true=1,
    sampled_values=None, remove_accidental_hits=False, name='nce_loss'
)

См. Оценка шума-контраста: новый принцип оценки для ненормализованных статистических моделей. Также см. нашу Справочник по алгоритмам выборки кандидатов

Распространённый случай использования этого метода — обучение, а вычисление полной сигмоидальной потери для оценки или вывода, как в следующем примере:

if mode == "train":
  loss = tf.nn.nce_loss(
      weights=weights,
      biases=biases,
      labels=labels,
      inputs=inputs,
      ...)
elif mode == "eval":
  logits = tf.matmul(inputs, tf.transpose(weights))
  logits = tf.nn.bias_add(logits, biases)
  labels_one_hot = tf.one_hot(labels, n_classes)
  loss = tf.nn.sigmoid_cross_entropy_with_logits(
      labels=labels_one_hot,
      logits=logits)
  loss = tf.reduce_sum(loss, axis=1)
Примечание: при выполнении поиска вложения weights и bias, будет использоваться стратегия разбиения «div». Поддержка других стратегий разбиения будет добавлена позже.
Примечание: По умолчанию для выборки используется логарифмически равномерное (зиффовское) распределение, поэтому ваши метки должны быть отсортированы по убыванию частоты, чтобы получить хорошие результаты. Дополнительные сведения см. в tf.random.log_uniform_candidate_sampler.
Примечание: В случае, когда num_true > 1, мы назначаем каждой целевой категории целевую вероятность 1 / num_true, чтобы суммарные целевые вероятности составляли 1 на пример.
Примечание: Было бы полезно разрешить переменное количество целевых категорий на пример. Мы надеемся предоставить эту функциональность в будущих выпусках. Пока что, если у вас есть переменное количество целевых категорий, вы можете заполнить их до постоянного числа, либо повторяя их, либо заполняя их другой недоступной категорией.
Аргументы
weights A Tensor of shape [num_classes, dim], or a list of Tensor objects whose concatenation along dimension 0 has shape [num_classes, dim]. The (possibly-partitioned) class embeddings.
biases A Tensor of shape [num_classes]. The class biases.
labels A Tensor of type int64 and shape [batch_size, num_true]. The target classes.
inputs A Tensor of shape [batch_size, dim]. The forward activations of the input network.
num_sampled An int. The number of negative classes to randomly sample per batch. This single sample of negative classes is evaluated for each element in the batch.
num_classes An int. The number of possible classes.
num_true An int. The number of target classes per training example.
sampled_values a tuple of (sampled_candidates, true_expected_count, sampled_expected_count) returned by a *_candidate_sampler function. (if None, we default to log_uniform_candidate_sampler)
remove_accidental_hits A bool. Whether to remove "accidental hits" where a sampled class equals one of the target classes. If set to True, this is a "Sampled Logistic" loss instead of NCE, and we are learning to generate log-odds instead of log probabilities. See our Справочник по алгоритмам выборки кандидатов. Default is False.
name A name for the operation (optional).
Возвращает
A batch_size 1-D tensor of per-example NCE losses.

© 2020 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 3.0.
Code samples licensed under the Apache 2.0 License.
https://www.tensorflow.org/versions/r2.3/api_docs/python/tf/nn/nce_loss

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API