Python 张量项水平的Keras/Tf自定义损失函数
我想在Keras中编写一个自定义损失函数,它接受预测值的张量,然后对于每个过程,在增加损失之前通过另一个函数。这是它的样子。这是一个完整的代码示例,请查看函数示例Python 张量项水平的Keras/Tf自定义损失函数,python,tensorflow,keras,Python,Tensorflow,Keras,我想在Keras中编写一个自定义损失函数,它接受预测值的张量,然后对于每个过程,在增加损失之前通过另一个函数。这是它的样子。这是一个完整的代码示例,请查看函数示例 class AE(): def __init__(self,inputSize=78,numNeurons = 50, latentSize=5,expSize = 10,batchSize = 1, activation="relu"): K.clear_session() self.inp
class AE():
def __init__(self,inputSize=78,numNeurons = 50, latentSize=5,expSize = 10,batchSize = 1, activation="relu"):
K.clear_session()
self.inputSize = inputSize
self.latentSize = latentSize
self.activation = activation
self.numNeurons = numNeurons
self.expSize = expSize
self.batchSize = batchSize
self.encoder = self.createEncoder()
self.decoder = self.createDecoder()
self.filterModel = self.createFilterModel()
self.AE = self.createAE()
def sample_loss(self,y_pred ):
loss = 0.0
for j in tf.range(0,self.inputSize ,2):
pt = y_pred[j:j+2]
loss += K.sum(self.filterModel.predict(pt))
return loss
def createEncoder(self):
# create the encoder
xIn = Input(shape=(self.inputSize,), name="data_in")
y_train = Input(shape=(self.latentSize,), name='y_train')
x = Dense(self.numNeurons,activation=self.activation)(xIn)
xlatent = Dense(self.latentSize,activation=self.activation)(x)
# create the encoder
encoder = Model(xIn,xlatent)
return encoder
def createDecoder(self):
# create the decoder
latentIn = Input(shape=(self.latentSize,))
x = Dense(self.numNeurons,activation=self.activation)(latentIn)
out = Dense(self.inputSize,activation="linear")(x)
# create a decoder
decoder = Model(latentIn,out)
return decoder
def createAE(self):
xIn = Input(shape=(self.inputSize,), name="ae_data_in")
# create the total model
latentOutput = self.encoder(xIn)
dataOutput = self.decoder(latentOutput)
model = Model(inputs=xIn,outputs=dataOutput)
model.add_loss( self.sample_loss( dataOutput) )
model.summary()
return model
def createFilterModel(self):
xIn = Input(shape=(2,), name="filter_data_in")
x = Dense(4, activation='sigmoid')(xIn)
x = Dense(1, activation='sigmoid')(x)
model = Model(xIn,x)
model.compile(optimizer='adam', loss='binary_crossentropy')
return model
modelAE = AE()
modelAE.AE.compile(optimizer='adam',loss="mse", metrics=['accuracy'])
所以我有一本模型词典,filterModels。这些实际上是Keras中的预测模型。对于本词典中的每个模型,我希望将其传递给y_pred的相应部分,然后将其输出添加到损失中
我该怎么做
以下是当前代码给我的错误:
'''
ValueError:向模型提供符号张量时,我们希望张量具有静态批量大小。有形状的张量:(无,78)
“”“是不是
tf2
?什么是expSize
?什么是inputSize
?当你似乎将张量大小与模型数量混为一谈时,i
与j
的关系如何?请详细描述你想做什么。把它想象成一个矩阵,expSize是行,inputSize是列。对于每一行,取两个连续点并将其输入过滤函数。把这个输出加到你的损失中。你试过你的功能了吗,它起作用了吗?出了什么问题?只要将.predict(pt)
替换为(pt,training=False)
,就可以了。您根本不需要i
循环。当我添加training=False时,我得到:tf\uu predict()得到了一个意外的关键字参数“training”