由于预测结果和标签必须具有相同的形状,我们应该创建一个完整的模型,其中包含您想要的函数(而不是将函数留给损失函数)。
稍后我们可以获取前一层的输出,这将是所需的参数。
因此,假设您已将模型准备到输出参数的层(Dense(4)
很可能是 A,它将为每个输入样本输出 4 个参数)。
让我们在它之后添加两个 lambda 层。
- 一个输出 4 个唯一参数,独立于样本,因为您稍后会想要检索它们
- 一是实际功能
a*sin(bx + c) + d
所以:
#add them to your model the usual way you do
model.add(Lambda(getParameters,output_shape=(4,),name='paramLayer'))
model.add(Lambda(yourFunction,output_shape=(1,),name='valueLayer'))
在哪里:
import keras.backend as K
def getParameters(x):
#since x comes in as a batch with shape (20,4) -- (or any other batch size different from 20)
#let's condense X in one sample only, because we want only 4 elements, not 20*4 elements
xCondensed = K.mean(x,axis=0,keepdims=True)
#I'm using keepdims because we will need that x end up with the same number of samples for compatibility purposes (keras rules)
#let's expand x again (for compatibility purposes), now repeating the 4 values 20 (or more) times
return K.ones_like(x) * xCondensed
def yourFunction(x):
#now x has 4 parameters (assuming you had a Dense(4) before these lambda layers)
a = x[:,0]
b = x[:,1]
c = x[:,2]
d = x[:,3]
#creating the 20 (or more) iterations
ones = K.ones_like(x[:,0])
iterationsStartingAt1= K.cumsum(ones)
iterationsStartingAt0= iterationsStartingAt1 - 1
iterations = #choose one of the above
return (a * K.sin((b*iterations) + c)) + d
现在您可以通过标签来训练这个模型。
当您想要检索四个参数时,您需要另一个模型,该模型更早结束:
from keras.models import Model
paramModel = Model(model.inputs,model.get_layer('paramLayer').output)
params = paramModel.predict(testOrTrainData)
结果的形状类似于 (20,4),但所有 20 行都将重复。