我想在tf keras中采样softmax损失。我通过子类化keras Model定义了自己的模型。在初始化中,我指定需要的层,包括最后一个Dense投影层。但是,在训练中不应调用此Dense层,因为我想对softmax进行采样,而仅使用其权重和偏差。然后,我定义损耗函数:
class SampledSoftmax:
def init( self,
num_sampled,
num_classes,
projection,
bias,
hidden_size):
self.weights = tf.transpose(projection)
self.bias = bias
self.num_classes = num_classes
self.num_sampled = num_sampled
self.hidden_size = hidden_size
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))
return tf.nn.sampled_softmax_loss(
weights=self.weights,
biases=self.bias,
labels=y_true,
inputs=input,
num_sampled=self.num_sampled,
num_classes=self.num_classes,
partition_strategy='div')
它需要初始化所需的参数,而类调用将是所需的采样softmax损失函数。要注意的是,要增加模型编译的损失,我需要最后一次密集的权重等。但是1)在训练中,模型中不包含Dense,2)即使包含,Dense层也只会与输入连接,因此在我的自定义模型调用中会得到其输入尺寸等。简而言之,权重等在编译模型之前将不可用。谁能提供一些帮助以指出正确的方向?
现在,使它失败的代码。我首先将模型分类如下:
class LanguageModel(tf.keras.Model):
def __init__(self,
vocal_size=15003,
embedding_size=512
input_len=64)
self.embedding = Embedding(vocal_size, embedding_size,
input_length=input_len)
self.lstm = LSTM(hidden_size, return_sequences=True)
self.dense = Dense(vocal_size, activation='softmax')
def call(self, inputs, training=False):
emb_out = self.embedding(inputs)
lstm_out = self.lstm(embrace_out)
res = self.dense(lstm_out)
if (training)
''' shouldn't use the last dense as we want to do sampling'''
return lstm_out
return res
然后按照以下步骤训练模型
sampled_loss = SampledSoftmax(num_sampled, vocal_size,
model.dense.kernel, model.dense.bias,
hidden_size)
model.compile(optimizer=tf.train.RMSPropOptimizer(lr),
loss=sampled_loss)
但是它将失败,因为我无法解决它,因为由于在编译模型时无法访问model.dense.kernel,因此尚未在调用方法中初始化密集层。错误消息如下:
Traceback (most recent call last):
File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/wuxinyu/workspace/nlu/lm/main.py", line 72, in <module>
train_main()
File "/home/wuxinyu/workspace/nlu/lm/main.py", line 64, in train_main
train_model.build_lm_model()
File "/home/wuxinyu/workspace/nlu/lm/main.py", line 26, in build_lm_model
self.model.dense.kernel,
AttributeError: 'Dense' object has no attribute 'kernel'
顺便说一句,上面定义的损失将在如下所示的小型测试案例中起作用。
x = Input(shape=(10,), name='input_x')
emb_out = Embedding(10000,200,input_length=10)(x)
lstm_out = LSTM(200, return_sequences=True)(emb_out)
dense = Dense(10000, activation='sigmoid')
output = dense(lstm_out)
sl = SampledSoftmax(10, 10000, dense.kernel, dense.bias)
model = Model(inputs=x, outputs=lstm_out)
model.compile(optimizer='adam', loss=sl)
model.summary()
model.fit(dataset, epochs=20, steps_per_epoch=5)