pyt*_*ist 2 python keras tensorflow sampled-softmax
我考虑过的一些方法:
从模型类继承 tensorflow keras 中的采样 softmax
从层类继承 如何在 Keras 模型中使用 TensorFlow 的采样 softmax 损失函数?
在这两种方法中,模型方法更简洁,因为层方法有点笨拙——它将目标作为输入的一部分推入,然后再见多输出模型。
我想在对 Model 类进行子类化方面得到一些帮助 - 具体来说:1) 与第一种方法不同 - 我想在指定标准 keras 模型时采用任意数量的层。例如,
class LanguageModel(tf.keras.Model):
def __init__(self, **kwargs)
Run Code Online (Sandbox Code Playgroud)
2)我希望在模型类中合并以下代码 - 但想让模型类认识到
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)
Run Code Online (Sandbox Code Playgroud)
3 我想我需要一些指针,指向函数 API 中模型类的哪些部分我应该弄乱 - 知道我必须像上面那样编写自定义损失函数。我想问题是访问 tf.nn.sampledsoftmax 函数中的权重
小智 6
我能想到的最简单的方法是定义一个忽略输出层结果的损失。
完整的 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
Run Code Online (Sandbox Code Playgroud)
模型:
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()
Run Code Online (Sandbox Code Playgroud)
请注意,SampledSoftmaxLoss 要求最后一个模型层的输入必须具有与类数量相同的维度。
| 归档时间: |
|
| 查看次数: |
1216 次 |
| 最近记录: |