如何使用在使用Keras进行训练时会改变的功能

时间:2019-03-09 21:29:26

标签: python keras deep-learning autoencoder dimension-reduction

我尝试在自动编码器中自定义损失函数,损失函数必须考虑另一个降维(LLE)的结果,传递给函数的数据必须更新为每次计算损失函数,必须更改的变量不会更改。那是我的代码,我在等待您的答案,谢谢。

损失函数:

def increment():
  global i
  i = i+1
  return i
def call_loss_lle():
  global i  #i does not increment
  def loss_lle(y_true,y_pred):
    global i
    global increment
    i  = increment()
    X = x_train[i-1:i,]
    lamda = 0.3
    z = encoder.predict(X)
    encoded = encoder.predict(X)
    z = z.reshape((28,3))
    y,W = LLE_(encoded.reshape((28,3)),10)
    produit = np.dot(W,z)  
    diff =  z - produit
    loss_lle = lamda * np.linalg.norm(diff)  
    cross = K.binary_crossentropy(y_true,y_pred)
    return cross + loss_lle
  return loss_lle

自动编码器:

from keras.layers import Input, Dense
from keras.models import Model

# this is the size of our encoded representations
encoding_dim = 84  

# this is our input placeholder
input_img = Input(shape=(784,))
# "encoded" is the encoded representation of the input
encoded = Dense(encoding_dim, activation='relu')(input_img)
# "decoded" is the lossy reconstruction of the input
decoded = Dense(784, activation='sigmoid')(encoded)
# this model maps an input to its reconstruction
autoencoder = Model(input_img, decoded)
# this model maps an input to its encoded representation
encoder = Model(input_img, encoded)
# create a placeholder for an encoded (32-dimensional) input
encoded_input = Input(shape=(encoding_dim,))
# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# create the decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))
autoencoder.updates()
autoencoder.compile(optimizer='adadelta', loss=call_loss_lle())

0 个答案:

没有答案