当前位置 > CPDA数据分析师 > “数”业专攻 > 为什么使用SVM(Support Vector Machine)?

为什么使用SVM(Support Vector Machine)?

来源:数据分析师 CPDA | 时间:2018-01-23 | 作者:admin

支持向量机(SVM, Support Vector Machine)近年来成为了机器学习中(machine learning)一个非常热门的算法。本文中,我将向大家详细举例说明什么是支持向量机,以及怎么在Python Scikits库中使用支持向量机。

 

什么是支持向量机?

 

在机器学习中,支持向量机(英语:Support Vector Machine,常简称为SVM,又名支持向量网络)是在分类与回归分析中分析数据的监督式学习模型与相关的学习算法。简单来说,SVM可以将最复杂的数据进行转化,然后根据我们定义的标签或输出结果来有效进行分类。

 

为什么支持向量机这么重要?

 

SVM在分类(classification)和回归分析(regression)中能起到巨大的作用。本文中我将着重分析两种SVM在分类中的应用:第一种,非线性SVM;第二种,SVM使用核技巧实现非线性分类。第一种,非线性SVM顾名思义,即在SVM中拟合的线不必是一根直线。这种分类方法的好处是我们可以直接精确找到数据之间的复杂关系,而不必先将它们进行转化。然而,缺点则在于庞大的计算量会使得计算时间变得更长。

 

牛和狼的问题

 

什么是核映射?

 

核映射,就是应用于最优超平面来创建非线性分类器的方法。核映射会将数据进行转换,自动保留一些数据集中可以用作潜在分类器的特征向量,并且自动去除一些无关的向量数据。这个过程有点类似于DNA解链,从数据中一些无关的向量开始,通过核映射作用后,这些数据会重新“排列组合”,变成一个更庞大复杂的的数据集。虽然看似复杂,但是这就是核映射的微妙之处:它将数据集拆散后扩大,所以有更多的空间可以使SVM找到样本类别间的最优超平面(optimal hyperplane)。

 

让我用一个生动的例子来帮助你理解。想象我们现在是一个农夫,然后我们需要造一个围墙来保护我们的牛,防止狼群的入侵。但是,这个围墙怎么造?要造在哪里呢?如果你是一个看重数据应用的农夫,你可能会根据牛群和狼群在草原上不同的位置分布,构建一个个分类器。在不同的分类器当中,我们认为SVM可以很好地帮助农夫区分牛群和狼群。下图详细说明了非线性模型SVM在此类问题中的好处,你可以对比看到逻辑模型和决策树模型都使用了直线来区分牛群和狼群。

 

为什么使用SVM? CPDA数据分析师

 

动手尝试一下上图的分类方法?

 

你可以根据自己的喜好在终端或者IDE中运行这个代码。但我今天想推荐“Rodeo”,一个超棒的弹出式画图应用,非常适合此类模型分析方法(注:Rodeo默认存在于Windows系统操作下)。等你下载好Rodeo,之后,你需要从我的github下载cows_and_wolves.txt文件(请确认存储路径便于之后在Python中打开)。

 

为什么使用SVM? CPDA数据分析师

 

好了,现在你只需要复制+黏贴下面这段代码到Rodeo中并且运行即可。别忘了这是一个弹出式窗口,所以你随时可以移动、缩放这个窗口。

 

# Data driven farmer goes to the Rodeo

 

import numpy as np

import pylab as pl

from sklearn import svm

from sklearn import linear_model

from sklearn import tree

import pandas as pd

 

def plot_results_with_hyperplane(clf, clf_name, df, plt_nmbr):

x_min, x_max = df.x.min() - .5, df.x.max() + .5

y_min, y_max = df.y.min() - .5, df.y.max() + .5

 

# step between points. i.e. [0, 0.02, 0.04, ...]

step = .02

# to plot the boundary, we're going to create a matrix of every possible point

# then label each point as a wolf or cow using our classifier

xx, yy = np.meshgrid(np.arange(x_min, x_max, step), np.arange(y_min, y_max, step))

Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

# this gets our predictions back into a matrix

Z = Z.reshape(xx.shape)

 

# create a subplot (we're going to have more than 1 plot on a given image)

pl.subplot(2, 2, plt_nmbr)

# plot the boundaries

pl.pcolormesh(xx, yy, Z, cmap=pl.cm.Paired)

 

# plot the wolves and cows

for animal in df.animal.unique():

pl.scatter(df[df.animal==animal].x,

df[df.animal==animal].y,

marker=animal,

label="cows" if animal=="x" else "wolves",

color='black')

pl.title(clf_name)

pl.legend(loc="best")

 

data = open("cows_and_wolves.txt").read()

data = [row.split('\t') for row in data.strip().split('\n')]

 

animals = []

for y, row in enumerate(data):

for x, item in enumerate(row):

# x's are cows, o's are wolves

if item in ['o', 'x']:

animals.append([x, y, item])

 

df = pd.DataFrame(animals, columns=["x", "y", "animal"])

df['animal_type'] = df.animal.apply(lambda x: 0 if x=="x" else 1)

 

# train using the x and y position coordiantes

train_cols = ["x", "y"]

 

clfs = {

"SVM": svm.SVC(),

"Logistic" : linear_model.LogisticRegression(),

"Decision Tree": tree.DecisionTreeClassifier(),

}

 

plt_nmbr = 1

