线性可分 SVM

import numpy as np

import matplotlib.pyplot as plt

from sklearn.svm import SVC # "Support vector classifier"

# 定义函数plot_svc_decision_function用于绘制分割超平面和其两侧的辅助超平面

def plot_svc_decision_function(model, ax=None, plot_support=True):

"""Plot the decision function for a 2D SVC"""

if ax is None:

ax = plt.gca()

xlim = ax.get_xlim()

ylim = ax.get_ylim()

# 创建网格用于评价模型

x = np.linspace(xlim[0], xlim[1], 30)

y = np.linspace(ylim[0], ylim[1], 30)

Y, X = np.meshgrid(y, x)

xy = np.vstack([X.ravel(), Y.ravel()]).T

P = model.decision_function(xy).reshape(X.shape)

#绘制超平面

ax.contour(X, Y, P, colors='k',

levels=[-1, 0, 1], alpha=0.5,

linestyles=['--', '-', '--'])

#标识出支持向量

if plot_support:

ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=300, linewidth=1, edgecolors='blue', facecolors='none');

ax.set_xlim(xlim)

ax.set_ylim(ylim)

# 用make_blobs生成样本数据

from sklearn.datasets.samples_generator import make_blobs

X, y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)

# 用线性核函数的SVM来对样本进行分类

model = SVC(kernel='linear')

model.fit(X, y)

# 将样本数据绘制在直角坐标中

plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')

# 在直角坐标中绘制出分割超平面、辅助超平面和支持向量

plot_svc_decision_function(model)

plt.show()

结果

线性 SVM

不同类型样本发生了重叠的情况

import numpy as np

import matplotlib.pyplot as plt

from sklearn.svm import SVC # "Support vector classifier"

# 定义函数plot_svc_decision_function用于绘制分割超平面和其两侧的辅助超平面

def plot_svc_decision_function(model, ax=None, plot_support=True):

"""Plot the decision function for a 2D SVC"""

if ax is None:

ax = plt.gca()

xlim = ax.get_xlim()

ylim = ax.get_ylim()

# 创建网格用于评价模型

x = np.linspace(xlim[0], xlim[1], 30)

y = np.linspace(ylim[0], ylim[1], 30)

Y, X = np.meshgrid(y, x)

xy = np.vstack([X.ravel(), Y.ravel()]).T

P = model.decision_function(xy).reshape(X.shape)

#绘制超平面

ax.contour(X, Y, P, colors='k',

levels=[-1, 0, 1], alpha=0.5,

linestyles=['--', '-', '--'])

#标识出支持向量

if plot_support:

ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=300, linewidth=1, edgecolors='blue', facecolors='none');

ax.set_xlim(xlim)

ax.set_ylim(ylim)

# 用make_blobs生成样本数据

from sklearn.datasets.samples_generator import make_blobs

# X, y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)

X, y = make_blobs(n_samples=100, centers=2, random_state=0, cluster_std=0.9)

# 用线性核函数的SVM来对样本进行分类

model = SVC(kernel='linear')

model.fit(X, y)

# 将样本数据绘制在直角坐标中

plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')

# 在直角坐标中绘制出分割超平面、辅助超平面和支持向量

plot_svc_decision_function(model)

plt.show()

结果

提高惩罚系数C

SVC 类,有一个 C 参数,对应的是错误项(Error Term)的惩罚系数。这个系数设置得越高,容错性也就越小,分隔空间的硬度也就越强。

import numpy as np

import matplotlib.pyplot as plt

from sklearn.svm import SVC # "Support vector classifier"

# 定义函数plot_svc_decision_function用于绘制分割超平面和其两侧的辅助超平面

def plot_svc_decision_function(model, ax=None, plot_support=True):

"""Plot the decision function for a 2D SVC"""

if ax is None:

ax = plt.gca()

xlim = ax.get_xlim()

ylim = ax.get_ylim()

# 创建网格用于评价模型

x = np.linspace(xlim[0], xlim[1], 30)

y = np.linspace(ylim[0], ylim[1], 30)

Y, X = np.meshgrid(y, x)

xy = np.vstack([X.ravel(), Y.ravel()]).T

P = model.decision_function(xy).reshape(X.shape)

#绘制超平面

ax.contour(X, Y, P, colors='k',

levels=[-1, 0, 1], alpha=0.5,

linestyles=['--', '-', '--'])

#标识出支持向量

if plot_support:

ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=300, linewidth=1, edgecolors='blue', facecolors='none');

ax.set_xlim(xlim)

