python - 张量流在损失函数中使用输入
问题描述
我正在使用 tensorflow/keras,我想在损失函数中使用输入
根据这里的答案
我因此创建了我的损失函数
def custom_Loss_with_input(inp_1):
def loss(y_true, y_pred):
b = K.mean(inp_1)
return y_true - b
return loss
并使用图层设置模型,并以这样的方式结束
model = Model(inp_1, x)
model.compile(loss=custom_Loss_with_input(inp_1), optimizer= Ada)
return model
不过,我收到以下错误:
TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.
有关如何消除此错误的任何建议?提前致谢
解决方案
您可以使用add_loss
将外部层传递给您的损失,在您的情况下是输入张量。
这里有一个例子:
def CustomLoss(y_true, y_pred, input_tensor):
b = K.mean(input_tensor)
return K.mean(K.square(y_true - y_pred)) + b
X = np.random.uniform(0,1, (1000,10))
y = np.random.uniform(0,1, (1000,1))
inp = Input(shape=(10,))
hidden = Dense(32, activation='relu')(inp)
out = Dense(1)(hidden)
target = Input((1,))
model = Model([inp,target], out)
model.add_loss( CustomLoss( target, out, inp ) )
model.compile(loss=None, optimizer='adam')
model.fit(x=[X,y], y=None, epochs=3)
如果您的损失由不同的部分组成并且您想跟踪它们,您可以添加与损失部分相对应的不同损失。通过这种方式,损失会在每个 epoch 结束时打印出来并存储在model.history.history
. 请记住,训练期间最小化的最终损失是各个损失部分的总和。
def ALoss(y_true, y_pred):
return K.mean(K.square(y_true - y_pred))
def BLoss(input_tensor):
b = K.mean(input_tensor)
return b
X = np.random.uniform(0,1, (1000,10))
y = np.random.uniform(0,1, (1000,1))
inp = Input(shape=(10,))
hidden = Dense(32, activation='relu')(inp)
out = Dense(1)(hidden)
target = Input((1,))
model = Model([inp,target], out)
model.add_loss(ALoss( target, out ))
model.add_metric(ALoss( target, out ), name='a_loss')
model.add_loss(BLoss( inp ))
model.add_metric(BLoss( inp ), name='b_loss')
model.compile(loss=None, optimizer='adam')
model.fit(x=[X,y], y=None, epochs=3)
要在推理模式下使用模型(从输入中删除目标):
final_model = Model(model.input[0], model.output)
final_model.predict(X)
推荐阅读
- amazon-web-services - 如何向 AWS CloudFormation 提供非字母数字参数类型
- python - 使用线性回归对年度分布的时间序列数据进行 -N 年之后的预测
- events - GTM dataLayer 推送链接点击 - 竞争条件?
- typescript - 如何在switchOperator中调用forkJoin?
- javascript - Vue中的数据翻译
- solr - 在向 Apache Solr 索引更新发出超过 500 个并发请求时遇到套接字饱和/IO 异常
- html - bootstrap 4 show tabs 在第一次点击后不起作用
- java - 是否可以启用本机代码的缓存?
- python - 如何从 Python 中的 DataFrame 列中删除特定的更改文本?
- javascript - 如何解决调用函数中无法提示.click()的问题?