支持向量机(二)

 一.理论
1.总结
1)训练好的模型的算法复杂度由支持向量的个数决定的,而不是由数据的维度决定的。所以SVM不太容易产生overfitting(过拟合)
2)SVM训练出来的模型完全依赖于支持向量,即使训练集中所有非支持向量的点被去除,重复训练过程,结果仍然会得到完全一样的模型。
3)一个SVM如果训练得出的支持向量个数比较少,SVM训练出的模型比较容易被泛化。
2.线性不可分的情况
1)数据集在空间中对应的向量不可被一个超平面分开
2)解决方法:
a.利用一个非线性的映射把元数据集中的向量点转化到一个更高维度的空间中;

b.在这个高维度的空间中找一个线性的超平面来根据线性可分的情况处理;


3.如何利用非线性映射把原数据转化到高维中?

1)将三维转化至六维


2)思考
如何选择合理的非线性转化把数据转到高维中?
如何解决计算内积时算法复杂度非常高的问题?
3)使用核方法
4.核方法

1)动机:在线性SVM转化为最优化问题时求解的公式计算都是以内积的形式出现的

是把训练集中的向量点转化到高维的非线性映射函数,因为内积的算法复杂度非常大,所以我们利用核函数来取代计算非线性映射函数的内积。
以下核函数和非线性映射函数的内积等同:

2)常用的核函数(kernel functions)


3)问题
如何选择使用哪个核函数?
根据先验知识,比如图像分类,通常使用RBF,文字不适用RBF
尝试不同的kernel,根据结果准确度而定

4)核函数举例


5.SVM扩展可解决多个类别分类问题
对于每个类,有一个当前类和其他类的二类分类器(one-vs-rest)

二.实践

1)代码

# -*- coding: utf-8 -*-
#使用SVM进行人脸识别
from time import time #程序运行时间
import logging  #打印程序信息
import matplotlib.pyplot as plt #图形化


from sklearn.cross_validation import train_test_split
from sklearn.datasets import fetch_lfw_people
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import RandomizedPCA
from sklearn.svm import SVC


print(__doc__)
#打印程序进展信息
logging.basicConfig(level=logging.INFO,format='%(asctime)s %(message)s')
#下载数集
lfw_people = fetch_lfw_people(min_faces_per_person =70,resize=0.4)
#数据集中获取样本数量、高度、宽度
n_samples,h,w = lfw_people.images.shape


#获取数据
X = lfw_people.data 
#多少维度,特征值数量
n_features = X.shape[1]
#图片标记
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]


print("Total dataset size")
print("n_samples:%d"%n_samples)
print("n_features:%d"%n_features)
print("n_classes:%d"%n_classes)
#数据分为训练集和测试集
X_train,X_test,y_train,y_test = train_test_split(
X,y,test_size=0.25)


n_components = 150


print("Extracting the top %d eigenfaces from %d faces"
      %(n_components,X_train.shape[0]))
#开始计时
t0 = time()
#高维的特征向量降维
pca = RandomizedPCA(n_components = n_components,whiten=True).fit(X_train)
print("done in %0.3fs"%(time()-t0))
#人脸中提取特征值
eigenfaces = pca.components_.reshape(n_components,h,w)


print("Projecting the input data on the eigenfaces orthonormal basis")
t0 = time()
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("done is %0.3fs"%(time()-t0))


#降维后的数据结合分类器进行分类
print("Fitting the classifiter to the training set")
t0 = time()
param_grid = {"C":[1e3,5e3,1e4,5e4,1e5],
              "gamma":[0.0001,0.0005,0.001,0.005,0.01,0.1],}
clf = GridSearchCV(SVC(kernel="rbf",class_weight="auto"),param_grid)
clf = clf.fit(X_train_pca,y_train)
print("done is %0.3fs"%(time()-t0))
print("Best estimator found by gird search")
print(clf.best_estimator_)


#测试集预测
print("Predicting people's names on the test set")
t0 = time()
y_pred = clf.predict(X_test_pca)
print("done is % 0.3fs"%(time()-t0))


print(classification_report(y_test,y_pred,target_names=target_names))
print(confusion_matrix(y_test,y_pred,labels=range(n_classes)))


#结果显示
def plot_gallery(images ,title,h,w,n_row=3,n_clo=4):
    plt.figure(figsize=(1.8*n_clo,2.4*n_row))
    plt.subplots_adjust(bottom=0,left=.01,right=.99,top=.90,hspace=.35)
    for i in range(n_clo*n_row):
        plt.subplot(n_row,n_clo,i+1)
        plt.imshow(images[0].reshape(h,w),cmp=plt.cm.gray)
        plt.title(title[i],size=12)
        plt.xticks()
        plt.yticks()
def title(y_pred,y_test,target_names,i):
    pred_name = target_names[y_pred[i]].rsplit(" ",1)[-1]
    true_name = target_names[y_test[i]].rsplit(" ",1)[-1]
    return "predicted:%s\ntrue:   %s"%(pred_name,true_name)


prediction_titles = [title(y_pred,y_test,target_names,i)
                for i in range(y_pred.shape[0])]


plot_gallery(X_test,prediction_titles,h,w)


eigenfaces_titles = ["eigentitles %d"
                     %i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces,eigenfaces_titles,h,w)


plt.show()

2)实验结果

Total dataset size
n_samples:1288
n_features:1850
n_classes:7
Extracting the top 150 eigenfaces from 966 faces

done is 33.550s
Best estimator found by gird search
SVC(C=1000.0, cache_size=200, class_weight='auto', coef0=0.0,
  decision_function_shape=None, degree=3, gamma=0.005, kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)
Predicting people's names on the test set
done is 0.097s
                   precision    recall  f1-score   support


     Ariel Sharon       1.00      0.54      0.70        24
     Colin Powell       0.81      0.82      0.81        61
  Donald Rumsfeld       0.81      0.81      0.81        21
    George W Bush       0.81      0.97      0.88       136
Gerhard Schroeder       0.74      0.64      0.68        22
      Hugo Chavez       0.91      0.59      0.71        17
       Tony Blair       1.00      0.80      0.89        41


      avg / total       0.85      0.84      0.83       322


[[13  3  1 ...,  0  0  0]
 [ 0 50  1 ...,  0  1  0]
 [ 0  3 17 ...,  0  0  0]
 ..., 
 [ 0  0  1 ..., 14  0  0]
 [ 0  1  0 ...,  2 10  0]
 [ 0  3  0 ...,  2  0 33]]

3)数据加载位置

runfile('E:/Python项目/MachineLearning/SVM/SVM03.py', wdir='E:/Python项目/MachineLearning/SVM')
2017-11-04 22:16:49,322 Loading LFW people faces fromC:\Users\流浪者\scikit_learn_data\lfw_home

在程序中:lfw_people = fetch_lfw_people(min_faces_per_person =70,resize=0.4)加载数据,可以考虑将数据在网站上下载至对应位置

即将lfw_funneled文件夹复制在:C:\Users\流浪者\scikit_learn_data\lfw_home之下,形成


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值