SVM实践

1. SVM多分类案例

SVM从原理而言只能做二分类任务。但是如果我们同时使用多个SVM去对数据进行拟合,就可以实现多分类的任务了。在sklearn包中,我们可以选择两种方式( decision_function_shape参数)去实现多分类任务,第一种是“ovo”,即一对一模式,如我们要将数据分为四类,便需要建立六个分类器(1vs2,1vs3,1vs4,2vs3,2vs4,3vs4)。第二种是“ovr”模型,即一对其他模型,如我们要将数据分为四类,便需要建立四个分类器(1 vs others,2 vs others,3 vs others,4 vs others)。这下面的案例中,我们生成了三组多元正态随机数,来进行三分类训练。

import numpy as np
from sklearn import svm
from scipy import stats
from sklearn.metrics import accuracy_score
import matplotlib as mpl
import matplotlib.pyplot as plt


def extend(a, b, r):
    x = a - b
    m = (a + b) / 2
    return m-r*x/2, m+r*x/2


if __name__ == "__main__":
    np.random.seed(0)
    N = 20
    x = np.empty((4*N, 2))
    means = [(-1, 1), (1, 1), (1, -1), (-1, -1)]
    sigmas = [np.eye(2), 2*np.eye(2), np.diag((1,2)), np.array(((2,1),(1,2)))]
    for i in range(4):
        mn = stats.multivariate_normal(means[i], sigmas[i]*0.3)
        x[i*N:(i+1)*N, :] = mn.rvs(N)
    a = np.array((0,1,2,3)).reshape((-1, 1))
    y = np.tile(a, N).flatten()
    clf = svm.SVC(C=1, kernel='rbf', gamma=1, decision_function_shape='ovo')
    # clf = svm.SVC(C=1, kernel='linear', decision_function_shape='ovr')
    clf.fit(x, y)
    y_hat = clf.predict(x)
    acc = accuracy_score(y, y_hat)
    np.set_printoptions(suppress=True)
    print (u'预测正确的样本个数:%d,正确率:%.2f%%' % (round(acc*4*N), 100*acc))
    # decision_function
    print (clf.decision_function(x))
    print (y_hat)

    x1_min, x2_min = np.min(x, axis=0)
    x1_max, x2_max = np.max(x, axis=0)
    x1_min, x1_max = extend(x1_min, x1_max, 1.05)
    x2_min, x2_max = extend(x2_min, x2_max, 1.05)
    x1, x2 = np.mgrid[x1_min:x1_max:500j, x2_min:x2_max:500j]
    x_test = np.stack((x1.flat, x2.flat), axis=1)
    y_test = clf.predict(x_test)
    y_test = y_test.reshape(x1.shape)
    cm_light = mpl.colors.ListedColormap(['#FF8080', '#A0FFA0', '#6060FF', '#F080F0'])
    cm_dark = mpl.colors.ListedColormap(['r', 'g', 'b', 'm'])
    mpl.rcParams['font.sans-serif'] = [u'SimHei']
    mpl.rcParams['axes.unicode_minus'] = False
    plt.figure(facecolor='w')
    plt.pcolormesh(x1, x2, y_test, cmap=cm_light)
    plt.scatter(x[:, 0], x[:, 1], s=40, c=y, cmap=cm_dark, alpha=0.7)
    plt.xlim((x1_min, x1_max))
    plt.ylim((x2_min, x2_max))
    plt.grid(b=True)
    plt.tight_layout(pad=2.5)
    plt.title(u'SVM多分类方法:One/One or One/Other', fontsize=18)
    plt.show()

最终结果如下:
在这里插入图片描述

2. SVM 参数的解读

SVM模型的参数较少。如果选择线性核,那主要需要调的参数便是C,也即惩罚因子,从图中第一行可以看出,C越大分离超平面的两条虚线越接近。而对于高斯核来说,需要调的参数主要有两个,一个是C,一个是 γ \gamma γ,其中 γ \gamma γ是高斯核函数中的系数,与方差有关。从图中可以看出, γ \gamma γ越大,SVM对于训练数据的拟合越充分,但是同时可能会带来过拟合的问题。
在这里插入图片描述
代码如下:

