美文网首页
python实现SVM以及画出分类的边界

python实现SVM以及画出分类的边界

作者: ghostdogss | 来源:发表于2019-08-26 15:37 被阅读0次
    from sklearn.datasets import load_iris
    from sklearn.tree import DecisionTreeClassifier
    
    dtree = DecisionTreeClassifier(max_depth = 3)
    iris = load_iris()
    x, y = iris.data, iris.target
    dtree.fit(x, y)
    # 用决策树方法看特征的重要性
    dtree.feature_importances_
    
    # 画数据点和边界
    import numpy as np
    import matplotlib.pyplot as plt
    plt.style.use('ggplot')
    
    def border_of_classifier(sklearn_cl, x, y):
        """
        param sklearn_cl: sklearn的分类器
        param x: np.array
        param y: np.array
        """
        
        # 1.生成网格数据
        x_min, y_min = x.min(axis=0) - 1
        x_max, y_max = x.max(axis=0) + 1
        # 利用一组网格数据求出方程的值, 然后把边界画出来
        # 生成网格点坐标矩阵。
        x_values, y_values = np.meshgrid(np.arange(x_min, x_max, 0.01),
                                        np.arange(y_min, y_max, 0.01))
        # 计算处分类器对所有数据点的分类姐夫哦,生成网格采样
        mesh_output = sklearn_cl.predict(np.c_[x_values.ravel(), y_values.ravel()])
        mesh_output = mesh_output.reshape(x_values.shape)
        fig, ax = plt.subplots(figsize=(16, 10), dpi=80)
        # 根据mesh_output结果自动从cmap中选择颜色
        plt.pcolormesh(x_values, y_values, mesh_output, cmap = 'rainbow')
        plt.scatter(x[:, 0], x[:, 1], c=y, s=100, edgecolors='steelblue', linewidth=1, cmap=plt.cm.Spectral)
        plt.xlim(x_values.min(), x_values.max())
        plt.ylim(y_values.min(), y_values.max())
        plt.xticks((np.arange(np.ceil(min(x[:, 0]) - 1), np.ceil(max(x[:, 0]) + 1), 1.0)))
        plt.yticks((np.arange(np.ceil(min(x[:, 1]) - 1), np.ceil(max(x[:, 1]) + 1), 1.0)))
        plt.show()
    
    # SVM 支持向量机 惩罚系数
    #### 1 观察支持向量机惩罚系数 C
    svc_line1 = SVC(C = 0.01, kernel='rbf')
    svc_line2 = SVC(C = 5.0, kernel='rbf')
    svc_line3 = SVC(C = 100.0, kernel='rbf')
    svc_line1.fit(x, y)
    svc_line2.fit(x, y)
    svc_line3.fit(x, y)
    border_of_classifier(svc_line1, x, y)
    border_of_classifier(svc_line2, x, y)
    border_of_classifier(svc_line3, x, y)
    

    效果:

    image.png

    相关文章

      网友评论

          本文标题:python实现SVM以及画出分类的边界

          本文链接:https://www.haomeiwen.com/subject/rmfdectx.html