在真实遥感任务里,“有标签像素太少”是家常便饭。半监督学习的思路是:用少量标注 + 大量未标注样本共同训练,从而提升泛化。本篇聚焦 sklearn.semi_supervised:
- LabelPropagation / LabelSpreading:基于图的标签扩散;
- SelfTrainingClassifier:自训练框架,可包裹任意有监督基学习器(如 SVM)。
评估要科学:只在完全未参与训练的测试集上计算 OA/Kappa/报告;同时严格“无泄露”:Scaler/PCA 仅用已标注训练集拟合。
💻 一键可跑代码(KSC 真实数据:极少标注 + 大量未标注 + 全图预测)
# -*- coding: utf-8 -*-
"""
Sklearn案例⑱:半监督学习(KSC 真实数据)
- 极少标注:从有标签像素中抽取一小部分作为标注训练集
- 未标注池:其余有标签像素的特征,但标签设为 -1(训练时不泄露标签)
- 评估:独立测试集(从最初有标签像素里留出)
- 模型:LabelPropagation / LabelSpreading / SelfTraining(SVM) + 监督SVM对照
- 整图预测:2×2 子图对比
"""
import os, numpy as np, scipy.io as sio, matplotlib.pyplot as plt, matplotlib
from matplotlib.colors import ListedColormap, BoundaryNorm
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.metrics import (confusion_matrix, classification_report,
accuracy_score, cohen_kappa_score)
from sklearn.svm import SVC
from sklearn.semi_supervised import LabelPropagation, LabelSpreading, SelfTrainingClassifier
# ===== 中文显示 =====
matplotlib.rcParams['font.family'] = 'SimHei'
matplotlib.rcParams['axes.unicode_minus'] = False
# ===== 参数区(仅需修改 DATA_DIR)=====
DATA_DIR = r"your_path" # ← 修改为你的 KSC 数据路径(含 KSC.mat / KSC_gt.mat)
PCA_DIM = 30
SEED = 42
LABELED_FRACTION = 0.05 # 已标注训练占比(在有标签像素上分层抽样)
TEST_FRACTION = 0.25 # 独立测试占比(在剩余像素中分层抽样)
# ===== 1) 载入 KSC 数据(仅取有标签像素),并构造“少标注 + 未标注 + 测试”=====
X_cube = sio.loadmat(os.path.join(DATA_DIR, "KSC.mat"))["KSC"].astype(np.float32) # (H,W,B)
Y_map = sio.loadmat(os.path.join(DATA_DIR, "KSC_gt.mat"))["KSC_gt"].astype(int) # (H,W)
h, w, b = X_cube.shape
coords = np.argwhere(Y_map != 0)
X_all = X_cube[coords[:,0], coords[:,1]] # (N,B)
y_all = Y_map[coords[:,0], coords[:,1]] - 1 # 0..C-1
num_classes = int(y_all.max(

最低0.47元/天 解锁文章
1834

被折叠的 条评论
为什么被折叠?



