监督分类——最小距离分类、最大似然分类、支持向量机

本文将详细介绍三种常见的监督分类方法:最小距离分类器最大似然分类器支持向量机(SVM)。每种方法都会包括原理、数学公式、具体例子和Python代码(含原图及分类结果可视化)。


1. 最小距离分类器(Minimum Distance Classifier)

原理

最小距离分类器是一种基于距离度量的简单分类方法。它将每个样本与各类别的均值(中心)计算欧氏距离,样本分配给距离最近的类别。适用于各类别内部方差相等且协方差为零的情况。

数学公式

对于样本 ( x ) 和第 ( i ) 类均值:
di(x)=(x−μi)T(x−μi) d_i(x) = \sqrt{(x-\mu_i)^T(x-\mu_i)} di(x)=(xμi)T(xμi)
样本 ( x ) 属于距离最近的类别 i,即:
i∗=arg⁡min⁡idi(x) i^* = \arg\min_{i} d_i(x) i=argimindi(x)

Python代码示例

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA

# 加载数据,用的是乳腺癌数据集
data = load_breast_cancer()
X = data.data
y = data.target

# 用PCA降维到二维,便于可视化
pca = PCA(n_components=2)
X2 = pca.fit_transform(X)

# 计算每一类的均值
mu0 = X2[y == 0].mean(axis=0)
mu1 = X2[y == 1].mean(axis=0)

def min_distance_classifier(X, mus):
    dists = np.array([np.linalg.norm(X - mu, axis=1) for mu in mus])
    return np.argmin(dists, axis=0)

pred = min_distance_classifier(X2, [mu0, mu1])

# 可视化
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].scatter(X2[:, 0], X2[:, 1], c=y, cmap='bwr', label='True')
axes[0].set_title('Original')
axes[0].set_xlabel('PC1')
axes[0].set_ylabel('PC2')

axes[1].scatter(X2[:, 0], X2[:, 1], c=pred, cmap='bwr')
# axes[1].scatter([mu0[0], mu1[0]], [mu0[1], mu1[1]], c=['red', 'blue'], marker='*', s=200, label='Mean')
axes[1].set_title('Minimum Distance Classification Result')
axes[1].set_xlabel('PC1')
axes[1].set_ylabel('PC2')
axes[1].legend()
plt.tight_layout()
plt.show()

结果:
在这里插入图片描述


2. 最大似然分类器(Maximum Likelihood Classifier)

原理

最大似然分类器基于贝叶斯判别原理。对于每个样本,计算其属于各类别的概率密度(通常假设高斯分布),并结合先验概率,选取后验概率最大的类别。

数学公式

后验概率:
p(ωi∣x)∝p(x∣ωi)P(ωi) p(\omega_i|x) \propto p(x|\omega_i)P(\omega_i) p(ωix)p(xωi)P(ωi)
如果各类别先验相同,则只需比较似然项 ( p(x|\omega_i) )。常见情况下,假设各类别为高斯分布:
p(x∣ωi)=1(2π)d/2∣Σi∣1/2exp⁡(−12(x−μi)TΣi−1(x−μi)) p(x|\omega_i) = \frac{1}{(2\pi)^{d/2}|\Sigma_i|^{1/2}} \exp\left(-\frac{1}{2}(x - \mu_i)^T \Sigma_i^{-1}(x - \mu_i)\right) p(xωi)=(2π)d/2Σi1/21exp(21(xμi)TΣi1(xμi))

Python代码示例

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from scipy.stats import multivariate_normal

data = load_breast_cancer()
X = data.data
y = data.target

# PCA降到二维
pca = PCA(n_components=2)
X2 = pca.fit_transform(X)

# 估计高斯分布参数
mu0, cov0 = X2[y == 0].mean(axis=0), np.cov(X2[y == 0], rowvar=False)
mu1, cov1 = X2[y == 1].mean(axis=0), np.cov(X2[y == 1], rowvar=False)

def ml_classifier(X, params):
    probs = [multivariate_normal(mean=mu, cov=cov).pdf(X) for mu, cov in params]
    return np.argmax(np.stack(probs, axis=1), axis=1)

pred = ml_classifier(X2, [(mu0, cov0), (mu1, cov1)])

fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].scatter(X2[:, 0], X2[:, 1], c=y, cmap='bwr')
axes[0].set_title('Original Data (PCA Projection)')
axes[0].set_xlabel('PC1')
axes[0].set_ylabel('PC2')

