机器学习 4种常见目标函数介绍+代码实现

2025-09-01 11:58:44

目标函数在机器学习中至关重要,不同的目标函数甚至能影像模型的性能。

目标函数类似于损失函数的总称,然后让目标函数优化取得最大或者最小值这样,总而让网络收敛

更多介绍参考本专栏:pytorch 深度学习初体验_喵星人监护人的博客-CSDN博客

1、 线性函数

线性函数是机器学习、深度学习中最简单的目标函数之一

线性函数是一种最简单的核函数,它假设样本在原始特征空间上是线性可分的,因此在不引入额外的复杂度的情况下,直接在原始特征空间上进行内积计算

实验代码如下:

import numpy as np

import matplotlib.pyplot as plt

from sklearn.datasets import make_classification

from sklearn.svm import SVC

# 生成一个线性不可分的数据集

X, y = make_classification(n_samples=100, n_features=2, n_redundant=0, n_clusters_per_class=1, random_state=42)

# 使用线性核函数的 SVM 分类器

svm_linear = SVC(kernel='linear')

svm_linear.fit(X, y)

# 绘制决策边界

plt.figure(figsize=(8, 6))

plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired, marker='o', edgecolors='k')

# 生成网格数据用于绘制决策边界

ax = plt.gca()

xlim = ax.get_xlim()

ylim = ax.get_ylim()

xx, yy = np.meshgrid(np.linspace(xlim[0], xlim[1], 100), np.linspace(ylim[0], ylim[1], 100))

Z = svm_linear.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)

# 绘制决策边界和支持向量

plt.contourf(xx, yy, Z, alpha=0.2, cmap=plt.cm.Paired)

plt.scatter(svm_linear.support_vectors_[:, 0], svm_linear.support_vectors_[:, 1], s=100, facecolors='none', edgecolors='k')

plt.title