【随感】在Keras中如何按最大似然(Max Likewood)训练模型

在Keras中如何按最大似然(Max Likewood)训练模型


按照生成模型的思路,模型的参数是和数据分布无关的,利用极大似然准则就可以训练模型。但是在类似Keras这种神经网络库中,如何训练类似如下的目标函数:

E o [ t ] , l [ log π θ ( a [ t ] o [ t ] , h [ t 1 ] , l ) ) + η v θ ( o [ t ] , h [ t 1 ] , l ) ] -\mathbb{E}_{{o}^{[t]},{l}} [ { \log\pi_{\theta}(a^{[t]}|{o}^{[t]},{h}^{[t-1]},{l})) } + { \eta v_{\theta}({o}^{[t]},{h}^{[t-1]},{l})} ]

其中类似 π θ ( a [ t ] o [ t ] , h [ t 1 ] , l ) ) \pi_{\theta}(a^{[t]}|{o}^{[t]},{h}^{[t-1]},{l})) 这样的映射的采样是困难的(你不能将一次/多次前向传播的结果就当做是采样的结果),必须以极大量的前向传播结果才能逼近这个分布(大数定律)。下面将介绍一种替代方案,也就是将证明可以用KL散度 (Kullback–Leibler divergence)代替最大似然模型。

最大似然的损失函数:
L ( θ , x ) = l o g ( P θ ( x ) ) \mathcal{L}(\theta,x) = -log(\mathcal{P}_{\theta}(x))

优化目标即为 θ = min θ l o g ( P θ ( x ) ) \theta=\min_{\theta} -log(\mathcal{P}_{\theta}(x)) ,假设真实数据分布服从 x Q ( x ) x \sim \mathcal{Q}(x) ,那么参数 θ \theta 的风险期望为:

E x [ L ( θ , x ) ] = x Q ( x ) l o g ( P θ ( x ) ) = x Q ( x ) l o g ( Q ( x ) / P θ ( x ) ) D K L ( Q P ) + x Q ( x ) l o g ( 1 / Q ( x ) H ( Q ) ) \mathbb{E}_{x}[\mathcal{L}(\theta,x)]=-\sum_{x}\mathcal{Q}(x) log(\mathcal{P}_{\theta}(x)) \\ = \underbrace{\sum_{x}\mathcal{Q}(x) log( { \mathcal{Q}(x) }/{ \mathcal{P}_{\theta}(x) })}_{D_{KL}(\mathcal{Q}||\mathcal{P}) } + \underbrace{\sum_{x}\mathcal{Q}(x) log( {1}/{ \mathcal{Q}(x) }}_{H(\mathcal{Q})} )

由于真实数据分布是 Q ( x ) \mathcal{Q}(x) ,那么 H ( Q ) H(\mathcal{Q}) 是给定的,那么 E x [ L ( θ , x ) ] \mathbb{E}_{x}[\mathcal{L}(\theta,x)] Q = P θ \mathcal{Q}=\mathcal{P_{\theta}} 时是最小的且为 0 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])
发布了142 篇原创文章 · 获赞 71 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/hanss2/article/details/83343168