KERAS: objective or loss functions

在Keras中,损失函数是模型编译时的关键参数之一,例如使用`model.compile(loss='mean_squared_error', optimizer='sgd')`。该函数从源代码`objectives.py`中提供了多种选择。" 133241113,19673579,使用jQuery轻松调整滚动条位置,"['jQuery', '前端开发', 'JavaScript']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



An objective function (or loss function, or optimization score function) is one of the two parameters required to compile a model:

model.compile(loss='mean_squared_error', optimizer='sgd')

There are quite a few choices of such functions that can be found from the source code objectives.py as follows:

import numpy as np

from . import backend as K

 
 

def mean_squared_error(y_true, y_pred):

return K.mean(K.square(y_pred  - y_true), axis=-1)

 
 

def mean_absolute_error(y_true, y_pred):

return K.mean(K.abs(y_pred  - y_true), axis=-1)

 
 

def mean_absolute_percentage_error(y_true, y_pred):

diff = K.abs((y_true  - y_pred) / K.clip(K.abs(y_true), K.epsilon(), np.inf))

return 100. * K.mean(diff,  axis=-1)

 
 

def mean_squared_logarithmic_error(y_true, y_pred):

first_log = K.log(K.clip(y_pred,  K.epsilon(), np.inf) + 1.)

second_log = K.log(K.clip(y_true,  K.epsilon(), np.inf) + 1.)

return K.mean(K.square(first_log  - second_log), axis=-1)

 
 

def squared_hinge(y_true,  y_pred):

return K.mean(K.square(K.maximum(1.  - y_true * y_pred, 0.)), axis=-1)

 
 

def hinge(y_true, y_pred):

return K.mean(K.maximum(1.  - y_true * y_pred, 0.), axis=-1)

 
 

def categorical_crossentropy(y_true, y_pred):

'''Expects a binary  class matrix instead of a vector of scalar classes.

'''

return K.categorical_crossentropy(y_pred,  y_true)

 
 

def sparse_categorical_crossentropy(y_true, y_pred):

'''expects an array  of integer classes.

Note: labels shape  must have the same number of dimensions as output shape.

If you get a shape  error, add a length-1 dimension to labels.

'''

return K.sparse_categorical_crossentropy(y_pred,  y_true)

 
 

def binary_crossentropy(y_true, y_pred):

return K.mean(K.binary_crossentropy(y_pred,  y_true), axis=-1)

 
 

def kullback_leibler_divergence(y_true, y_pred):

y_true = K.clip(y_true,  K.epsilon(), 1)

y_pred = K.clip(y_pred,  K.epsilon(), 1)

return K.sum(y_true *  K.log(y_true / y_pred), axis=-1)

 
 

def poisson(y_true, y_pred):

return K.mean(y_pred  - y_true * K.log(y_pred + K.epsilon()), axis=-1)

 
 

def cosine_proximity(y_true, y_pred):

y_true =K.l2_normalize(y_true, axis=-1)

y_pred =K.l2_normalize(y_pred, axis=-1)

return-K.mean(y_true * y_pred, axis=-1)

 
 

# aliases

mse =MSE= mean_squared_error

mae =MAE= mean_absolute_error

mape =MAPE=  mean_absolute_percentage_error

msle =MSLE=  mean_squared_logarithmic_error

kld =KLD=  kullback_leibler_divergence

cosine = cosine_proximity

 

from .utils.generic_utils import get_from_module

def get(identifier):

return get_from_module(identifier, globals(), 'objective')

 

tensorflow. python. keras. engine. training. Model def compile(self, optimizer: str = 'rmsprop', loss: Any = None, metrics: Any = None, loss_weights: Any = None, weighted_metrics: Any = None, run_eagerly: Any = None, steps_per_execution: Any = None, **kwargs: Any) -> None Configures the model for training. 形参: optimizer – String (name of optimizer) or optimizer instance. See tf. keras. optimizers. loss – String (name of objective function), objective function or tf. keras. losses. Loss instance. See tf. keras. losses. An objective function is any callable with the signature loss = fn(y_true, y_pred), where y_true = ground truth values with shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]. y_pred = predicted values with shape = [batch_size, d0, .. dN]. It returns a weighted loss float tensor. If a custom Loss instance is used and reduction is set to None, return value has the shape [batch_size, d0, .. dN-1] i. e. per-sample or per-timestep loss values; otherwise, it is a scalar. If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses, unless loss_weights is specified. metrics – List of metrics to be evaluated by the model during training and testing. Each of this can be a string (name of a built-in function), function or a tf. keras. metrics. Metric instance. See tf. keras. metrics. Typically you will use metrics=['accuracy']. A function is any callable with the signature result = fn(y_true, y_pred). To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}. You can also pass a list 翻译
最新发布
03-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值