import numpy as np
from sklearn import svm
import matplotlib as mpl
import matplotlib.colors
import matplotlib.pyplot as plt


def show_accuracy(a, b):
    acc = a.ravel() == b.ravel()



if __name__ == "__main__":
    data = np.loadtxt('bipartition.txt', dtype=np.float, delimiter='\t')
    x, y = np.split(data, (2, ), axis=1)
    y = y.ravel()

    # 分类器
    clf_param = (('linear', 0.1), ('linear', 0.5), ('linear', 1), ('linear', 2),
                ('rbf', 1, 0.1), ('rbf', 1, 1), ('rbf', 1, 10), ('rbf', 1, 100),
                ('rbf', 5, 0.1), ('rbf', 5, 1), ('rbf', 5, 10), ('rbf', 5, 100))
    x1_min, x1_max = x[:, 0].min(), x[:, 0].max()  # 第0列的范围
    x2_min, x2_max = x[:, 1].min(), x[:, 1].max()  # 第1列的范围
    x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j]  # 生成网格采样点
    grid_test = np.stack((x1.flat, x2.flat), axis=1)  # 测试点

    cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FFA0A0'])
    cm_dark = mpl.colors.ListedColormap(['g', 'r'])
    mpl.rcParams['font.sans-serif'] = [u'SimHei']
    mpl.rcParams['axes.unicode_minus'] = False
    plt.figure(figsize=(14, 10), facecolor='w')
    for i, param in enumerate(clf_param):
        clf = svm.SVC(C=param[1], kernel=param[0])
        if param[0] == 'rbf':
            clf.gamma = param[2]
            title = u'高斯核,C=%.1f,$\gamma$ =%.1f' % (param[1], param[2])
        else:
            title = u'线性核,C=%.1f' % param[1]

        clf.fit(x, y)
        y_hat = clf.predict(x)
        show_accuracy(y_hat, y)  # 准确率

        # 画图
        print (title)
        print ('支撑向量的数目:', clf.n_support_)
        print ('支撑向量的系数:', clf.dual_coef_)
        print ('支撑向量:', clf.support_)
        plt.subplot(3, 4, i+1)
        grid_hat = clf.predict(grid_test)       # 预测分类值
        grid_hat = grid_hat.reshape(x1.shape)  # 使之与输入的形状相同
        plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light, alpha=0.8)
        plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', s=40, cmap=cm_dark)      # 样本的显示
        plt.scatter(x[clf.support_, 0], x[clf.support_, 1], edgecolors='k', facecolors='none', s=100, marker='o')   # 支撑向量
        z = clf.decision_function(grid_test)
      
        print ('clf.decision_function(x) = ', clf.decision_function(x))
        print ('clf.predict(x) = ', clf.predict(x))
        z = z.reshape(x1.shape)
        plt.contour(x1, x2, z, colors=list('kbrbk'), linestyles=['--', '--', '-', '--', '--'],
                    linewidths=[1, 0.5, 1.5, 0.5, 1], levels=[-1, -0.5, 0, 0.5, 1])
        plt.xlim(x1_min, x1_max)
        plt.ylim(x2_min, x2_max)
        plt.title(title, fontsize=14)
    plt.suptitle(u'SVM不同参数的分类', fontsize=20)
    plt.tight_layout(1.4)
    plt.subplots_adjust(top=0.92)
    plt.savefig('1.png')
    plt.show()

3. SVM不平衡数据的处理

SVM可以通过调节参数进行不平衡数据的处理。在下例中,正样本只有10个,而负样本有990个,我们通过调整class_weight参数,如:class_weight={-1: 1, 1: 10},来拟合不平衡的数据。
在这里插入图片描述
代码如下:

import numpy as np
from sklearn import svm
import matplotlib.colors
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.exceptions import UndefinedMetricWarning
import warnings


