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模型的更多相关文章

  1. 吴裕雄 python 机器学习——半监督学习标准迭代式标记传播算法LabelPropagation模型

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

  2. 吴裕雄 python 机器学习——层次聚类AgglomerativeClustering模型

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

  3. 吴裕雄 python 机器学习——密度聚类DBSCAN模型

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

  4. 吴裕雄 python 机器学习——支持向量机非线性回归SVR模型

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

  5. 吴裕雄 python 机器学习——KNN回归KNeighborsRegressor模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from skle ...

  6. 吴裕雄 python 机器学习——KNN分类KNeighborsClassifier模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from skle ...

  7. 吴裕雄 python 机器学习——支持向量机线性回归SVR模型

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

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

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

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

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

随机推荐

  1. PIE-SDK For C++栅格数据集的读取

    1.功能简介 栅格数据包含很多信息,在数据的运用中需要对数据的信息进行读取,目前PIE SDK支持多种数据格式的数据读取,下面对栅格数据格式的数据读取功能进行介绍. 2.功能实现说明 2.1 实现思路 ...

  2. idea AutoWired 报红

  3. PHP实现导出CSV文件

    在做导出一个信息表为excel文件这个功能完成之后,自己用得好好的,但是到HR那边就告诉我导出的文件无法用她电脑上的office打开,心想,兼容没做好,想问下她的版本号,结果半天没回复消息.我老大来了 ...

  4. GCC中 -I、-L、-l 选项的作用

    在makefile中经常会看到这些选项,gcc默认会在程序当前目录.path路径中查找所需要的材料 如何给gcc添加我们自己的原材料(头文件,库等) -I (注意是大写的i) 给gcc添加自定义的头文 ...

  5. Linq To Sqlite使用心得

    若要使用Linq To Sqlite类库,可以安装Devart Linq Connect Model,如图: 新建这个Model就可以和Linq To Sql一样使用Linq模型,下载地址:https ...

  6. 全排列(dfs-有重复数字)

    给出一个字符串S(可能有重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列.例如:S = "1312", 输出为:   1123 1132 1213 1231 131 ...

  7. 16day 路径信息系列

    ../ 上一级目录 ./ 当前路径 ~ 返回到家目录 - 两个目录之间进行快速切换 An argument of - is equivalent to $OLDPWD(环境变量) 补充说明: [roo ...

  8. 题解【洛谷P1433】吃奶酪

    题面 看到数据范围那么小,一眼状压\(\text{DP}\). 设\(dp[i][s]\)表示从\(i\)出发,走过的点的集合为\(s\)的最小距离. 不难推出转移方程(\(dis(i,j)\)为\( ...

  9. kao shi di er ti(还没有订正)

    // 离散化点 思路应该是对的 吧 但没时间去检查编译上的错误 #include <bits/stdc++.h> using namespace std; ; #define ri reg ...

  10. Oracle VM VirtualBox - ping不通虚拟机

    问题描述 用Oracle VM VirtualBox创建虚拟机后,本机电脑ping不通虚拟机 解决方案 https://www.cnblogs.com/ranrongzhen/p/6958485.ht ...