基础知识包含公式和代码
-
均方误差损失函数(Mean Squared Error,MSE):适用于回归问题,计算预测值与真实值之间的平均平方误差。
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))
-
平均绝对误差损失函数(Mean Absolute Error,MAE):适用于回归问题,计算预测值与真实值之间的平均绝对误差。
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)
-
交叉熵损失函数(Cross Entropy Loss):适用于分类问题,计算预测值与真实值之间的交叉熵。
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
-
对数损失函数(Logarithmic Loss):适用于二分类问题,计算预测值与真实值之间的对数损失。
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
-
感知机损失函数(Perceptron Loss):适用于二分类问题,计算预测值与真实值之间的误差。
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)
-
Hinge损失函数:适用于支持向量机(SVM)分类问题,计算预测值与真实值之间的误差。
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)
-
KL散度损失函数(Kullback-Leibler Divergence Loss):适用于度量两个概率分布之间的差异。
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