if __name__ == "__main__":
    warnings.filterwarnings(action='ignore', category=UndefinedMetricWarning)
    np.random.seed(0)   # 保持每次生成的数据相同

    c1 = 990
    c2 = 10
    N = c1 + c2
    x_c1 = 3*np.random.randn(c1, 2)
    x_c2 = 0.5*np.random.randn(c2, 2) + (4, 4)
    x = np.vstack((x_c1, x_c2))
    y = np.ones(N)
    y[:c1] = -1

    # 显示大小
    s = np.ones(N) * 30
    s[:c1] = 10

    # 分类器
    clfs = [svm.SVC(C=1, kernel='linear'),
           svm.SVC(C=1, kernel='linear', class_weight={-1: 1, 1: 50}),
           svm.SVC(C=0.8, kernel='rbf', gamma=0.5, class_weight={-1: 1, 1: 2}),
           svm.SVC(C=0.8, kernel='rbf', gamma=0.5, class_weight={-1: 1, 1: 10})]
    titles = 'Linear', 'Linear, Weight=50', 'RBF, Weight=2', 'RBF, Weight=10'

    x1_min, x1_max = x[:, 0].min(), x[:, 0].max()  # 第0列的范围
    x2_min, x2_max = x[:, 1].min(), x[:, 1].max()  # 第1列的范围
    x1, x2 = np.mgrid[x1_min:x1_max:500j, x2_min:x2_max:500j]  # 生成网格采样点
    grid_test = np.stack((x1.flat, x2.flat), axis=1)  # 测试点

    cm_light = matplotlib.colors.ListedColormap(['#77E0A0', '#FF8080'])
    cm_dark = matplotlib.colors.ListedColormap(['g', 'r'])
    matplotlib.rcParams['font.sans-serif'] = [u'SimHei']
    matplotlib.rcParams['axes.unicode_minus'] = False
    plt.figure(figsize=(10, 8), facecolor='w')
    for i, clf in enumerate(clfs):
        clf.fit(x, y)

        y_hat = clf.predict(x)
        # show_accuracy(y_hat, y) # 正确率
        # show_recall(y, y_hat)   # 召回率
        print (i+1, '次:')
        print ('accuracy:\t', accuracy_score(y, y_hat))
        print ('precision:\t', precision_score(y, y_hat, pos_label=1))
        print ('recall:\t', recall_score(y, y_hat, pos_label=1))
        print ('F1-score:\t', f1_score(y, y_hat, pos_label=1))



        # 画图
        plt.subplot(2, 2, i+1)
        grid_hat = clf.predict(grid_test)       # 预测分类值
        grid_hat = grid_hat.reshape(x1.shape)  # 使之与输入的形状相同
        plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light, alpha=0.8)
        plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', s=s, cmap=cm_dark)      # 样本的显示
        plt.xlim(x1_min, x1_max)
        plt.ylim(x2_min, x2_max)
        plt.title(titles[i])
        plt.grid()
    plt.suptitle(u'不平衡数据的处理', fontsize=18)
    plt.tight_layout(1.5)
    plt.subplots_adjust(top=0.92)
    plt.show()

4. MNIST手写数据识别

在这一部分,我们通过手写数据来对SVM的分类效果进行测试,对照组选取的是随机森林。MNIST手写数据也是很著名的分类数据。具体形式如下图:
在这里插入图片描述
代码如下:

import numpy as np
from sklearn import svm
import matplotlib.colors
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import accuracy_score
import pandas as pd
import os
import csv
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from time import time



def save_image(im, i):
    im = 255 - im
    a = im.astype(np.uint8)
    output_path = '.\\HandWritten'
    if not os.path.exists(output_path):
        os.mkdir(output_path)
    Image.fromarray(a).save(output_path + ('\\%d.png' % i))


def save_result(model):
    data_test_hat = model.predict(data_test)
    with open('Prediction.csv', 'wb') as f:
        writer = csv.writer(f)
        writer.writerow(['ImageId', 'Label'])
        for i, d in enumerate(data_test_hat):
            writer.writerow([i, d])
        # writer.writerows(zip(np.arange(1, len(data_test_hat) + 1), data_test_hat))


