rbf-svm在lfw上demo

from matplotlib import pyplot as plt
from sklearn.datasets import fetch_lfw_people
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
import time

faces=fetch_lfw_people(min_faces_per_person=60) #一个人人脸图像数少于60就不作为样本

print(faces.target_names)

print(faces.images.shape)

fig,ax=plt.subplots(3,5)
for i, axi in enumerate(ax.flat):
axi.imshow(faces.images[i],cmap=“bone”)
axi.set(xticks=[],yticks=[],xlabel=faces.target_names[faces.target[i]])

#每个图62*47,需要降维,降到150维

pca=PCA(n_components=150,whiten=True,random_state=42) #random_state就是随机种子,控制每次随机结果一样
svc=SVC(kernel=“rbf”,class_weight=“balanced”)
model=make_pipeline(pca,svc)

#在sklearn中构造训练集和验证集
Xtrain,Xtest,ytrain,ytest=train_test_split(faces.data,faces.target,random_state=40)

#用GridSearchCV来寻找参数,c,gamma,给出几个值,遍历
param_grid={“svc__C”:[2,3,4],
“svc__gamma”:[0.0015,0.0017,0.0019]

}
grid=GridSearchCV(model,param_grid)
%time grid.fit(Xtrain,ytrain)
print(grid.best_params_)

model=grid.best_estimator_
yfit=model.predict(Xtest)
yfit.shape

#画出结果
fig, ax=plt.subplots(4,6)
for i, axi in enumerate(ax.flat):
axi.imshow(Xtest[i].reshape(62,47),cmap=“bone”)
axi.set(xticks=[],yticks=[])
axi.set_ylabel(faces.target_names[yfit[i]].split()[-1],
color=“black” if yfit[i]==ytest[i] else “red”
)
fig.suptitle(“Predicted names;Incorrect labels in red”,size=18)

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值