python - Problems with a custom loss function in Keras
问题描述
I need to have a custom Keras loss function. The following code works with loss function loss2 but not using loss function loss1. I am getting errors as
OperatorNotAllowedInGraphError: using a tf.Tensor
as a Python bool
is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
I have decorated the function with @tf.function but it does not work.
import numpy as np
from keras import backend as K
from keras.models import Sequential
from keras.layers import Dense, LeakyReLU
def individual_model(keys, labels):
model = Sequential()
size = 32
model.add(Dense(32, input_dim=1))
model.add(LeakyReLU())
for i in range(2):
model.add(Dense(size))
model.add(LeakyReLU())
model.add(Dense(1))
model.compile(optimizer='adam', loss=my_loss, metrics=[
my_loss])
model.fit(keys, labels, epochs=256, batch_size=32, verbose=1)
return model
def loss1(v):
if v<0:
return -100 * v
else:
return v
def loss2(v):
return v*v
def my_loss(y_true, y_pred):
return K.map_fn(loss1,y_true-y_pred) #with loss2 this works
x=np.random.exponential(100,1000)
x.sort()
labels=np.arange(0,1000)
m=individual_model(x,labels)
解决方案
tf.where could be used in loss v1 definition something like this link:
import tensorflow as tf
import numpy as np
arr = np.array([1., -1])
sess = tf.Session()
print(sess.run(tf.where(arr<0., arr*100., arr*10.))
Output:
array([ 10., -100.])
推荐阅读
- gulp - 如何摆脱 Gulp 的“从未定义的任务:默认”?
- r - 使用 R 中的蒙特卡洛模拟股票价格
- swift - iOS 13 Xcode 11:PKPushKit 和 APNS 在一个应用程序中
- python-3.x - python2和python3中用gmpy2计算q,但结果不一样
- android - 用于 RESTFul JSON API 交互的推荐 Android HTTP 库是什么?
- java - RecyclerView 更新而不刷新适配器列表
- java - Firebase RecycleView 与 Edittext 同时进行多项更改
- ios - Firestore 访问规则在拒绝访问时不会报告任何错误
- chart.js - Chart.js 不显示带有线性轴和固定步长的堆叠数据
- ios - 在 UITableViewCell 中创建“标签云”