if __name__ == "__main__":
    classifier_type = 'RF'

    print ('载入训练数据...')
    t = time()
    data = pd.read_csv('.\\MNIST.train.csv', header=0, dtype=np.int)
    print ('载入完成,耗时%f秒' % (time() - t))
    y = data['label'].values
    x = data.values[:, 1:]
    print ('图片个数:%d,图片像素数目:%d' % x.shape)
    images = x.reshape(-1, 28, 28)
    y = y.ravel()

    print ('载入测试数据...')
    t = time()
    data_test = pd.read_csv('.\\MNIST.test.csv', header=0, dtype=np.int)
    data_test = data_test.values
    images_test_result = data_test.reshape(-1, 28, 28)
    print ('载入完成,耗时%f秒' % (time() - t))

    np.random.seed(0)
    x, x_test, y, y_test = train_test_split(x, y, train_size=0.8, random_state=1)
    images = x.reshape(-1, 28, 28)
    images_test = x_test.reshape(-1, 28, 28)
    print (x.shape, x_test.shape)

    matplotlib.rcParams['font.sans-serif'] = [u'SimHei']
    matplotlib.rcParams['axes.unicode_minus'] = False
    plt.figure(figsize=(15, 9), facecolor='w')
    for index, image in enumerate(images[:16]):
        plt.subplot(4, 8, index + 1)
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title(u'训练图片: %i' % y[index])
    for index, image in enumerate(images_test_result[:16]):
        plt.subplot(4, 8, index + 17)
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        save_image(image.copy(), index)
        plt.title(u'测试图片')
    plt.tight_layout()
    plt.show()

    # SVM
    if classifier_type == 'SVM':
        # params = {'C':np.logspace(1, 4, 4, base=10), 'gamma':np.logspace(-10, -2, 9, base=10)}
        # clf = svm.SVC(kernel='rbf')
        # model = GridSearchCV(clf, param_grid=params, cv=3)
        model = svm.SVC(C=1000, kernel='rbf', gamma=1e-10)
        print ('SVM开始训练...')
        t = time()
        model.fit(x, y)
        t = time() - t
        print ('SVM训练结束,耗时%d分钟%.3f秒' % (int(t/60), t - 60*int(t/60)))
        # print '最优分类器:', model.best_estimator_
        # print '最优参数:\t', model.best_params_
        # print 'model.cv_results_ ='
        # pprint(model.cv_results_)
        t = time()
        y_hat = model.predict(x)
        t = time() - t
        print ('SVM训练集准确率:%.3f%%,耗时%d分钟%.3f秒' % (accuracy_score(y, y_hat)*100, int(t/60), t - 60*int(t/60)))
        t = time()
        y_test_hat = model.predict(x_test)
        t = time() - t
        print ('SVM测试集准确率:%.3f%%,耗时%d分钟%.3f秒' % (accuracy_score(y_test, y_test_hat)*100, int(t/60), t - 60*int(t/60)))
        save_result(model)
    elif classifier_type == 'RF':
        rfc = RandomForestClassifier(100, criterion='gini', min_samples_split=2,
                                     min_impurity_split=1e-10, bootstrap=True, oob_score=True)
        print ('随机森林开始训练...')
        t = time()
        rfc.fit(x, y)
        t = time() - t
        print ('随机森林训练结束,耗时%d分钟%.3f秒' % (int(t/60), t - 60*int(t/60)))
        print ('OOB准确率:%.3f%%' % (rfc.oob_score_*100))
        t = time()
        y_hat = rfc.predict(x)
        t = time() - t
        print ('随机森林训练集准确率:%.3f%%,预测耗时:%d秒' % (accuracy_score(y, y_hat)*100, t))
        t = time()
        y_test_hat = rfc.predict(x_test)
        t = time() - t
        print ('随机森林测试集准确率:%.3f%%,预测耗时:%d秒' % (accuracy_score(y_test, y_test_hat)*100, t))
        save_result(rfc)

    err = (y_test != y_test_hat)
    err_images = images_test[err]
    err_y_hat = y_test_hat[err]
    err_y = y_test[err]
    print (err_y_hat)
    print (err_y)
    plt.figure(figsize=(10, 8), facecolor='w')
    for index, image in enumerate(err_images):
        if index >= 12:
            break
        plt.subplot(3, 4, index + 1)
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title(u'错分为:%i,真实值:%i' % (err_y_hat[index], err_y[index]))
    plt.suptitle(u'数字图片手写体识别:分类器%s' % classifier_type, fontsize=18)
    plt.tight_layout(rect=(0, 0, 1, 0.95))
    plt.show()
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值