机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)

摘要:
轴=1)x=x[:decision_function_shape='vr')clf=svr.SVC(C=0.8,decision\ufunction_sshape='vr')clf.fit(x_train,'训练集')打印(clf分数(x_test,x2=np.mgrid[x1_min:

1.主要内容

机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)第1张

2.SVM的应用

(1)利用SVM处理分类问题

机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)第2张

机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)第3张

机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)第4张

分类器的性能的评价指标:

机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)第5张

应用案例:

机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)第6张

accuracy=3/6=0.5

precision=3/5=0.6

recall=3/4=0.75

3.代码示例

(1)鸢尾花SVM案例

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

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

def iris_type(s):
    it = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2}
    return it[s]


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


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


if __name__ == "__main__":
    path = '8.iris.data'  # 数据文件路径
    data = np.loadtxt(path, dtype=float, delimiter=',', converters={4: iris_type})
    x, y = np.split(data, (4,), axis=1)
    x = x[:, :2]
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6)

    # 分类器
    # 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))  # 精度
    y_hat = clf.predict(x_train)
    show_accuracy(y_hat, y_train, '训练集')
    print(clf.score(x_test, y_test))
    y_hat = clf.predict(x_test)
    show_accuracy(y_hat, y_test, '测试集')

    # 画图
    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)  # 测试点

    Z = clf.decision_function(grid_test)    # 样本到决策面的距离
    print(Z)
    grid_hat = clf.predict(grid_test)       # 预测分类值
    print(grid_hat)
    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'])
    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)  # 测试点
    plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light)

    plt.scatter(x[:, 0], x[:, 1], c=np.squeeze(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=15)
    plt.grid()
    plt.show()

效果图:

机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)第7张

(2)

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

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('14.bipartition.txt', dtype=np.float, delimiter='	')
    x, y = np.split(data, (2, ), axis=1)
    y[y == 0] = -1
    y = y.ravel()

    # 分类器
    clfs = [svm.SVC(C=0.3, kernel='linear'),
           svm.SVC(C=10, kernel='linear'),
           svm.SVC(C=5, kernel='rbf', gamma=1),
           svm.SVC(C=5, kernel='rbf', gamma=4)]
    titles = 'Linear,C=0.3', 'Linear, C=10', 'RBF, gamma=1', 'RBF, gamma=4'

    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)  # 准确率

        # 画图
        print('支撑向量的数目:', clf.n_support_)
        print('支撑向量的系数:', clf.dual_coef_)
        print('支撑向量:', clf.support_)
        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=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)
        z = z.reshape(x1.shape)
        plt.contour(x1, x2, z, colors=list('krk'), linestyles=['--', '-', '--'], linewidths=[1, 2, 1], levels=[-1, 0, 1])
        plt.xlim(x1_min, x1_max)
        plt.ylim(x2_min, x2_max)
        plt.title(titles[i])
        plt.grid()
    plt.suptitle(u'SVM不同参数的分类', fontsize=18)
    plt.tight_layout(2)
    plt.subplots_adjust(top=0.92)
    plt.show()

效果图:

机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)第8张

免责声明:文章转载自《机器学习笔记14-----SVM实践和分类器的性能的评价指标(了解python画图的技巧)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇C#数据导出Excel详细介绍ISCSI共享存储下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

使用jest进行单元测试

以前,写完一段代码我也是直接调用或者实例化一下,发现过了就把测试相关部分删了。今年的不幸与坎坷使我有很长一段时间去思考人生,不想将就了,鲁棒健壮的程序,开发和测试应该是分得很开的,于是我选择jest去做单元测试这件事。 为什么要做单元测试 在开始之前,我们先思考这样一个问题,我们为什么要做单元测试? 不扯犊子直接说吧,第一点,用数据、用茫茫多的测试用例去告...

iOS宏定义的使用与规范

宏定义在很多方面都会使用,例如定义高度、判断iOS系统、工具类,还有诸如文件路径、服务端api接口文档。为了对宏能够快速定位和了解其功能,我们最好在定义的时候将其放入特定的头文件中 定义尺寸类的宏 DimensMacros.h //状态栏高度 #define STATUS_BAR_HEIGHT 20 //NavBar高度 #define NA...

Vue之日历控件vue-full-calendar的使用

(1).安装依赖 npm install vue-full-calendar  npm install moment 因为这是日历插件用到了时间工具类 === moment  (2).文件中导入依赖 在想要用此插件的文件中导入依赖 import { FullCalendar } from 'vue-full-calendar' import "f...

Android -- TypedArray

当我们自定义View的时候,在给View赋值一些长度宽度的时候,一般都是在layout布局文件中进行的。,比如android:layout_height="wrap_content",除此之外,我们也可以自己定义属性,这样在使用的时候我们就可以使用形如 myapp:myTextSize="20sp"的方式了。 values/attrs.xml 首先要创建变...

js中的同步与异步

同步:提交后等待服务器的响应,接收服务器返回的数据后再执行下面的代码    异步:与上面相反,提交后继续执行下面的代码,而在后台继续监听,服务器响应后有程序做相应处理,异步的操作好处是不必等待服务器而可以继续在客户端做其它事情。 可以简单的理解认为同步是单线程的异步是多线程的           在使用异步请求时,有时需要将异步请求的结果返回给另一个js函...

Python3 连接各类数据库

Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口。它定义了一系列必须的对象和数据库存取方式, 以便为各种各样的底层数据库系统和多种多样的数据库接口程序提供一致的访问接口 。Python 数据库接口支持非常多的数据库,MySQL 、 PostgreSQL、Microsoft SQL Se...