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

def test_LabelSpreading_rbf(*data):
'''
测试 LabelSpreading 的 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=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
test_LabelSpreading_rbf(*data)

def test_LabelSpreading_knn(*data):
'''
测试 LabelSpreading 的 knn 核时,预测性能随 alpha 和 n_neighbors 的变化
'''
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)
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(kernel='knn',max_iter=100,n_neighbors=K,alpha=alpha)
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
test_LabelSpreading_knn(*data)

吴裕雄 python 机器学习——半监督学习LabelSpreading模型的更多相关文章
- 吴裕雄 python 机器学习——半监督学习标准迭代式标记传播算法LabelPropagation模型
import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn import d ...
- 吴裕雄 python 机器学习——层次聚类AgglomerativeClustering模型
import numpy as np import matplotlib.pyplot as plt from sklearn import cluster from sklearn.metrics ...
- 吴裕雄 python 机器学习——密度聚类DBSCAN模型
import numpy as np import matplotlib.pyplot as plt from sklearn import cluster from sklearn.metrics ...
- 吴裕雄 python 机器学习——支持向量机非线性回归SVR模型
import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model,svm fr ...
- 吴裕雄 python 机器学习——KNN回归KNeighborsRegressor模型
import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from skle ...
- 吴裕雄 python 机器学习——KNN分类KNeighborsClassifier模型
import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from skle ...
- 吴裕雄 python 机器学习——支持向量机线性回归SVR模型
import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model,svm fr ...
- 吴裕雄 python 机器学习——分类决策树模型
import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.model_s ...
- 吴裕雄 python 机器学习——回归决策树模型
import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.model_s ...
随机推荐
- H3C ARP配置
一.ARP简介 ARP(Address Resolution Protocol,地址解析协议)是将IP地址解析为以太网MAC地址(或称物理地址)的协议. 在网络中,当主机或其它网络设备有数据要发送给另 ...
- Pytest学习7-参数化
在测试过程中,参数化是必不可少的功能,本文就讨论下pytest的几种参数化方法 @pytest.mark.parametrize:参数化测试函数 1.内置的pytest.mark.parametriz ...
- ASPxGridView 排序、分页、加载数据必需的三个函数
protected void ASPxGridViewPoint_OnCustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs ...
- linux - mysql:安装mysql
安装环境 系统是 centos6.5 1.下载 下载地址:http://dev.mysql.com/downloads/mysql/5.6.html#downloads 下载版本:我这里选择的5.6. ...
- webpack 之loader
webpack的作用: 是 用来处理我们写的js代码.并且会自动处理js之间相关的依赖. 但是,开发中我们不仅仅有基本的js代码处理,还需要加载css,图片,也包括一些高级的 将ES6转成ES5代 ...
- c# 嵌入资源并读取
原文:c# 嵌入资源并读取 1. 右键点击项目,选择资源,然后选择资源的类型,插入资源. 2. 这时候在项目的目录树上会出现一个Resource的文件夹,找到嵌入的资源文件,右击属性,在 Build ...
- JQuery-Snowfall降雪插件使用
一个很好使用的降雪插件,可以实现雪花.爱心.图片等下降落. 1.JQuery-Snowfall插件的使用方法: 增加了使用图像作为雪花而不是纯色元素的功能. $(element).snowfa ...
- 12c的PDB创建DIRECTORY要注意与PATH_PREFIX的关系(ORA-65254)
在创建PDB过程中如果使用了带PATH_PREFIX的参数,意味着在创建DIRECTORY目录时需要指定相对路径,而不能指定其它绝对路径.来自博客园AskScuti 11g整库作为一个PDB迁移至阿里 ...
- memcached和redis对比
关于memcached和redis的使用场景,总结如下:两者对比: redis提供数据持久化功能,memcached无持久化. redis的数据结构比memcached要丰富,能完成场景以外的事情: ...
- SuperSocket与SuperSocket.ClientEngine实现Protobuf协议
参考资料说明 SuperSocket文档 http://docs.supersocket.net/ Protobuf语言参考 https://developers.google.com/protoco ...