我在张量流中创建一个神经网络,需要最小化以下损失函数: 其中表示真实值,表示预测值。由于损失函数不可微,因此在使用梯度下降时会成为一个问题。
更新,现在我正在尝试实现:
这是我的代码:
def custom_loss(y_true, pred):
if pred > y_true:
custom_loss = K.log(pred) - K.log(y_true)
elif pred < y_true:
custom_loss = K.log(y_true) - K.log(pred)
else:
custom_loss = K.log(pred)-K.log(pred)
return custom_loss
if __name__ == '__main__':
run = 1
X = np.load("vectors_normal_2way.npy")
with open("target2.pickle", "rb") as file:
target_dict = pickle.load(file)
target_strings = [*target_dict]
Y = np.array([])
for target_value in target_strings:
Y = np.append(Y, target_dict.get(target_value))
for i in range(run):
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2)
model = get_model()
start = time.time()
model.fit(X_train, Y_train, verbose = 1, epochs = 1, batch_size = 32)
end_time = time.time()-start
pred = model.predict(X_test)[:, 0]
但我收到以下错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: The second input must be a scalar, but it has shape [32]
[[{{node gradient_tape/custom_loss/cond/StatelessIf/gradient_tape/custom_loss/weighted_loss/Mul/_17}}]] [Op:__inference_train_function_1040]
当我有 batch_size = 1 时代码可以运行