如何使用在keras培训期间发生变化的函数

2024-06-16 10:02:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的自动编码器中自定义我的损失函数,损失函数必须考虑到另一个维度缩减(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())

Tags: ofthe函数imginputmodelisthis