ax.set_ylim(ylim)

# 用make_blobs生成样本数据

from sklearn.datasets.samples_generator import make_blobs

# X, y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)

X, y = make_blobs(n_samples=100, centers=2, random_state=0, cluster_std=0.9)

# 用线性核函数的SVM来对样本进行分类

# model = SVC(kernel='linear')

model = SVC(kernel='linear', C=100.0)

model.fit(X, y)

# 将样本数据绘制在直角坐标中

plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')

# 在直角坐标中绘制出分割超平面、辅助超平面和支持向量

plot_svc_decision_function(model)

plt.show()

结果

完全线性不可分的数据

在完全线性不可分的数据中可以用RBF核在高维度空间分割样本

import numpy as np

import matplotlib.pyplot as plt

from sklearn.svm import SVC # "Support vector classifier"

# 定义函数plot_svc_decision_function用于绘制分割超平面和其两侧的辅助超平面

def plot_svc_decision_function(model, ax=None, plot_support=True):

"""Plot the decision function for a 2D SVC"""

if ax is None:

ax = plt.gca()

xlim = ax.get_xlim()

ylim = ax.get_ylim()

# 创建网格用于评价模型

x = np.linspace(xlim[0], xlim[1], 30)

y = np.linspace(ylim[0], ylim[1], 30)

Y, X = np.meshgrid(y, x)

xy = np.vstack([X.ravel(), Y.ravel()]).T

P = model.decision_function(xy).reshape(X.shape)

#绘制超平面

ax.contour(X, Y, P, colors='k',

levels=[-1, 0, 1], alpha=0.5,

linestyles=['--', '-', '--'])

#标识出支持向量

if plot_support:

ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=300, linewidth=1, edgecolors='blue', facecolors='none');

ax.set_xlim(xlim)

ax.set_ylim(ylim)

# 用make_blobs生成样本数据

# from sklearn.datasets.samples_generator import make_blobs

# X, y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)

# X, y = make_blobs(n_samples=100, centers=2, random_state=0, cluster_std=0.9)

# 用make_circles生成样本数据

from sklearn.datasets.samples_generator import make_circles

X, y = make_circles(100, factor=.1, noise=.1)

from mpl_toolkits import mplot3d

def plot_3D(elev=30, azim=30, X=None, y=None):

ax = plt.subplot(projection='3d')

r = np.exp(-(X ** 2).sum(1))

ax.scatter3D(X[:, 0], X[:, 1], r, c=y, s=50, cmap='autumn')

ax.view_init(elev=elev, azim=azim)

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.set_zlabel('r')

# 用线性核函数的SVM来对样本进行分类

# model = SVC(kernel='linear')

# model = SVC(kernel='linear', C=10.0)

# 用 RBF 核对样本进行分类 再把惩罚系数再调高一百倍

model = SVC(kernel='rbf', C=100)

model.fit(X, y)

# 将样本数据绘制在直角坐标中

# plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')

# 将样本数据绘制在3维坐标中

plot_3D(X=X, y=y)

# 在直角坐标中绘制出分割超平面、辅助超平面和支持向量

plot_svc_decision_function(model)

plt.show()

结果

SVR

import numpy as np

from sklearn.svm import SVR

import matplotlib.pyplot as plt

# 生成样本数据

X = np.sort(5 * np.random.rand(40, 1), axis=0)

# 线性

# y = np.ravel(2*X + 3)

# 曲线

# y = np.polyval([2,3,5,2], X).ravel()

y = np.sin(X).ravel()

# 加入部分噪音

y[::5] += 3 * (0.5 - np.random.rand(8))

# 调用模型

svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)

svr_lin = SVR(kernel='linear', C=1e3)

svr_poly = SVR(kernel='poly', C=1e3, degree=2)

y_rbf = svr_rbf.fit(X, y).predict(X)

y_lin = svr_lin.fit(X, y).predict(X)

y_poly = svr_poly.fit(X, y).predict(X)

# 可视化结果

lw = 2

plt.scatter(X, y, color='darkorange', label='data')

plt.plot(X, y_rbf, color='navy', lw=lw, label='RBF model')

plt.plot(X, y_lin, color='c', lw=lw, label='Linear model')

plt.plot(X, y_poly, color='cornflowerblue', lw=lw, label='Polynomial model')

plt.xlabel('data')

plt.ylabel('target')

plt.title('Support Vector Regression')

plt.legend()

plt.show()

结果

