R 当我没有真实值时,如何编写自己的自定义损失函数?
我想找出一种方法来创建我自己的损失函数。我在R上使用了keras\u模型\u序列模型R 当我没有真实值时,如何编写自己的自定义损失函数?,r,tensorflow,keras,R,Tensorflow,Keras,我想找出一种方法来创建我自己的损失函数。我在R上使用了keras\u模型\u序列模型 custom_loss <- function(x){ post <- second_model(x) #the current model pri <- first_model() #another already defined model LOSS <- sum((pri-post)^2) return(LOSS) } 好的,现在我明
custom_loss <- function(x){
post <- second_model(x) #the current model
pri <- first_model() #another already defined model
LOSS <- sum((pri-post)^2)
return(LOSS)
}
好的,现在我明白了。由于使用tensorflow后端,因此必须在损失函数中传递tensor对象,并导入tensorflow后端进行计算 所以 导入tensorflow后端 直接使用tensorflow操作在损失函数中进行这些计算 对于第一个模型的结果,可以使用keras输入层: 图层输入%>% 这里有一个例子
x_train <- model1 %>% predict(input_vector)
--code defining the model2 --
y_true <- matrix(c(1),100,16) #dummy, because no target values
delta <- model2 %>% predict(x_train)
adjusted_input <- input_vector + delta
adjusted_y <- model1 %>% predict(adjusted_input)
y_pred <- adjusted_y #(just to have the same variable names as argument)
custom_loss <- function(y_pred, y_true){
LOSS <- sum((10-y_pred)^2)
return(LOSS)
}
model2 %>% compile(
loss = custom_loss(y_pred, y_true),
optimizer = optimizer_nadam(),
metrics = c("mae")
)
delta <- model2 %>% predict(x_train)
adjusted_input <- input_vector + delta
adjusted_y <- model1 %>% predict(adjusted_input)
y_pred <- adjusted_