第一步:导包:numpy matplotlib sklearn pil 遇到了问题下载的是python三点八的Python要导包在pycharm里得settings切到三点七的 或者下载一个转换的插件才能在三点八里面导包
import numpy as np
from matplotlib import colors
from sklearn import svm
from sklearn.svm import SVC
from sklearn import model_selection
import matplotlib.pyplot as plt
from PIL import Image
import matplotlib as mpl
第二步:字符串转换成整形
b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2
将这三种花用 0 1 2 表示 因为iris.data文件中的数据都是浮点型 但第五列是字符串所以要将其转换成整形
第三步:读取iris.data文件
#加载数据
data_path: str = 'C:/Users/THINK/iris.data' # 数据文件的路径
data = np.loadtxt(data_path, # 数据文件路径
dtype=float, # 数据类型
delimiter=',', # 数据分隔符
converters={4: iris_type}) # 将第5列使用函数iris_type进行转换
Converters 就是将第五列的数据变成整形 delimiter是因为iris.data 文件里的数据使用,分开的
第四步:划分数据
x, y = np.split(data, # 要切分的数组
(4,), # 沿轴切分的位置,第5列开始往后为y
axis=1) # 代表纵向分割,按列分割
x = x[:, 0:2] # 在X中我们取前两列作为特征,为了后面的可视化。x[:,0:4]代表第一维(行)全取,第二维(列)取0~2
# print(x)
x_train, x_test, y_train, y_test = model_selection.train_test_split(x, # 所要划分的样本特征集
y, # 所要划分的样本结果
random_state=1, # 随机数种子
test_size=0.3) # 测试样本占比
X 是花的特质 y是花的种类 说白了就是教机器 什么特质下是什么种类的话 然后y_train 是根据随机种子固定生成的测试
第五步:svm分类器构建(问)
def classifier():
# clf = svm.SVC(C=0.8,kernel='rbf', gamma=50,decision_function_shape='ovr')
# decision_function_shape='ovr'时,为one v rest,即一个类别与其他类别进行划分,
# decision_function_shape='ovo'时,为one v one,即将类别两两之间进行划分,用二分类的方法模拟多分类的结果。
clf = svm.SVC(C=0.5, # 误差项惩罚系数,默认值是1
kernel='linear', # 线性核 kenrel="rbf":高斯核
decision_function_shape='ovr') # 决策函数
return clf
根据数据可分的情况,svm分为3种:
- 线性可分支持向量机(没有噪音和异常数据,分隔超平面可以在训练数据集做到100%准确)
- 线性支持向量机(有噪音和异常数据,分隔超平面无法在训练数据集做到100%准确)
- 非线性支持向量机(数据集不是线性可分的,必须借助升维)
在sklearn里面,这三个核函数需要不同的超参。
共同需要的超参是C,惩罚系数
clf_linear = svm.SVC(C=1.0, kernel='linear')
clf_poly = svm.SVC(C=1.0, kernel='poly', degree=3)
clf_rbf = svm.SVC(C=1.0, kernel='rbf', gamma=0.5)
1
2
3
degree :多项式poly函数的维度,默认是3,选择其他核函数时会被忽略。
gamma : ‘rbf’,‘poly’ 和‘sigmoid’的核函数参数。默认是’auto’,则会选择1/n_features
coef0 :核函数的常数项,默认为0。对于‘poly’和 ‘sigmoid’有用。
————————————————
版权声明:本文为CSDN博主「yuanlulu」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yuanlulu/article/details/81048496
以下内容整理自吴恩达的视频课程。
当特征很多,样例很少的时候(n很大,m很小),使用核函数容易过拟合,此时经常选择线性核函数。
在使用核函数之前,最好将特征缩放到相同的范围内。否则训练的效果会很差。
n代表特征数量,m代表样本数量
如果n相对m大很多,建议使用逻辑回归或者svm线性核。否则容易过拟合
如果n很小,m比它大,但是大的不是特别多(1000比10000这种),建议使用高斯核
如果m相对n大很多,建议创造一些新特征,然后使用逻辑回归或者使用线性核svm。因为此时高斯核运算会很慢。
————————————————
版权声明:本文为CSDN博主「yuanlulu」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yuanlulu/article/details/81048496
参考文献:https://www.zhihu.com/question/40217487?sort=created
C理解为调节优化方向中两个指标(间隔大小,分类准确度)偏好的权重
soft-margin SVM针对hard-margin SVM容易出现的过度拟合问题,适当放宽了margin的大小,容忍一些分类错误(violation),把这些样本当做噪声处理,本质上是间隔大小和噪声容忍度的一种trade-off,至于具体怎么trade-off,对哪个指标要求更高,那就体现在C这个参数上了。
- 当C趋于无穷大时,这个问题也就是不允许出现分类误差的样本存在,那这就是一个hard-margin SVM问题(过拟合)
- 当C趋于0时,我们不再关注分类是否正确,只要求间隔越大越好,那么我们将无法得到有意义的解且算法不会收敛。(欠拟合)
第六步:其余部分
# **************并判断a b是否相等,计算acc的均值*************
def show_accuracy(a, b, tip):
acc = a.ravel() == b.ravel()
print('%s Accuracy:%.3f' %(tip, np.mean(acc)))
def print_accuracy(clf, x_train, y_train, x_test, y_test):
# 分别打印训练集和测试集的准确率 score(x_train,y_train):表示输出x_train,y_train在模型上的准确率
print('training prediction:%.3f' % (clf.score(x_train, y_train)))
print('testing prediction:%.3f' % (clf.score(x_test, y_test)))
# 原始结果与预测结果进行对比 predict()表示对x_train样本进行预测,返回样本类别
show_accuracy(clf.predict(x_train), y_train, 'training data')
show_accuracy(clf.predict(x_test), y_test, 'testing data')
# 计算决策函数的值,表示x到各分割平面的距离
print('decision_function:\n', clf.decision_function(x_train))
# 4.模型评估
print_accuracy(clf, x_train, y_train, x_test, y_test)
def draw(clf, x):
iris_feature = 'sepal length', 'sepal width', 'petal lenght', 'petal width'
# 开始画图
x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的范围
x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的范围
x1, x2 = np.mgrid[x1_min:x1_max:200j, x2_min:x2_max:200j] # 生成网格采样点 flat是迭代器
grid_test = np.stack((x1.flat, x2.flat), axis=1) # stack():沿着新的轴加入一系列数组 stack增加了一个维度
print('沿着新的轴加入一系列数组:\n', grid_test)
# 输出样本到决策面的距离
z = clf.decision_function(grid_test)
print('样本到决策面的距离:\n', z)
grid_hat = clf.predict(grid_test) # 预测分类值 得到【0,0.。。。2,2,2】
print('预测分类值:\n', grid_hat)
grid_hat = grid_hat.reshape(x1.shape) # reshape grid_hat和x1形状一致
# 若3*3矩阵e,则e.shape()为3*3,表示3行3列
cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])#点的颜色
cm_dark = mpl.colors.ListedColormap(['g', 'b', 'r'])# 背景颜色
plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light) # pcolormesh(x,y,z,cmap)这里参数代入
# x1,x2,grid_hat,cmap=cm_light绘制的是背景。
plt.scatter(x[:, 0], x[:, 1], c=np.squeeze(y), edgecolor='k', s=50, cmap=cm_dark) # 样本点
plt.scatter(x_test[:, 0], x_test[:, 1], s=120, facecolor='none', zorder=30) # 测试点
plt.xlabel(iris_feature[0], fontsize=20)# 这个是两个轴的注释的字体大小
plt.ylabel(iris_feature[1], fontsize=20)
plt.xlim(x1_min, x1_max)#这是数轴的顺序 是从小到大还是从大到小
plt.ylim(x2_min, x2_max)
plt.title('svm in iris data classification', fontsize=30)
plt.grid(1)#这个里面的参数是1 或者不写就是显示网格线 是0就是不显示网格线
plt.show()# 画完了以后进行结果的显示 必须写就完了
# 5.模型使用
draw(clf, x)
Draw中的函数 自己试试就知道做什么用了