【发布时间】:2018-11-28 16:41:12
【问题描述】:
我对 keras 有一个“我该怎么做”的问题:
假设我有第一个神经网络,比如 NNa,它有 4 个输入 (x,y,z,t),已经训练过。 如果我有第二个神经网络,比如 NNb,它的损失函数取决于第一个神经网络。
NNb的自定义损失函数customLossNNb调用NNa的预测有一个固定的网格(x,y,z),只修改最后一个变量t。
在伪python代码中我想训练第二个NN:NNb:
grid=np.mgrid[0:10:1,0:10:1,0:10:1].reshape(3,-1).T
Y[:,0]=time
Y[:,1]=something
def customLossNNb(NNa,grid):
def diff(y_true,y_pred):
for ii in range(y_true.shape[0]):
currentInput=concatenation of grid and y_true[ii,0]
toto[ii,:]=NNa.predict(currentInput)
#some stuff with toto
return #...
return diff
然后
NNb.compile(loss=customLossNNb(NNa,K.variable(grid)),optimizer='Adam')
NNb.fit(input,Y)
实际上给我带来麻烦的线路是currentInput=concatenation of grid and y_true[ii,0]
我尝试使用K.variable(grid) 将网格作为张量发送到 customLossNNb。但是我不能在损失函数中定义一个新的张量,比如CurrentY,它的形状为(grid.shape[0],1),填充y[ii,0](即当前t),然后连接grid和currentY 构建currentInput
有什么想法吗?
谢谢
【问题讨论】:
-
正如我在回答中指出的那样,您不能在损失函数中使用 model.predict(x),因为它不能成为图表的一部分。改用model(x),但是你需要正确地冻结权重。 tensor.shape 属性也不是图表的一部分。要成为图表的一部分,这需要返回张量对象。您可以使用 keras.backend.shape(tensor)。 For 循环也不会成为图表的一部分。一般来说,我认为你需要自己澄清一下图形对象的概念。