5.3 SVM分类

文章目录

1.鸢尾花SVM分类

鸢尾花数据集——提取码:1234

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


# 鸢尾花SVM-二特征分类
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
# sklearn中svm
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 'sepal length', 'sepal width', 'petal length', 'petal width'
iris_feature = u'花萼长度', u'花萼宽度', u'花瓣长度', u'花瓣宽度'

if __name__ == "__main__":
    path = 'iris.data'  # 数据文件路径
    data = pd.read_csv(path, header=None)
    # 特征值与目标值
    x, y = data.iloc[:, range(4)], data.iloc[:, 4]
    # 将字符串数据y转换成categorical类别数据,并映射成0,1,2
    y = pd.Categorical(y).codes
    # u'花萼长度', u'花萼宽度'
    x = x.iloc[:, :2]
    # 数据集的分割
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6)

    # 分类器
    # decision_function_shape='ovr'表示用若干个二分类转换成三分类
    clf = svm.SVC(C=0.1, kernel='linear', decision_function_shape='ovr')
    # clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr')
    clf.fit(x_train, y_train.ravel())

    # 准确率
    print(clf.score(x_train, y_train))  # 精度
    print('训练集准确率:', accuracy_score(y_train, clf.predict(x_train)))
    print(clf.score(x_test, y_test))
    print('测试集准确率:', accuracy_score(y_test, clf.predict(x_test)))

    # decision_function
    # 到分类器的距离,三个值哪一个大就属于哪一个类别,decision_function与predict一一对应
    print('decision_function:\n', clf.decision_function(x_train))
    print('\npredict:\n', clf.predict(x_train))

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

    # print Z
    grid_hat = clf.predict(grid_test)  # 预测分类值
    grid_hat = grid_hat.reshape(x1.shape)  # 使之与输入的形状相同
    mpl.rcParams['font.sans-serif'] = [u'SimHei']
    mpl.rcParams['axes.unicode_minus'] = False

    cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
    cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
    plt.figure(facecolor='w')
    plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light)
    plt.scatter(x[0], x[1], c=y, edgecolors='k', s=50, cmap=cm_dark)  # 样本
    plt.scatter(x_test[0], x_test[1], s=120, facecolors='none', zorder=10)  # 圈中测试集样本
    plt.xlabel(iris_feature[0], fontsize=13)
    plt.ylabel(iris_feature[1], fontsize=13)
    plt.xlim(x1_min, x1_max)
    plt.ylim(x2_min, x2_max)
    plt.title(u'鸢尾花SVM二特征分类', fontsize=16)
    plt.grid(b=True, ls=':')
    plt.tight_layout(pad=1.5)
    plt.show()

5.3 SVM分类

2.SVM多分类

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


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)]
    # 方差
    # numpy.eye返回一个二维数组,对角线上为1,其他地方为0
    # np.diag提取对角线或构造一个对角线数组。
    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)
        # 模型中随机采样20个
        x[i * N:(i + 1) * N, :] = mn.rvs(N)
    # reshape((-1, 1)将行变成列
    a = np.array((0, 1, 2, 3)).reshape((-1, 1))
    # 将a复制N份,并且迭代返回结果
    y = np.tile(a, N).flatten()
    print('x=\n', x)
    print('y=\n', y)

    # 分类器
    # decision_function_shape='ovo'表示一对一做一个分类器
    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
    # decision_function_shape='ovo'表示一对一做一个分类器,任取两个有6个分类器
    print('decision_function = \n', 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()

5.3 SVM分类

3.SVM不同参数的分类-不同的分类器(调参)

数据链接

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

# 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()
    print ('正确率:%.2f%%' % (100*float(acc.sum()) / a.size))


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()

5.3 SVM分类

4.不平衡数据处理

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

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))
        print()


        # 画图
        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()

5.3 SVM分类

5.手写数字识别

链接—提取码:1234

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

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


def show_accuracy(a, b, tip):
    acc = a.ravel() == b.ravel()
    print(tip + '正确率:%.2f%%' % (100 * np.mean(acc)))


def save_image(im, i):
    im *= 15.9375
    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))


if __name__ == "__main__":
    print('Load Training File Start...')
    data = np.loadtxt('optdigits.tra', dtype=np.float, delimiter=',')
    x, y = np.split(data, (-1,), axis=1)
    images = x.reshape(-1, 8, 8)
    y = y.ravel().astype(np.int)

    print('Load Test Data Start...')
    data = np.loadtxt('optdigits.tes', dtype=np.float, delimiter=',')
    x_test, y_test = np.split(data, (-1,), axis=1)
    print(y_test.shape)
    images_test = x_test.reshape(-1, 8, 8)
    y_test = y_test.ravel().astype(np.int)
    print('Load Data OK...')

    # x, x_test, y, y_test = train_test_split(x, y, test_size=0.4, random_state=1)
    # images = x.reshape(-1, 8, 8)
    # images_test = x_test.reshape(-1, 8, 8)

    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[: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'测试图片: %i' % y_test[index])
    plt.tight_layout()
    plt.show()

    # params = {'C':np.logspace(0, 3, 7), 'gamma':np.logspace(-5, 0, 11)}
    # model = GridSearchCV(svm.SVC(kernel='rbf'), param_grid=params, cv=3)
    model = svm.SVC(C=10, kernel='rbf', gamma=0.001)
    print('Start Learning...')
    t0 = time()
    model.fit(x, y)
    t1 = time()
    t = t1 - t0
    print('训练+CV耗时:%d分钟%.3f秒' % (int(t / 60), t - 60 * int(t / 60)))
    # print '最优参数:\t', model.best_params_
    # clf.fit(x, y)
    print('Learning is OK...')
    print('训练集准确率:', accuracy_score(y, model.predict(x)))
    y_hat = model.predict(x_test)
    print('测试集准确率:', accuracy_score(y_test, model.predict(x_test)))
    print(y_hat)
    print(y_test)

    err_images = images_test[y_test != y_hat]
    err_y_hat = y_hat[y_test != y_hat]
    err_y = y_test[y_test != y_hat]
    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.tight_layout()
    plt.show()

