1. 程式人生 > >5.4支援向量機(SVM)演算法(下)應用

5.4支援向量機(SVM)演算法(下)應用

利用SVM進行人臉識別例項:

# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: YaHuYang

#在python2.x版本中要使用Python3.x的特性,可以使用__future__模組匯入相應的介面,減少對當前低版本影響
#from __future__ import print_function

#計時,程式執行時間
from time import time
#列印程式進展時的一些資訊
import logging
#最後識別出來的人臉通過繪圖打印出來
import matplotlib.pyplot as plt

#當import 一個模組比如如下模組cross_validation時,會有刪除橫線,表示該模組在當前版本可能已經被刪除,在新版本中改為model_selection模組
#DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20."This module will be removed in 0.20.", DeprecationWarning)
#from sklearn.cross_validation import train_test_split
from sklearn.model_selection import train_test_split
from sklearn.datasets import fetch_lfw_people
#grid_search已經被移除
#from sklearn.grid_search import GridSearchCV
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.decomposition import RandomizedPCA
from sklearn.svm import SVC
#匯入混淆矩陣模組confusion_matrix()
from sklearn.metrics import confusion_matrix

print(__doc__)

# Display progress logs on stdout程式進展的資訊打印出來
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')

###############################################################################
# Download the data, if not already on disk and load it as numpy arrays
#下載人臉庫 http://vis-www.cs.umass.edu/lfw/

lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)

# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape

# for machine learning we use the 2 data directly (as relative pixel
# positions info is ignored by this model)
#獲取特徵向量矩陣
X = lfw_people.data
#特徵向量的維度(列數)或者稱特徵點的個數
n_features = X.shape[1]

# the label to predict is the id of the person
#返回每一組的特徵標記
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)


###############################################################################
# Split into a training set and a test set using a stratified k fold
# split into a training and testing set
#將資料集拆分成四個部分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)


###############################################################################
#PCA降維方法,減少特徵值,降低複雜度。
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
# dataset): unsupervised feature extraction / dimensionality reduction
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 in %0.3fs" % (time() - t0))


###############################################################################
# Train a SVM classification model

