15

我目前正在尝试重现以下文章的结果。
http://karpathy.github.io/2015/05/21/rnn-effectiveness/
我正在使用带有 theano 后端的 Keras。在文章中,他谈到了控制最终 softmax 层的温度以提供不同的输出。

温度。我们还可以在采样期间使用 Softmax 的温度。将温度从 1 降低到某个较低的数字(例如 0.5)使 RNN 更加自信,但在其样本中也更加保守。相反,更高的温度会带来更多的多样性,但代价是更多的错误(例如拼写错误等)。特别是,将温度设置得非常接近于零会给出 Paul Graham 最有可能说的话:

我的模型如下。

model = Sequential()
model.add(LSTM(128, batch_input_shape = (batch_size, 1, 256), stateful = True, return_sequences = True))
model.add(LSTM(128, stateful = True))
model.add(Dropout(0.1))
model.add(Dense(256, activation = 'softmax'))

model.compile(optimizer = Adam(),
              loss = 'categorical_crossentropy', 
              metrics = ['accuracy'])

我能想到的调整最终密集层温度的唯一方法是获取权重矩阵并将其乘以温度。有谁知道更好的方法吗?此外,如果有人发现我设置模型的方式有任何问题,请告诉我,因为我是 RNN 的新手。

4

3 回答 3

13

好吧,看起来温度是您对 softmax 层的输出所做的事情。我找到了这个例子。

https://github.com/fchollet/keras/blob/master/examples/lstm_text_generation.py

他应用以下函数对 soft-max 输出进行采样。

def sample(a, temperature=1.0):
    # helper function to sample an index from a probability array
    a = np.log(a) / temperature
    a = np.exp(a) / np.sum(np.exp(a))
    return np.argmax(np.random.multinomial(1, a, 1))
于 2016-05-16T12:37:57.780 回答
6

@chasep255 的答案可以正常工作,但您会因为 log(0) 而收到警告。您可以简化操作 e^log(a)/T = a^(1/T) 并摆脱日志

def sample(a, temperature=1.0):
  a = np.array(a)**(1/temperature)
  p_sum = a.sum()
  sample_temp = a/p_sum 
  return np.argmax(np.random.multinomial(1, sample_temp, 1))

希望能帮助到你!

于 2017-11-03T07:40:32.483 回答
2

您可以在 keras 中构建自定义层来制作 temprature 。

keras 中的代码将是这样的,并将该层用作 keras 中的任何层,例如(密集)

class Temperature(keras.layers.Layer):
  def __init__(self):
    super(Temperature, self).__init__()
    self.temperature = torch.nn.Parameter(torch.ones(1))
    
  def call(self, final_output):
    return final_output/ self.temperature
于 2021-08-29T14:30:21.413 回答