Load Training File Start...
Load Test Data Start...
(1797, 1)
Load Data OK...
Start Learning...
训练+CV耗时:0分钟0.308秒
Learning is OK...
训练集准确率: 1.0
测试集准确率: 0.9827490261547023
[0 1 2 ... 8 9 8]
[0 1 2 ... 8 9 8]
[9 1 1 1 1 9 5 9 9 9 9 9 9 8 1 0 1 3 8 9 9 3 5 9 1 7 3 5 8 5 1]
[5 2 2 2 8 7 7 5 7 7 7 7 7 1 8 6 8 9 9 3 8 8 8 7 8 3 9 9 3 3 8]

5.3 SVM分类
5.3 SVM分类

6.MINIST手写数字图片识别

链接—提取码:1234

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

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


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__":
    # 消除警告
    warnings.filterwarnings(action='ignore')
    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_ =',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))


    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()

载入训练数据...
载入完成,耗时1.746520秒
图片个数:42000,图片像素数目:784
载入测试数据...
载入完成,耗时1.179636秒
(33600, 784) (8400, 784)
随机森林开始训练...
随机森林训练结束,耗时0分钟18.557秒
OOB准确率:95.821%
随机森林训练集准确率:100.000%,预测耗时:1秒
随机森林测试集准确率:96.512%,预测耗时:0秒
[2 6 0 7 8 7 0 7 5 0 2 2 9 3 9 8 2 8 7 0 4 9 3 9 2 8 9 7 4 4 1 5 8 7 5 3 2
 4 0 1 8 7 3 2 6 5 8 4 9 2 7 8 5 2 4 9 9 6 8 2 5 3 9 2 5 1 4 6 2 8 8 0 8 2
 2 1 9 8 4 9 3 3 2 8 7 6 8 9 7 3 5 3 1 2 3 9 9 3 9 8 4 4 7 8 3 3 7 3 4 4 0
 9 9 1 7 4 9 5 2 8 8 3 5 5 8 5 1 3 6 2 7 7 3 6 4 3 4 5 0 7 4 9 5 1 4 3 3 5
 8 7 9 2 0 8 3 3 2 6 5 9 9 9 8 1 3 7 1 5 5 3 4 1 2 9 5 2 8 3 1 4 4 3 2 8 3
 4 4 3 9 2 5 7 1 7 6 8 0 5 9 5 6 5 0 8 8 7 0 6 4 8 7 9 4 3 2 4 4 2 8 6 3 1
 9 2 9 6 2 8 9 5 8 4 4 0 0 2 2 6 9 7 9 4 5 0 6 2 3 6 5 9 9 9 2 5 2 9 9 8 8
 5 4 2 3 9 3 7 9 0 5 0 9 5 3 2 4 3 9 8 8 3 9 5 2 7 9 2 8 5 8 5 4 5 8]
[4 5 6 4 2 2 5 2 9 7 7 3 7 9 4 3 7 5 3 5 6 4 5 3 7 2 4 4 6 8 4 8 9 8 3 5 3
 0 5 8 2 3 8 9 0 6 9 8 5 3 3 2 9 1 9 8 5 5 3 7 3 5 4 3 6 8 2 4 3 1 3 3 5 3
 4 8 8 2 7 4 9 5 4 9 3 2 3 8 2 8 3 5 8 3 9 7 3 2 7 9 2 8 9 4 9 1 0 9 6 9 9
 4 4 7 9 9 4 8 7 3 5 5 9 3 6 9 8 5 4 7 5 3 5 5 9 9 9 3 2 5 8 4 6 8 9 5 9 0
 3 3 2 7 8 4 9 5 1 4 6 3 4 8 9 5 1 9 7 8 3 1 9 8 3 7 3 7 3 8 3 9 9 1 3 3 2
 9 7 5 7 0 3 2 9 9 8 6 6 8 4 3 4 3 9 2 0 9 5 5 7 9 2 3 9 9 1 9 7 1 9 8 9 8
 4 7 7 0 1 7 7 3 9 3 9 4 9 3 3 2 4 9 4 8 1 5 5 3 8 4 1 7 7 7 3 8 3 7 5 3 0
 3 7 7 2 7 8 4 4 2 9 3 4 8 1 8 9 5 7 5 3 1 7 8 3 9 8 3 2 6 5 6 8 8 3]

5.3 SVM分类

载入训练数据...
载入完成,耗时1.661703秒
图片个数:42000,图片像素数目:784
载入测试数据...
载入完成,耗时1.106137秒
(33600, 784) (8400, 784)
SVM开始训练...
SVM训练结束,耗时2分钟21.074秒
SVM训练集准确率:94.676%,耗时4分钟13.307秒
SVM测试集准确率:93.810%,耗时1分钟3.327秒
上一篇:统计学习(一):导论


下一篇:Java on Visual Studio Code的更新 – 2021年3月