在Keras中如何按最大似然(Max Likewood)训练模型
按照生成模型的思路,模型的参数是和数据分布无关的,利用极大似然准则就可以训练模型。但是在类似Keras这种神经网络库中,如何训练类似如下的目标函数:
−Eo[t],l[logπθ(a[t]∣o[t],h[t−1],l))+ηvθ(o[t],h[t−1],l)]
其中类似
πθ(a[t]∣o[t],h[t−1],l))这样的映射的采样是困难的(你不能将一次/多次前向传播的结果就当做是采样的结果),必须以极大量的前向传播结果才能逼近这个分布(大数定律)。下面将介绍一种替代方案,也就是将证明可以用KL散度 (Kullback–Leibler divergence)代替最大似然模型。
最大似然的损失函数:
L(θ,x)=−log(Pθ(x))
优化目标即为
θ=minθ−log(Pθ(x)),假设真实数据分布服从
x∼Q(x),那么参数
θ的风险期望为:
Ex[L(θ,x)]=−x∑Q(x)log(Pθ(x))=DKL(Q∣∣P)
x∑Q(x)log(Q(x)/Pθ(x))+H(Q)
x∑Q(x)log(1/Q(x))
由于真实数据分布是
Q(x),那么
H(Q)是给定的,那么
Ex[L(θ,x)]在
Q=Pθ时是最小的且为
0.
因此我们在训练时采用Keras自带的crossentropy即可:
from keras.layers import Input,Embedding,LSTM,Dense
from keras.models import Model
from keras import backend as K
word_size = 128
dim_hidden = 100
dim_action = 10
dim_value = 10
encode_size = 64
input = Input(shape=(None,))
embedded = Embedding(dim_hidden,word_size)(input)
encoder = LSTM(encode_size)(embedded)
predict_action = Dense(dim_action)(encoder)
predict_value = Dense(dim_value)(encoder)
def object1(y_true, y_pred, eta=0.2):
loss1 = K.categorical_crossentropy(y_true, y_pred)
return K.log(loss1)
def object2(y_true, y_pred, eta=0.2):
loss2 = K.categorical_crossentropy(y_true, y_pred)
return eta*loss2
model = Model(inputs=input, outputs=[predict_action,predict_value])
model.compile(optimizer='adam', loss=[object1,object2])