吴恩达机器学习ex6 python实现

本篇博客探讨了如何使用支持向量机(SVM)进行垃圾邮件分类,重点在于高斯内核的实现。作者首先在2D数据集上应用线性SVM,然后自定义实现高斯内核以处理非线性问题,详细解释了高斯内核的作用。接着,通过调整不同数据集的C和σ参数找到最优超参数。最后,利用SVM构建了一个1899维特征的垃圾邮件分类器,并可视化了分类结果。
摘要由CSDN通过智能技术生成

支持向量机

在本练习中,我们将使用高斯核函数的支持向量机(SVM)来构建垃圾邮件分类器。

数据集1

现在2d数据集上实验

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from scipy.io import loadmat
raw_data = loadmat('ex6data1.mat')
data=pd.DataFrame(raw_data.get('X'),columns=['X1','X2'])
data['y'] = raw_data.get('y')
data.head()
X1 X2 y
0 1.9643 4.5957 1
1 2.2753 3.8589 1
2 2.9781 4.5651 1
3 2.9320 3.5519 1
4 3.5772 2.8560 1
#可视化
def plot_init_data(data,fig,ax):
    positive = data[data['y']==1]
    negative = data[data['y']==0]
    ax.scatter(positive['X1'],positive['X2'],s=50,marker='o',c='r',label='positive')
    ax.scatter(negative['X1'],negative['X2'],s=50,marker='x',c='b',label='negative')
fig,ax = plt.subplots(figsize=(12,8))
plot_init_data(data,fig,ax)
ax.legend()
plt.show()

在这里插入图片描述

可以看出左上角有一个异常点,但是整体依然呈现线性分布,所以可以调用线性支持向量机来学习类边界。
令C=1

from sklearn import svm
svc = svm.LinearSVC(C=1,loss='hinge',max_iter=1000)
svc
LinearSVC(C=1, class_weight=None, dual=True, fit_intercept=True,
          intercept_scaling=1, loss='hinge', max_iter=1000, multi_class='ovr',
          penalty='l2', random_state=None, tol=0.0001, verbose=0)
svc.fit(data[['X1','X2']],data['y'])
svc.score(data[['X1','X2']],data['y'])
0.9803921568627451
# 可视化分类边界
def find_decision_boundary(svc,x1min,x2min,x1max,x2max,diff):
    x1 = np.linspace(x1min,x1max,1000)
    x2 = np.linspace(x2min,x2max,1000)
    
    cordinates = [(x,y) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值