半监督学习——LabelSpreading

模型原型

class sklearn.semi_supervised.LabelSpreading(kernel=’rbf’,gamma=20,n_neighbors=7,alpha=0.2,max_iter=30,tol=0.001)
参数

  • kernel
  • gamma
  • n_neighbors
  • alpha
  • max_iter
  • tol

属性

  • X_
  • classes_
  • labeldistributions
  • transduction_
  • niter

方法

  • fit(X,y)
  • predict(X)
  • predict_proba(X)
  • score(X,y[,sample_weight])
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn import datasets
from sklearn.semi_supervised import LabelSpreading

加载数据集

def load_data():
    digits=datasets.load_digits()
    #混洗样本
    rng=np.random.RandomState(0)
    indices=np.arange(len(digits.data))
    rng.shuffle(indices)
    X=digits.data[indices]
    y=digits.target[indices]
    #生成未标记样本的下标集合
    n_labeled_points=int(len(y)/10)
    unlabeled_indices=np.arange(len(y))[n_labeled_points:]
    return X,y,unlabeled_indices

使用test_LabelSpreading类

def test_LabelSpreading(*data):
    X,y,unlabeled_indices=data
    y_train=np.copy(y)
    y_train[unlabeled_indices]=-1
    clf=LabelSpreading(max_iter=100,kernel='rbf',gamma=0.1)
    clf.fit(X,y_train)

    #获取预测准确率
    predicted_labels=clf.transduction_[unlabeled_indices]
    true_labels=y[unlabeled_indices]
    print('Accuracy:%f'%metrics.accuracy_score(true_labels,
        predicted_labels))

data=load_data()
test_LabelSpreading(*data)

折中系数alpha以及gamma参数对rbf核的影响

def test_LabelSpreading_rbf(*data):
    X,y,unlabeled_indices=data
    y_train=np.copy(y)
    y_train[unlabeled_indices]=-1

    fig=plt.figure()
    ax=fig.add_subplot(1,1,1)
    alphas=np.linspace(0.01,0.99,num=10,endpoint=True)
    gammas=np.logspace(-2,2,num=50)
    colors=((1,0,0),(0,1,0),(0,0,1),(0.5,0.5,0),(0,0.5,0.5),
        (0.5,0,0.5),(0.4,0.6,0),(0.6,0.4,0),(0,0.6,0.4),(0.5,0.3,0.2),)
    #训练并绘图
    for alpha,color in zip(alphas,colors):
        scores=[]
        for gamma in gammas:
            clf=LabelSpreading(max_iter=100,gamma=gamma,
                alpha=alpha,kernel='rbf')
            clf.fit(X,y_train)
            scores.append(clf.score(X[unlabeled_indices],
                y[unlabeled_indices]))
        ax.plot(gammas,scores,label=r"$\alpha=%s$"%alpha,color=color)

    #设置图形
    ax.set_xlabel(r'$\gamma$')
    ax.set_ylabel('score')
    ax.set_xscale('log')
    ax.legend(loc='best')
    ax.set_title('LabelSpreading rbf kernel')
    plt.show()

test_LabelSpreading_rbf(*data)

折中系数alpha以及n_neighbors参数对knn核的影响

def test_LabelSpreading_knn(*data):
    X,y,unlabeled_indices=data
    y_train=np.copy(y)
    y_train[unlabeled_indices]=-1

    fig=plt.figure()
    ax=fig.add_subplot(1,1,1)
    alphas=np.linspace(0.01,0.99,num=10,endpoint=True)
    Ks=[1,2,3,4,5,8,10,15,20,25,30,35,40,50]
    colors=((1,0,0),(0,1,0),(0,0,1),(0.5,0.5,0),(0,0.5,0.5),
        (0.5,0,0.5),(0.4,0.6,0),(0.6,0.4,0),(0,0.6,0.4),(0.5,0.3,0.2),)

    #训练并绘图
    for alpha,color in zip(alphas,colors):
        scores=[]
        for K in Ks:
            clf=LabelSpreading(max_iter=100,n_neighbors=K,
                alpha=alpha,kernel='knn')
            clf.fit(X,y_train)
            scores.append(clf.score(X[unlabeled_indices],
                y[unlabeled_indices]))
        ax.plot(Ks,scores,label=r"$\alpha=%s$"%alpha,color=color)
    #设置图形
    ax.set_xlabel(r'$k$')
    ax.set_ylabel('score')
    ax.legend(loc='best')
    ax.set_title('LabelSpreading knn kernel')
    plt.show()

test_LabelSpreading_knn(*data)
### 监督学习、无监督学习和半监督学习在跨领域场景中的差异与联系 #### 差异分析 1. **监督学习 (Supervised Learning)** 在跨领域应用中,监督学习依赖于目标领域的标注数据来构建模型。然而,在实际情况下,不同领域之间可能存在分布差异(即域偏移 Domain Shift),这可能导致源领域上的高性能模型无法很好地适应目标领域[^2]。为了缓解这一问题,通常会采用迁移学习技术,通过调整特征表示或优化策略使模型更好地适配新领域。 2. **无监督学习 (Unsupervised Learning)** 由于无需标注数据,无监督学习非常适合处理未标记的目标领域数据集。它能够发现隐藏模式并提取通用特征向量用于后续任务。但是单独依靠无结构化的输入可能会导致较低精度的结果,尤其是在面对复杂多样的应用场景时[^3]。 3. **半监督学习 (Semi-supervised Learning)** 对于跨领域情况下的少量已知类别实例加上大量未知分类的数据组合而言,半监督方法展现出了独特的优势——既利用了带标签样本提高准确性又借助海量非标注资料增强泛化能力从而减少因缺乏充分训练而导致过拟合的风险同时还能获得较优解质量[^1]。 #### 关联探讨 尽管三种方式各有侧重但在某些特定条件下它们并非完全独立而是相互补充甚至融合形成新的解决方案路径: - 当存在显著的领域差距而仅有稀缺的手动打分记录可用作参考依据之时,则可先运用自编码器之类的降维算法完成初步探索再引入部分人工干预逐步完善整个体系直至达到预期效果为止; - 另一方面如果两个相距甚远却共享相似底层规律的不同业务范畴间希望通过知识传递实现快速部署那么基于共同表征空间映射机制设计出来的联合框架便成为可行选项之一其中可能涉及到多种混合形式比如伪标签生成过程或者一致性正则项约束条件等等最终目的是让各个子模块都能发挥各自特长共同促进整体表现提升。 ```python # 示例代码展示如何简单模拟一个基本的半监督学习流程 import numpy as np from sklearn.semi_supervised import LabelSpreading def semi_supervised_example(): # 假设我们有一些带有标签的数据以及更多没有标签的数据 labeled_data = [[0], [1]] unlabeled_data = [[2], [3], [4], [5]] labels = [-1, -1, 1, 1, -1, -1] # 使用-1表示未标注 model = LabelSpreading(kernel='knn', alpha=0.8) combined_data = labeled_data + unlabeled_data model.fit(combined_data, labels) predicted_labels = model.transduction_ probabilities = model.predict_proba(unlabeled_data) return predicted_labels, probabilities predicted_labels, probabilities = semi_supervised_example() print(predicted_labels) print(probabilities) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值