python中的sklearn.svm.svr_Python sklearn 实现SVM和SVR相关推荐

  1. python中的sklearn.svm.svr_python机器学习库scikit-learn:SVR的基本应用

    scikit-learn是python的第三方机器学习库,里面集成了大量机器学习的常用方法.例如:贝叶斯,svm,knn等. scikit-learn的官网 : http://scikit-learn ...

  2. python遥感影像分类代码_python,sklearn,svm,遥感数据分类,代码实例

    python,sklearn,svm,遥感数据分类,代码实例,数据,函数,精度,遥感,路径 python,sklearn,svm,遥感数据分类,代码实例 易采站长站,站长之家为您整理了python,s ...

  3. Python中机器学习神器——sklearn模块

    参考文章 Python机器学习笔记:sklearn库的学习 ML神器:sklearn的快速使用 机器学习与Sklearn的初识 传统的机器学习任务从开始到建模的一般流程是:获取数据 → 数据预处理 → ...

  4. Python中sklearn中HistGradientBoostingRegressor回归器配置单调约束参数monotonic_cst提高回归模型的抗噪声以及局部扰动的能力

    Python中sklearn中HistGradientBoostingRegressor回归器配置单调约束参数monotonic_cst提高回归模型的抗噪声以及局部扰动的能力 目录

  5. python中算法(sklearn)的最优超参数寻优:skopt贝叶斯搜索

    python中算法(sklearn)的最优超参数寻优:skopt贝叶斯搜索 Jeff Dean在ICML 2019上进行了有关AutoML的演讲,并将自动化分为4个级别 手动构造预测变量,不引入学习的 ...

  6. Python中的线性回归:Sklearn与Excel

    内部AI (Inside AI) Around 13 years ago, Scikit-learn development started as a part of Google Summer of ...

  7. python找不到指定模块sklearn怎么办_python中sklearn找不到指定模块怎么办

    python中sklearn找不到指定模块怎么办 发布时间:2020-07-11 15:12:30 来源:亿速云 阅读:94 作者:清晨 这篇文章将为大家详细讲解有关python中sklearn找不到 ...

  8. 解决Python中加载sklearn人脸数据集出现的fetch_olivetti_faces HTTPError: HTTP Error : Forbidden

    解决Python中加载sklearn人脸数据集出现的fetch_olivetti_faces HTTPError: HTTP Error : Forbidden 在使用Python进行机器学习或深度学 ...

  9. python 中的sklearn

    sklearn是python的重要机器学习库,其中封装了大量的机器学习算法,如:分类.回归.降维以及聚类:还包含了监督学习.非监督学习.数据变换三大模块.sklearn拥有完善的文档,使得它具有了上手 ...

最新文章

  1. 央企名录、央企排名——国务院国有资产监督管理委员会央企名录
  2. Go 转义字符及风格
  3. html树形多选下拉列表,EasyUI 多行树形下拉框(Multiple ComboTree)_Vue EasyUI Demo
  4. centos 6 防火墙开启端口无效问题
  5. wxpython制作表格界面_wxpython入门第二步(布局)
  6. putty连接Linux
  7. java中nextLine(),读取换行符的解决
  8. maven 相关简介,和操作命令
  9. java线程期末考试_mooc课程 java 期末考试试卷
  10. uniapp H5端实现PC端适配
  11. ABAP Enhancement
  12. 写一个旅行青蛙攻略APP
  13. 海尔简爱S15电脑使用U盘来重新安装Win10系统教学
  14. 怎么用class引入svg_让动效更酷炫!4 个常见且常用的 SVG 交互动画方法
  15. 供应科研试剂乙缩醛-琥珀酰亚胺酯,Acetal-NHS (SDMB)
  16. 为什么装完计算机系统后进不去,电脑系统装完后为啥进不去?
  17. IT经理世界封面报道:淘宝潜规则
  18. 学习笔记javaSE---集合
  19. 在Linux中进行端口映射问题
  20. SDU软件17级大一下离散期末真题(回忆版)

热门文章

  1. 解决HTML页面右侧空白问题
  2. 支撑好分期千万级还款的支付系统
  3. Resilient Distributed Datasets (RDD)
  4. 程序员一个胳膊受伤了,只能用一个手写代码怎么办?
  5. Git-gitignore规则之“感叹号“的用法坑点
  6. 第二天u3d的学习!
  7. 开源解析器--ANTLR
  8. 马来西亚的吉梦达乳胶床垫以纯天然的姿势震憾入驻中国
  9. php 服务层dao层,DAO层,Service层,Controller层、View层详解
  10. 王思聪100万电脑配置——详情表(附价格)