for clf_name, clf in clfs.iteritems():

clf.fit(df[train_cols], df.animal_type)

plot_results_with_hyperplane(clf, clf_name, df, plt_nmbr)

plt_nmbr += 1

pl.show()

 

让SVM帮你解决难题

 

在刚才那个例子中,如果因变量和自变量之间的关系是非线性的,那么SVM可以说是此类问题中最精确的模型了。算法中将变量log(x)和x^2进行转换也将不再那么重要。如果你仍然对此有疑问,试着看看下面的例子:

 

假设我们现在有一个包含许多红色点和绿色点的数据集。当我们用这些点的坐标画图时,这些点恰好构成了一个描边和外围为绿色,中间为红色的圆(有点像粗糙版的孟加拉国国旗)。

 

此时,如果我们缺少了1/3的数据,那么将会发生什么呢?如果我们没有能力百分百复原这部分缺失的数据,但我们想找到一种近似的方法去还原这1/3的数据,那我们能怎么做呢?

 

其中一个方法便是:用我们现有的2/3的数据作为训练集来建立一个模型。但是,我们怎么去找到合适的模型呢?试着用用以下三种:

 

线性回归(逻辑)模型

 

决策树模型

 

SVM模型

 

于是我分别套用了上述三种模型,并且得到三个对缺失部分数据的预测,让我们一起来看一下图:

 

为什么使用SVM? CPDA数据分析师

 

这里是分别使用这三种模型的代码:

 

import numpy as np

import pylab as pl

import pandas as pd

 

from sklearn import svm

from sklearn import linear_model

from sklearn import tree

 

from sklearn.metrics import confusion_matrix

 

x_min, x_max = 0, 15

y_min, y_max = 0, 10

step = .1

 

# to plot the boundary, we're going to create a matrix of every possible point

# then label each point as a wolf or cow using our classifier

xx, yy = np.meshgrid(np.arange(x_min, x_max, step), np.arange(y_min, y_max, step))

 

df = pd.DataFrame(data={'x': xx.ravel(), 'y': yy.ravel()})

 

df['color_gauge'] = (df.x-7.5)**2 + (df.y-5)**2

df['color'] = df.color_gauge.apply(lambda x: "red" if x <= 15 else "green")

df['color_as_int'] = df.color.apply(lambda x: 0 if x=="red" else 1)

 

print "Points on flag:"

print df.groupby('color').size()

print

 

figure = 1

 

# plot a figure for the entire dataset

for color in df.color.unique():

idx = df.color==color

pl.subplot(2, 2, figure)

pl.scatter(df[idx].x, df[idx].y, color=color)

pl.title('Actual')

 

train_idx = df.x < 10

 

train = df[train_idx]

test = df[-train_idx]

 

print "Training Set Size: %d" % len(train)

print "Test Set Size: %d" % len(test)

 

# train using the x and y position coordiantes

cols = ["x", "y"]

 

clfs = {

"SVM": svm.SVC(degree=0.5),

"Logistic" : linear_model.LogisticRegression(),

 

"Decision Tree": tree.DecisionTreeClassifier()

}

 

# racehorse different classifiers and plot the results

for clf_name, clf in clfs.iteritems():

figure += 1

 

# train the classifier

clf.fit(train[cols], train.color_as_int)

 

# get the predicted values from the test set

test['predicted_color_as_int'] = clf.predict(test[cols])

test['pred_color'] = test.predicted_color_as_int.apply(lambda x: "red" if x==0 else "green")

 

# create a new subplot on the plot

pl.subplot(2, 2, figure)

# plot each predicted color

for color in test.pred_color.unique():

# plot only rows where pred_color is equal to color

idx = test.pred_color==color

pl.scatter(test[idx].x, test[idx].y, color=color)

 

# plot the training set as well

for color in train.color.unique():

idx = train.color==color

pl.scatter(train[idx].x, train[idx].y, color=color)

 

# add a dotted line to show the boundary between the training and test set

# (everything to the right of the line is in the test set)

#this plots a vertical line

train_line_y = np.linspace(y_min, y_max) #evenly spaced array from 0 to 10

train_line_x = np.repeat(10, len(train_line_y)) #repeat 10 (threshold for traininset) n times

# add a black, dotted line to the subplot

pl.plot(train_line_x, train_line_y, 'k--', color="black")

 

pl.title(clf_name)

 

print "Confusion Matrix for %s:" % clf_name

print confusion_matrix(test.color, test.pred_color)

pl.show()

 

为什么使用SVM?结论

 

从最终得到的图中我们很明显可以看出SVM拥有最高的预测能力,为什么?如果你观察一下线性回归模型和决策树模型得到的图,你会发现什么?是的,答案显而易见:呈直线状的边界。然而,我们输入的模型中却没有包括任何变换来解释x 、y和颜色之间的非线性关系。如果特地变换数据,我们肯定能从线性回归模型和决策树模型得到更好的预测结果。但是为什么要浪费时间去转换数据呢?SVM已经为我们得到了98%的预测准确率(错误值仅有117/5000),线性回归和决策树的准确率只有相应的12%和51%。

 

但是你可能会问,SVM模型既然准确率这么高,为什么我们不在所有的问题中都应用它呢?不巧的是,在SVM精准的计算率背后,它产生的边界也比较难以理解,我们常常称之为“黑匣子”。而线性模型和决策树则恰恰相反,一目了然容易理解。