print("Fitting the classifier 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 = GridSearchCV(SVC(kernel='rbf'), param_grid)
clf = clf.fit(X_train_pca, y_train)
print("done in %0.3fs" % (time() - t0))
print("Best estimator found by grid search:")
print(clf.best_estimator_)


###############################################################################
# Quantitative evaluation of the model quality on the test set

print("Predicting people's names on the test set")
t0 = time()
y_pred = clf.predict(X_test_pca)
print("done in %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)))


###############################################################################
# Qualitative evaluation of the predictions using matplotlib

def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
    """Helper function to plot a gallery of portraits"""
    plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
    plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
    for i in range(n_row * n_col):
        plt.subplot(n_row, n_col, i + 1)
        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
        plt.title(titles[i], size=12)
        plt.xticks(())
        plt.yticks(())


# plot the result of the prediction on a portion of the test set

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)

# plot the gallery of the most significative eigenfaces

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

plt.show()

結果:Total dataset size:
n_samples: 1288
n_features: 1850
n_classes: 7
Extracting the top 150 eigenfaces from 966 faces
D:\anaconda3\anaconda3install\lib\site-packages\sklearn\utils\deprecation.py:58: DeprecationWarning: Class RandomizedPCA is deprecated; RandomizedPCA was deprecated in 0.18 and will be removed in 0.20. Use PCA(svd_solver='randomized') instead. The new implementation DOES NOT store whiten ``components_``. Apply transform to get them.
  warnings.warn(msg, category=DeprecationWarning)
done in 3.302s
Projecting the input data on the eigenfaces orthonormal basis
done in 0.020s
Fitting the classifier to the training set
done in 29.999s
Best estimator found by grid search:
SVC(C=1000.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', 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 in 0.068s
                   precision    recall  f1-score   support


     Ariel Sharon       0.91      0.59      0.71        17
     Colin Powell       0.82      0.91      0.86        65
  Donald Rumsfeld       0.86      0.67      0.75        27
    George W Bush       0.80      0.96      0.87       133
Gerhard Schroeder       0.86      0.58      0.69        31
      Hugo Chavez       1.00      0.56      0.72        16
       Tony Blair       0.81      0.67      0.73        33


      avg / total       0.83      0.82      0.81       322


[[ 10   4   0   3   0   0   0]
 [  0  59   1   5   0   0   0]
 [  1   1  18   7   0   0   0]
 [  0   3   0 128   2   0   0]
 [  0   0   1   8  18   0   4]
 [  0   3   0   3   0   9   1]

 [  0   2   1   7   1   0  22]]

結果:

相關推薦

5.4支援向量SVM演算法應用

利用SVM進行人臉識別例項: # !/usr/bin/env python # -*- coding: utf-8 -*- # Author: YaHuYang #在python2.x版本中要使用Python3.x的特性,可以使用__future__模組匯入相應的介面

4.支援向量SVM演算法(

1.SVM演算法的特點  1.1 訓練好的模型的演算法複雜度是由支援向量的個數決定的,而不是由資料的維度決定的。 所有SVM不太容易產生overfitting 1.2 SVM訓練出來的模型完全依賴於支援向量(Support Vectors),即使訓練集裡面所有非支援向量的點都

支援向量SVM演算法庫(scikit-learn)

1. SVM核函式概述     在scikit-learn中,內建的核函式一共有4種,當然如果你認為線性核函式不算核函式的話,那就只有三種。     1)線性核函式(Linear Kernel)表示式為:K(x,z)=x∙zK(x,z)=x∙z,就是普通的內積,LinearSVC 和 Linea

支援向量數學證明與推導SVM

支援向量機(SVM) @(資料探勘)[svm] 一、線性可分支援向量機和硬間隔最大化 名詞解釋 線性可分:就是指給定一組資料集T={(x1,y1),(x2,y2),⋯,(x

SVM支援向量-SKlearn實現與繪圖8

瞭解了SVM的基本形式與演算法實現,接下來用SKlearn實現支援向量機分類器.1.函式定義與引數含義先看一下SVM函式的完全形式和各引數含義:SVC(C=1.0, kernel=’rbf’, degree=3, gamma=’auto’, coef0=0.0, shrink

特徵選擇之支援向量遞迴特徵消除SVM-RFE

支援向量機遞迴特徵消除(下文簡稱SVM-RFE)是由Guyon等人在對癌症分類時提出來的,最初只能對兩類資料進行特徵提取。它是一種基於Embedded方法。 支援向量機 支援向量機廣泛用於模式識別,機器學習等領域,SVM採用結構風險最小化原則,同時最小化

支援向量—SMO論文詳解序列最小最優化演算法

SVM的學習演算法可以歸結為凸二次規劃問題。這樣的凸二次規劃問題具有全域性最優解,並且許多最優化演算法可以用來求解,但是當訓練樣本容量很大時,這些演算法往往變得非常低效,以致無法使用。論文《Sequential Minimal Optimization:A Fast Algori

支援向量SVM

  SVM 是一種監督式的機器學習演算法,可用於分類或迴歸問題。它使用一種稱為核函式的技術來變換資料,然後基於這種變換,演算法找到預測可能的兩種分類之間的最佳邊界。通俗來講,它是一種二類分類模型,其基本模型定義為特徵空間上的間隔最大的線性分類器,即支援向量機的學習策略便是間隔最大化,最終

機器學習---演算法---支援向量---線性SVM--第一部分

轉自:https://cuijiahua.com/blog/2017/11/ml_8_svm_1.html 什麼是SVM? SVM的英文全稱是Support Vector Machines,我們叫它支援向量機。支援向量機是我們用於分類的一種演算法。讓我們以一個小故事的形式,開啟我們的SVM之旅吧。 在很

機器學習4-支援向量

目錄 支援向量機(SVM) 原理 引數 不同核函式的分類效果 線性核函式:linear 多項式核函式:poly 徑向基核函式:rbf 樣本類別均衡化 置信概率 網格

人工智障學習筆記——機器學習(4)支援向量

一.概念 支援向量機(Support Vector Machine),簡稱SVM。是常見的一種判別方法。在機器學習領域,是一個有監督的學習模型,通常用來進行模式識別、分類以及迴歸分析。 SVM的主要思想可以概括為兩點: 1.它是針對線性可分情況進行分析,對於線性不可分的情況

Python 資料科學手冊 5.7 支援向量

5.7 支援向量機 支援向量機(SVM)是一種特別強大且靈活的監督演算法,用於分類和迴歸。 在本節中,我們將探索支援向量機背後的直覺,及其在分類問題中的應用。 我們以標準匯入開始: %matplotlib inline import numpy as

二分類支援向量模型SVM知識點詳解

1 引言 在本篇部落格中,你將會了解到支援向量機分類器名字的由來、它的基本假設、支援向量機針對線性可分、廣義線性、非線性情況下的解決方法以及一些具體的推導過程,支援向量機常見問題的解答。在本篇部落格的第二部分會給一幅支援向量機整個過程的流程圖,從圖中你可以清晰

支援向量從原理到演算法的實現

思想:尋找能夠成功分開兩類樣本並且具有最大分類間隔的最優超平面。 1.原理解析 空間中任何一個平面的方程都可以表示為wx+b =0,如上圖,設最優超平面方程H為wx+b=0,支援向量x-到H的距離為,要使分類間隔最大,即該距離最大,而該距離只與|w|有關,分子為一個常數,為了簡

支援向量與SMO優化演算法

1 演算法概述 1.1 工作原理 類似於感知機,用一個分離超平面將正負類分開,不同之處在於,感知機只是要求分開正負類,而支援向量機要求找出分離間隔最大的超平面。 1.2 三要素 模型:超平面分類決策模

決策樹、貝葉斯、人工神經網路、K-近鄰、支援向量等常用分類演算法小結

單一的分類演算法:決策樹、貝葉斯、人工神經網路、K-近鄰、支援向量機和基於關聯規則的分類,HMM 組合分類演算法:Bagging和Boosting k-近鄰(kNN,k-Nearest Neighbors)演算法 找出與未知樣本x距離最近的k個訓練樣本,看這k個樣本中

機器學習實戰【5SVM-支援向量

本部落格記錄《機器學習實戰》(MachineLearningInAction)的學習過程,包括演算法介紹和python實現。 SVM(支援向量機) SVM是一種分類演算法,通過對訓練集資料的分析找到最好的分隔平面,然後用該平面對新資料進行分類。本

SVM支援向量-《機器學習實戰》SMO演算法Python實現5

經過前幾篇文章的學習,SVM的優化目標,SMO演算法的基本實現步驟,模型對應引數的選擇,我們已經都有了一定的理解,結合《機器學習實戰》,動手實踐一個基本的SVM支援向量機,來完成一個簡單的二分類任務。建立模型之前,首先看一下我們的資料,然後再用支援向量機實現分類:     

機器學習實戰支援向量SVMSupport Vector Machine

目錄 0. 前言 1. 尋找最大間隔 2. 拉格朗日乘子法和KKT條件 3. 鬆弛變數 4. 帶鬆弛變數的拉格朗日乘子法和KKT條件 5. 序列最小優化SMO(Sequential Minimal Optimiz

吳恩達機器學習第十三章---支援向量SVM

一、優化目標 邏輯迴歸中的代價函式:  畫出兩種情況下的函式影象可得: y=1: 我們找一條折線來近似表示這個函式影象 y=0:    我們用這兩條折線來近似表示原來的曲線函式可得新的代價函式(假設-log(h(x))為,-log(1