【Python】SVM 线性可分 硬间隔最大化
2018-03-13 10:42
375 查看
1. 代码
from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt
# np.random.seed(0)
x = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]] # 正态分布来产生数字,20行2列*2
print(x)
# y 的写法值得学习!
y = [0] * 20 + [1] * 20 # 20个class0,20个class1
# svm设置:
clf = svm.SVC(kernel='linear')
clf.fit(x, y)
# 获取w
w = clf.coef_[0]
print('w', w)
a = -w[0] / w[1] # 斜率
# 画图划线
xx = np.linspace(-5, 5) # (-5,5)之间x的值
yy = a * xx - (clf.intercept_[0]) / w[1] # xx带入y,截距
# 画出与点相切的线
b = clf.support_vectors_[0]
yy_down = a * xx + (b[1] - a * b[0])
b = clf.support_vectors_[-1]
yy_up = a * xx + (b[1] - a * b[0])
print("W:", w)
print("a:", a)
print("\nsupport_vectors_:\n", clf.support_vectors_)
print("clf.coef_:", clf.coef_)
# 测试, 两个中括号!
for i in range(20):
a = np.random.randn(1, 2) * 10
print(a)
print('测试', clf.predict(a))
plt.figure(figsize=(8, 4))
plt.plot(xx, yy)
plt.plot(xx, yy_down)
plt.plot(xx, yy_up)
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80)
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Paired) # [:,0]列切片,第0列
plt.axis('tight')
plt.show()
from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt
# np.random.seed(0)
x = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]] # 正态分布来产生数字,20行2列*2
print(x)
# y 的写法值得学习!
y = [0] * 20 + [1] * 20 # 20个class0,20个class1
# svm设置:
clf = svm.SVC(kernel='linear')
clf.fit(x, y)
# 获取w
w = clf.coef_[0]
print('w', w)
a = -w[0] / w[1] # 斜率
# 画图划线
xx = np.linspace(-5, 5) # (-5,5)之间x的值
yy = a * xx - (clf.intercept_[0]) / w[1] # xx带入y,截距
# 画出与点相切的线
b = clf.support_vectors_[0]
yy_down = a * xx + (b[1] - a * b[0])
b = clf.support_vectors_[-1]
yy_up = a * xx + (b[1] - a * b[0])
print("W:", w)
print("a:", a)
print("\nsupport_vectors_:\n", clf.support_vectors_)
print("clf.coef_:", clf.coef_)
# 测试, 两个中括号!
for i in range(20):
a = np.random.randn(1, 2) * 10
print(a)
print('测试', clf.predict(a))
plt.figure(figsize=(8, 4))
plt.plot(xx, yy)
plt.plot(xx, yy_down)
plt.plot(xx, yy_up)
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80)
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Paired) # [:,0]列切片,第0列
plt.axis('tight')
plt.show()
相关文章推荐
- 线性SVM与软间隔最大化
- 线性可分SVM与硬间隔最大化
- SVM学习记录1:线性可分硬间隔最大化
- 支持向量机(二)线性可分支持向量机与硬间隔最大化
- 支持向量机(二)线性可分支持向量机与硬间隔最大化
- SVM 支持向量机(1) 硬间隔最大化
- 统计学习方法笔记:支持向量机之线性可分支持向量机与硬间间隔最大化
- 【Python学习系列八】Python实现线性可分SVM(支持向量机)
- 机器学习之支持向量机SVM Support Vector Machine (一) 线性SVM模型与软硬间隔
- 统计学习方法笔记:1.2 线性支持向量机与软间隔最大化
- [机器学习&数据挖掘]SVM---软间隔最大化
- 机器学习(7)——支持向量机(三):线性支持向量机和软间隔最大化
- SVM 推到期间 遇到的 表背景知识 (间隔最大化)
- Python构建SVM分类器(线性)
- python SVM调包线性分类西瓜
- [机器学习]SVM---硬间隔最大化数学原理
- 【机器学习】使用Scikit-Learn库实现支持向量机(SVM)最大化分类间隔
- 最大间隔多超平面分类器(多线性SVM分类器)介绍及Matlab实现
- 支持向量机 - 2 - 线性可分支持向量机与硬间隔最大化
- SVM 支持向量机(2) 软间隔最大化与核方法