Keras 模型中的采样 Softmax

Sampled Softmax in Keras Model

我考虑过的一些方法:

从模型继承 class Sampled softmax in tensorflow keras

从层继承class How can I use TensorFlow's sampled softmax loss function in a Keras model?

在这两种方法中,模型方法更简洁,因为层方法有点老套——它将目标作为输入的一部分推入,然后再见多输出模型。

我需要一些帮助 class 模型 class - 特别是: 1) 与第一种方法不同——我想像指定标准 keras 模型时那样采用任意数量的层。例如,

class LanguageModel(tf.keras.Model):
    def __init__(self, **kwargs)

2) 我希望在模型 class 中加入以下代码 - 但想让模型 class 认识到

def call(self, y_true, input):
        """ reshaping of y_true and input to make them fit each other """
        input = tf.reshape(input, (-1,self.hidden_size))
        y_true = tf.reshape(y_true, (-1,1))
      weights = tf.Variable(tf.float64))
      biases = tf.Variable(tf.float64)
      loss = tf.nn.sampled_softmax_loss(
      weights=weights,
      biases=biases,
      labels=labels,
      inputs=inputs,
      ...,
      partition_strategy="div")
      logits = tf.matmul(inputs, tf.transpose(weights))
      logits = tf.nn.bias_add(logits, biases)
       y_predis = tf.nn.softmax_cross_entropy_with_logits_v2(
                                labels=inputs[1],
                                logits=logits) 




3 我想我需要一些指向功能 API 中模型 class 的哪些部分的指针,我应该弄乱 - 知道我必须像上面那样编写自定义损失函数。 我想问题是访问 tf.nn.sampledsoftmax 函数

中的权重

我能想到的最简单的方法是定义一个忽略输出层结果的损失。

这里是完整的 Colab: https://colab.research.google.com/drive/1Rp3EUWnBE1eCcaisUju9TwSTswQfZOkS

损失函数。请注意,它假定输出层是 Dense(activation='softmax') 并且忽略了 y_pred。因此,在使用损失的训练/评估期间,密集层的实际输出是 NOP。

做预测时使用输出层。

class SampledSoftmaxLoss(object):
  """ The loss function implements the Dense layer matmul and activation
  when in training mode.
  """
  def __init__(self, model):
    self.model = model
    output_layer = model.layers[-1]
    self.input = output_layer.input
    self.weights = output_layer.weights

  def loss(self, y_true, y_pred, **kwargs):
    labels = tf.argmax(y_true, axis=1)
    labels = tf.expand_dims(labels, -1)
    loss = tf.nn.sampled_softmax_loss(
        weights=self.weights[0],
        biases=self.weights[1],
        labels=labels,
        inputs=self.input,
        num_sampled = 3,
        num_classes = 4,
        partition_strategy = "div",
    )
    return loss

型号:

def make_model():
  inp = Input(shape=(10,))
  h1 = Dense(16, activation='relu')(inp)
  h2 = Dense(4, activation='linear')(h1)
  # output layer and last hidden layer must have the same dims
  out = Dense(4, activation='softmax')(h2)
  model = Model(inp, out)
  loss_calculator = SampledSoftmaxLoss(model)
  model.compile('adam', loss_calculator.loss)
  return model

tf.set_random_seed(42)
model = make_model()
model.summary()

请注意,SampledSoftmaxLoss 强制最后一个模型层的输入必须与 类 的数量相同。