import numpy as np
import matplotlib.pyplot as plt from sklearn import metrics
from sklearn import datasets
from sklearn.semi_supervised import LabelPropagation 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]
###### 生成未标记样本的下标集合 ####
# 只有 10% 的样本有标记
n_labeled_points = int(len(y)/10)
# 后面 90% 的样本未标记
unlabeled_indices = np.arange(len(y))[n_labeled_points:]
return X,y,unlabeled_indices #半监督学习标准迭代式标记传播算法LabelPropagation模型
def test_LabelPropagation(*data):
'''
测试 LabelPropagation 的用法
'''
X,y,unlabeled_indices=data
# 必须拷贝,后面要用到 y
y_train=np.copy(y)
# 未标记样本的标记设定为 -1
y_train[unlabeled_indices]=-1
clf=LabelPropagation(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))
# 或者 print("Accuracy:%f"%clf.score(X[unlabeled_indices],true_labels)) # 获取半监督分类数据集
data=load_data()
# 调用 test_LabelPropagation
test_LabelPropagation(*data)

def test_LabelPropagation_rbf(*data):
'''
测试 LabelPropagation 的 rbf 核时,预测性能随 alpha 和 gamma 的变化
'''
X,y,unlabeled_indices=data
# 必须拷贝,后面要用到 y
y_train=np.copy(y)
# 未标记样本的标记设定为 -1
y_train[unlabeled_indices]=-1 fig=plt.figure()
ax=fig.add_subplot(1,1,1)
alphas=np.linspace(0.01,1,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=LabelPropagation(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("LabelPropagation rbf kernel")
plt.show() # 调用 test_LabelPropagation_rbf
test_LabelPropagation_rbf(*data)

def test_LabelPropagation_knn(*data):
'''
测试 LabelPropagation 的 knn 核时,预测性能随 alpha 和 n_neighbors 的变化
'''
X,y,unlabeled_indices=data
y_train=np.copy(y) # 必须拷贝,后面要用到 y
y_train[unlabeled_indices]=-1 # 未标记样本的标记设定为 -1 fig=plt.figure()
ax=fig.add_subplot(1,1,1)
alphas=np.linspace(0.01,1,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=LabelPropagation(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("LabelPropagation knn kernel")
plt.show() # 调用 test_LabelPropagation_knn
test_LabelPropagation_knn(*data)

吴裕雄 python 机器学习——半监督学习标准迭代式标记传播算法LabelPropagation模型的更多相关文章

  1. 吴裕雄 python 机器学习——半监督学习LabelSpreading模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn import d ...

  2. 吴裕雄 python 机器学习——人工神经网络与原始感知机模型

    import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from ...

  3. 吴裕雄 python 机器学习——分类决策树模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.model_s ...

  4. 吴裕雄 python 机器学习——回归决策树模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.model_s ...

  5. 吴裕雄 python 机器学习——线性判断分析LinearDiscriminantAnalysis

    import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot ...

  6. 吴裕雄 python 机器学习——逻辑回归

    import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot ...

  7. 吴裕雄 python 机器学习——ElasticNet回归

    import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot ...

  8. 吴裕雄 python 机器学习——Lasso回归

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model from s ...

  9. 吴裕雄 python 机器学习——岭回归

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model from s ...

随机推荐

  1. AVR单片机丢固件原因分析和解决方案

    一.硬件方面 除了下面列举的方面,还需要评估下其他措施. 1.电源因素,禁干扰. 只要用廉价劣质的开关电源,不管哪个单片机,都存在EEPROM丢数据和单片机程序丢失的情况. 1.转接板走线,直接接到了 ...

  2. 题解【洛谷P1083】[NOIP2012]借教室

    题面 二分到哪一个申请人要修改订单,可以差分\(+\)前缀和达到\(\Theta(n)\)的\(\text{check}\). 具体细节见代码. #include <bits/stdc++.h& ...

  3. 转载:polyphase filter

    http://www.ws.binghamton.edu/fowler/fowler%20personal%20page/ee521.htm http://www.ws.binghamton.edu/ ...

  4. url 获取 geoserver 中对应的style

    http://userName:password@127.0.0.1:7093/geoserver/rest/workspaces/FAST/styles/AVG_RSRP.sld

  5. PHP实现推送微信小程序模板消息

    这边只会写如何实现,至于在公众号管理后台添加模板消息可以参考这篇文章: https://www.cnblogs.com/txw1958/p/wechat-template-message.html,当 ...

  6. 2、gitlab使用及权限管理

    目录 1.创建用户组... 2 2.创建用户... 4 3.新建项目... 5 4.linux端访问项目... 6 4.1 通过ssh方式访问... 6 4.2 通过http访问... 9 5.win ...

  7. python面试的100题(17)

    内存管理与垃圾回收机制 48.哪些操作会导致Python内存溢出,怎么处理? 内存溢出:你申请了10个字节的内存,但写入了大于10个字节的数据会导致内存溢出 内存溢出原因:1.内存中加载的数据量过于庞 ...

  8. 三、linux环境的搭建1(oracle、ssh、jdk、mysql、samba、tomcat)

    linux环境的搭建1(oracle.ssh.jdk.mysql.samba.tomcat)   网络配置 方案一 tip 1 使用ifconfig : ifconfig eth0 新ip 然后编辑/ ...

  9. 【Unity|C#】基础篇(7)——属性(Property)/ 索引器(Indexer)

    [学习资料] <C#图解教程>(第6章):https://www.cnblogs.com/moonache/p/7687551.html 电子书下载:https://pan.baidu.c ...

  10. arm-linux下qt + opencv开发环境的搭建(Altera DE1 Soc)

    arm-linux-gnueabihf-gcc下载 qt下载 arm-linux下qt + opencv开发环境的搭建(Altera DE1 Soc) Ubuntu 16.04 安装QT arm嵌入式 ...