axes[1].scatter(X2[:, 0], X2[:, 1], c=pred, cmap='bwr')
axes[1].set_title('Maximum Likelihood Classification Result')
axes[1].set_xlabel('PC1')
axes[1].set_ylabel('PC2')
plt.tight_layout()
plt.show()

结果:
在这里插入图片描述


3. 支持向量机(SVM)

原理

SVM是一种判别式模型,通过寻找一个最优超平面,将不同类别样本分开,并最大化两类之间的间隔。对于线性可分情况,目标是:
min⁡w,b12∥w∥2 \min_{w,b} \frac{1}{2} \|w\|^2 w,bmin21w2
约束条件:
yi(wTxi+b)≥1 y_i(w^T x_i + b) \geq 1 yi(wTxi+b)1
对于非线性情况,可通过核函数映射到高维空间。

Python代码示例

用scikit-learn的SVM对两类数据进行分类并可视化决策边界。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.svm import SVC

data = load_breast_cancer()
X = data.data
y = data.target

# PCA降维
pca = PCA(n_components=2)
X2 = pca.fit_transform(X)

clf = SVC(kernel='linear')
clf.fit(X2, y)
pred = clf.predict(X2)

def plot_decision_boundary(clf, X, y, ax):
    x_min, x_max = X[:, 0].min()-1, X[:, 0].max()+1
    y_min, y_max = X[:, 1].min()-1, X[:, 1].max()+1
    xx, yy = np.meshgrid(np.linspace(x_min, x_max, 300), np.linspace(y_min, y_max, 300))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    ax.contourf(xx, yy, Z, alpha=0.3, cmap='bwr')
    ax.scatter(X[:, 0], X[:, 1], c=y, cmap='bwr', edgecolors='k')
    ax.set_title('SVM Classification Result')
    ax.set_xlabel('PC1')
    ax.set_ylabel('PC2')

fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].scatter(X2[:, 0], X2[:, 1], c=y, cmap='bwr')
axes[0].set_title('Original Data (PCA Projection)')
axes[0].set_xlabel('PC1')
axes[0].set_ylabel('PC2')

plot_decision_boundary(clf, X2, y, axes[1])
plt.tight_layout()
plt.show()

结果:
在这里插入图片描述


### 关于机器学习中的最大似然分类算法 #### 定义与原理 最大似然估计(Maximum Likelihood Estimation, MLE)是一种用于参数估计的方法,在给定数据集的情况下寻找使得模型最有可能产生该观测数据的参数值。对于分类问题而言,MLE通过最大化属于某一类别的概率来决定样本所属类别。 在具体实施过程中,假设有一个由多个特征组成的输入向量 \( \mathbf{x}=(x_1,x_2,\ldots ,x_n)\),以及对应的离散标签\( y\in {c_1,c_2,...,c_k}\)表示k个可能的目标类别之一,则可以定义条件概率分布函数\[ P(y|\mathbf{x};\theta)=f(\mathbf{x},y;\theta), \]其中θ代表待估参数。为了找到最佳拟合训练数据的最佳参数设置,目标是最小化负对数似然损失函数: \[ L=-\sum _{i=1}^{N}{\log f({{\textbf {x}}_{(i)}},{y}_{(i)};{{\boldsymbol {\theta }}})}, \] 这里 N 表示总的样例数量[^1]。 #### 实现过程 下面给出Python语言下的简单实现方式,使用scikit-learn库来进行逻辑回归建模作为例子展示如何利用最大似然法完成二元分类任务: ```python from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression import numpy as np # 创建模拟数据集 X, Y = make_classification(n_samples=1000, n_features=20, n_informative=2, n_redundant=10, random_state=42) # 划分训练集测试集 X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=.3,random_state=42) # 构造并训练逻辑回归模型 (默认采用的是最大似然方法) clf = LogisticRegression().fit(X_train,y_train) print("Training set score: {:.3f}".format(clf.score(X_train, y_train))) print("Test set score: {:.3f}".format(clf.score(X_test, y_test))) def log_likelihood(features,label,params): scores=np.dot(params.T,features).reshape(-1,1) predictions=1/(1+np.exp(-scores)) ll=label*np.log(predictions)+(1-label)*np.log(1-predictions) return -ll.sum() params=np.array([[-8],[-7]]) example_feature=X[:5].T example_label=y_train[:5].reshape(-1,1) print('Log-Likelihood:',log_likelihood(example_feature, example_label, params)) ``` 此代码片段展示了创建一个简单的线性可分离的数据集,并构建了一个基于最大似然原则优化权重系数w和偏置b值得到预测结果的概率模型——即逻辑斯谛回归(Logistic Regression)[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值