深度学习损失函数(含公式和代码)

基础知识包含公式和代码

  1. 均方误差损失函数(Mean Squared Error,MSE):适用于回归问题,计算预测值与真实值之间的平均平方误差。MSE = \frac{1}{n}\sum_{i=1}n}(y_i - \hat{y_i})^2

    import tensorflow as tf
    # 构建神经网络模型
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(64, activation='relu'),
        tf.keras.layers.Dense(10)
    ])
    # 编译模型,指定优化器、损失函数和评估指标
    model.compile(optimizer=tf.keras.optimizers.Adam(),
                  loss=tf.keras.losses.MeanSquaredError(),
                  metrics=['mse'])
    # 加载数据集
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.boston_housing.load_data()
    # 训练模型
    model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))

  2. 平均绝对误差损失函数(Mean Absolute Error,MAE):适用于回归问题,计算预测值与真实值之间的平均绝对误差。MAE=\frac{1}{n}\sum_{i=1}^{n}|y_i-\hat{y_i}|

    
    from sklearn.metrics import mean_absolute_error
    
    y_true = [3, -0.5, 2, 7]
    y_pred = [2.5, 0.0, 2, 8]
    
    mae = mean_absolute_error(y_true, y_pred)
    print("MAE:", mae)

  3. 交叉熵损失函数(Cross Entropy Loss):适用于分类问题,计算预测值与真实值之间的交叉熵。H(p,q)=-\sum_{x}p(x)\log q(x)

    import numpy as np
    
    def cross_entropy_loss(y_true, y_pred):
        """
        计算交叉熵损失函数
        :param y_true: 真实标签,one-hot编码
        :param y_pred: 模型输出的概率分布
        :return: 交叉熵损失函数的值
        """
        epsilon = 1e-10
        y_pred = np.clip(y_pred, epsilon, 1. - epsilon)
        ce_loss = -np.sum(y_true * np.log(y_pred))
        return ce_loss

  4. 对数损失函数(Logarithmic Loss):适用于二分类问题,计算预测值与真实值之间的对数损失。LogLoss = -\frac{1}{N}\sum_{i=1}^{N}[y_i\log(\hat{y_i})+(1-y_i)\log(1-\hat{y_i})]

    import torch
    import torch.nn.functional as F
    
    # 定义真实标签和预测标签
    y_true = torch.tensor([1, 0, 1, 0])
    y_pred = torch.tensor([0.9, 0.1, 0.8, 0.2])
    
    # 使用对数损失函数计算损失值
    loss = F.binary_cross_entropy(y_pred, y_true)
    
    print(loss.item()) # 输出:0.17380797863006592

  5. 感知机损失函数(Perceptron Loss):适用于二分类问题,计算预测值与真实值之间的误差。L(w,b)=-\sum_{x_i\in M}y_i(w\cdot x_i+b)

    import numpy as np
    
    class Perceptron:
        def __init__(self, lr=0.1, max_iter=1000):
            self.lr = lr
            self.max_iter = max_iter
    
        def fit(self, X, y):
            self.w = np.zeros(X.shape[1])
            self.b = 0
            for _ in range(self.max_iter):
                for i in range(X.shape[0]):
                    if y[i] * (np.dot(self.w, X[i]) + self.b) <= 0:
                        self.w += self.lr * y[i] * X[i]
                        self.b += self.lr * y[i]
    
        def predict(self, X):
            return np.sign(np.dot(X, self.w) + self.b)

  6. Hinge损失函数:适用于支持向量机(SVM)分类问题,计算预测值与真实值之间的误差。L(y, f(x)) = \max(0, 1 - yf(x))

    import torch
    from torch.autograd import Variable
    
    # 定义数据
    x = Variable(torch.Tensor([[1, 2], [2, 3], [3, 4], [4, 5]]))
    y = Variable(torch.Tensor([-1, -1, 1, 1]))
    
    # 定义模型
    class SVM(torch.nn.Module):
        def __init__(self):
            super(SVM, self).__init__()
            self.linear = torch.nn.Linear(2, 1)
            
        def forward(self, x):
            return self.linear(x)
    
    model = SVM()
    
    # 定义损失函数
    criterion = torch.nn.HingeEmbeddingLoss()
    
    # 定义优化器
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
    
    # 训练模型
    for epoch in range(100):
        optimizer.zero_grad()
        output = model(x)
        loss = criterion(output.view(-1), y)
        loss.backward()
        optimizer.step()
    
    # 测试模型
    test_x = Variable(torch.Tensor([[1, 1], [2, 2], [3, 3], [4, 4]]))
    test_y = model(test_x)
    print(test_y)

  7. KL散度损失函数(Kullback-Leibler Divergence Loss):适用于度量两个概率分布之间的差异。D_{KL}(P||Q)=\sum_{i}P(i)\log\frac{P(i)}{Q(i)}

    import tensorflow as tf
    
    # 定义真实分布和模型输出分布
    y_true = tf.constant([0.2, 0.3, 0.5])
    y_pred = tf.constant([0.1, 0.4, 0.5])
    
    # 计算KL散度
    kl_loss = tf.keras.losses.KLDivergence()(y_true, y_pred)
    
    # 输出KL散度的值
    print(kl_loss.numpy()) # 输出:0.020286322

  • 34
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

New___dream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值