Machine-Learning 编程作业
Programming Exercise 6:Support Vector Machines
SVM的简单应用
part1 示例文件1使用线性核函数
part2 示例文件2运用高斯核函数
part3 示例文件3运用验证集找最优参数
part4 垃圾邮件分类
这周的作业SVM的实现因为使用的是sklearn库中的SVM库,所以较为简单。但让我最头秃的就是每一次分类之后分类边界的绘制,matplotlab的学习路途任重而道远啊,花了我一下午时间找到三种绘图方法,,太难了。
线性核函数的应用
导入数据集可视化
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
from sklearn.svm import LinearSVC, SVC
raw_data = loadmat('data/ex6data1')
data = pd.DataFrame(raw_data['X'], columns=['X1', 'X2'])
data['y'] = raw_data['y']
print(data)
positive = data[data['y'].isin([1])]
negative = data[data['y'].isin([0])]
fig, ax = plt.subplots(figsize=(6,4))#定义图的大小
ax.scatter(positive['X1'], positive['X2'], s=50, c='b', marker='o', label='Positive')
ax.scatter(negative['X1'], negative['X2'], s=50, c='r', marker='x', label='Negative')
ax.legend()#在图形中加入颜色不同的备注
ax.set_xlabel('X1')
ax.set_ylabel('X2')
plt.show()
评估分类器性能
#下面有两种svm库的使用方法,但几乎都是同样的功能,因为SVC的核函数选为了 线性核函数
# clf = LinearSVC(C=100, loss='hinge', max_iter=1000)
clf = SVC(C=100, kernel='linear', gamma= 0.001)
clf.fit(data[['X1', 'X2']], data['y'])
print(clf.score(dat