当前位置: 首页 > news >正文

株洲建设网站的公司邢台手机网站建设报价

株洲建设网站的公司,邢台手机网站建设报价,软件工程 旅游网站开发er图,电商专员是做什么的系列文章目录及链接 上篇#xff1a;机器学习#xff08;五#xff09; -- 监督学习#xff08;7#xff09; --SVM1 下篇#xff1a; 前言 tips#xff1a;标题前有“***”的内容为补充内容#xff0c;是给好奇心重的宝宝看的#xff0c;可自行跳过。文章内容被“文…系列文章目录及链接 上篇机器学习五 -- 监督学习7 --SVM1 下篇 前言 tips标题前有“***”的内容为补充内容是给好奇心重的宝宝看的可自行跳过。文章内容被“文章内容”删除线标记的也可以自行跳过。“”一般需要特别注意或者容易出错的地方。 本系列文章是作者边学习边总结的内容有不对的地方还请多多指正同时本系列文章会不断完善每篇文章不定时会有修改。 由于作者时间不算富裕有些内容的《算法实现》部分暂未完善以后有时间再来补充。见谅 文中为方便理解会将接口在用到的时候才导入实际中应在文件开始统一导入。 三、**算法实现 四、接口实现 1、API sklearn.svm.SVC导入 from sklearn.svm import SVC语法 SVC(C1.0, kernel‘rbf’, degree3, gamma‘auto’, coef00.0, shrinkingTrue, probabilityFalse,tol0.001, cache_size200, class_weightNone, verboseFalse, max_iter-1, decision_function_shapeNone,random_stateNone)C惩罚参数默认值是1.0。C越大表示越不允许分类出错这样对训练集测试时准确率很高但泛化能力弱。C值小对误分类的惩罚减小允许容错将他们当成噪声点泛化能力较强。Kernel核函数默认是rbf‘linear’为线性核C越大分类效果越好但可能会过拟合‘rbf’为高斯核gamma值越小分类界面越连续gamma值越大分类界面越“散”分类效果越好但可能会过拟合‘poly’多项式核‘sigmoid’Sigmoid核函数 ‘precomputed’核矩阵decision_function_shape ‘ovo’, ‘ovr’ or None, defaultNoneovr时为one v rest,即一个类别与其他ov类别进行划分ovo时为one v one,即将类别两两进行划分用二分类的方法模拟多分类的结果degree 多项式poly函数的维度默认是3选择其他核函数时会被忽略。gamma ‘rbf’,‘poly’ 和‘sigmoid’的核函数参数。默认是’auto’则会选择1/n_featurescoef0 核函数的常数项。对于‘poly’和 ‘sigmoid’有用。probability 是否采用概率估计.默认为Falseshrinking 是否采用shrinking heuristic方法默认为truetol 停止训练的误差值大小默认为1e-3cache_size 核函数cache缓存大小默认为200class_weight 类别的权重字典形式传递。设置第几类的参数C为weightC(C-SVC中的C)verbose 允许冗余输出max_iter 最大迭代次数。-1为无限制。random_state 数据洗牌时的种子值int值SVC.coef_权重 SVC.intercept_偏置 sklearn.svm.LinearSVC导入 from sklearn.svm import LinearSVC语法 sklearn.svm.LinearSVC(penaltyl2, losssquared_hinge, dualTrue, C1.0)参数penalty:正则化参数L1和L2两种参数可选仅LinearSVC有。loss:损失函数有hinge和squared_hinge两种可选前者⼜称L1损失后者称为L2损失默认是squared_hinge其中hinge是SVM的标准损失squared_hinge是hinge的平方dual:是否转化为对偶问题求解默认是True。C:惩罚系数属性 LinearSVC.coef_权重 LinearSVC.intercept_偏置方法 fix(x,y): 训练模型 predict(x): 用模型进行预测返回预测值 score(x,y[, sample_weight]):返回在(X, y)上预测的准确率 2、线性可分SVM硬间隔流程 2.1、获取数据 from sklearn.datasets import load_iris from sklearn.model_selection import train_test_splitfrom sklearn.svm import SVC# 获取数据 iris load_iris() 2.2、数据预处理 xiris.data[:,(2,3)] yiris.targetsetosa_or_versicolor(y0)|(y1) xx[setosa_or_versicolor] yy[setosa_or_versicolor]# 划分数据集 x_train,x_test,y_train,y_test train_test_split(x, y, test_size0.2, random_state1473) 2.3、特征工程 2.4、模型训练 # 实例化学习器 model_svc SVC(kernellinear,Cfloat(inf))# 模型训练 model_svc.fit(x_train,y_train)print(建立的支持向量机模型为\n, model_svc) 2.5、模型评估 # 用模型计算测试值得到预测值 y_predmodel_svc.predict(x_test)print(前20条记录的预测值为\n, y_pred[:20]) print(前20条记录的实际值为\n, y_test[:20])# 求出预测准确率和混淆矩阵 from sklearn.metrics import accuracy_score, confusion_matrix print(预测结果准确率为, accuracy_score(y_test, y_pred)) print(预测结果混淆矩阵为\n, confusion_matrix(y_test, y_pred)) 2.6、结果预测 经过模型评估后通过的模型可以代入真实值进行预测。 2.7、可视化 xiris.data[:,(2,3)] yiris.targetwmodel_svc.coef_[0] bmodel_svc.intercept_[0]x0np.linspace(0,5.5,200)decision_boundary-w[0]/w[1]*x0-b/w[1] margin1/w[1]gutter_updecision_boundarymargin gutter_downdecision_boundary-margin# 可视化 plt.figure(figsize(14,8))# 数据点 plt.plot(x[:,0][y1],x[:,1][y1],bs) plt.plot(x[:,0][y0],x[:,1][y0],ys)# 支持向量 svsmodel_svc.support_vectors_ plt.scatter(svs[:,0],svs[:,1],s180,facecolorsred)# 决策边界和决策超平面 plt.plot(x0,decision_boundary,k-,linewidth2) plt.plot(x0,gutter_up,k--,linewidth2) plt.plot(x0,gutter_down,k--,linewidth2)# plt.axis([0,5.5,0,2]) 3、线性SVM软间隔流程 3.1、获取数据 from sklearn.datasets import load_iris from sklearn.model_selection import train_test_splitfrom sklearn.svm import SVC# 获取数据 iris load_iris() 3.2、数据预处理 xiris.data[:,(2,3)] y(iris.target2).astype(np.float64) 3.3、特征工程 3.4、模型训练 实现线性SVM用LinearSVC试试 from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScalersvm_clfPipeline(((std,StandardScaler()),(linear_svc,LinearSVC(C 1)) ))svm_clf.fit(x,y) 3.5、模型评估 3.6、结果预测 经过模型评估后通过的模型可以代入真实值进行预测。 svm_clf.predict([[5.5,1.7]]) 3.7、可视化不同C值带来的效果差异 scaler StandardScaler()svm_clf1SVC(kernellinear,C1,random_state1473) svm_clf2SVC(kernellinear,C100,random_state1473)# scaled_svm_clf1Pipeline(( # (std,StandardScaler()), # (linear_svc,svm_clf1) # ))# scaled_svm_clf2Pipeline(( # (std,StandardScaler()), # (linear_svc,svm_clf2) # )) # scaled_svm_clf1.fit(x,y)# scaled_svm_clf2.fit(x,y)svm_clf1.fit(x,y) svm_clf2.fit(x,y) # 绘制决策边界 def plot_svc_decision_boundary(clf,svTrue):wclf.coef_[0]bclf.intercept_[0]x0np.linspace(0,5.5,200)decision_boundary-w[0]/w[1]*x0-b/w[1]margin1/w[1]gutter_updecision_boundarymargingutter_downdecision_boundary-marginif sv:svsclf.support_vectors_plt.scatter(svs[:,0],svs[:,1],s180,facecolorsred)plt.plot(x0,decision_boundary,k-,linewidth2)plt.plot(x0,gutter_up,k--,linewidth2)plt.plot(x0,gutter_down,k--,linewidth2) plt.figure(figsize(14,4))plt.subplot(121) # 数据点 plt.plot(x[:,0][y1],x[:,1][y1],bs,labelIris-Virginica) plt.plot(x[:,0][y0],x[:,1][y0],ys,labelIris-Versicolor)# 决策边界和决策超平面 plot_svc_decision_boundary(svm_clf1,svTrue) plt.xlabel(Petal length,fontsize14) plt.ylabel(Petal width,fontsize14) plt.legend(locupper left,fontsize14) plt.title($C{}$.format(svm_clf1.C),fontsize16)plt.axis([4,6,0.5,3])plt.subplot(122) # 数据点 plt.plot(x[:,0][y1],x[:,1][y1],bs,labelIris-Virginica) plt.plot(x[:,0][y0],x[:,1][y0],ys,labelIris-Versicolor)# 决策边界和决策超平面 plot_svc_decision_boundary(svm_clf2,svTrue) plt.xlabel(Petal length,fontsize14) plt.ylabel(Petal width,fontsize14) plt.legend(locupper left,fontsize14) plt.title($C{}$.format(svm_clf2.C),fontsize16)plt.axis([4,6,0.5,3]) 4、非线性可分SVM核技巧 4.1、升维转换演示 x1Dnp.linspace(-4,4,9).reshape(-1,1) x2Dnp.c_[x1D,x1D**2] ynp.array([0,0,1,1,1,1,1,0,0])plt.figure(figsize(11,4))plt.subplot(121)plt.grid(True,whichboth) plt.axhline(y0,colork) plt.plot(x1D[:,0][y0],np.zeros(4),bs) plt.plot(x1D[:,0][y1],np.zeros(5),g^) plt.gca().get_yaxis().set_ticks([]) plt.xlabel(r$x_1$,fontsize20) plt.axis([-4.5,4.5,-0.2,0.2]) np.zeros(4) x1Dnp.linspace(-4,4,9).reshape(-1,1) x2Dnp.c_[x1D,x1D**2] ynp.array([0,0,1,1,1,1,1,0,0])plt.figure(figsize(11,4))plt.subplot(121)plt.grid(True,whichboth) plt.axhline(y0,colork) plt.plot(x1D[:,0][y0],np.zeros(4),bs) plt.plot(x1D[:,0][y1],np.zeros(5),g^) plt.gca().get_yaxis().set_ticks([]) plt.xlabel(r$x_1$,fontsize20) plt.axis([-4.5,4.5,-0.2,0.2]) np.zeros(4)plt.subplot(122) plt.grid(True,whichboth) plt.axhline(y0,colork) plt.axvline(x0,colork) plt.plot(x2D[:,0][y0],x2D[:,1][y0],bs) plt.plot(x2D[:,0][y1],x2D[:,1][y1],g^) plt.xlabel(r$x_1$,fontsize20) plt.xlabel(r$x_2$,fontsize20,rotation0) plt.gca().get_yaxis().set_ticks([0,4,8,12,16]) plt.plot([-4.5,4.5],[6.5,6.5],r--,linewidth3) plt.axis([-4.5,4.5,-1,17])plt.subplots_adjust(right1) plt.show() 4.2、线性核 4.2.1、创建非线性数据 from sklearn.datasets import make_moons x,ymake_moons(n_samples100,noise0.15,random_state1473)# 创建非线性数据 def plot_dataset(x,y,axes):plt.plot(x[:,0][y0],x[:,1][y0],bs)plt.plot(x[:,0][y1],x[:,1][y1],g^)plt.axis(axes)plt.grid(True,whichboth)plt.xlabel(r$x_1$,fontsize20)plt.xlabel(r$x_2$,fontsize20,rotation0)plot_dataset(x,y,[-1.5,2.5,-1,1.5]) plt.show() 4.2.2、分类预测 使用PolynomialFeatures模块进行预处理使用这个可以增加数据维度 polynomial_svm_clf.fit(X,y)对当前进行训练传进去X和y数据 # 分类预测 from sklearn.datasets import make_moons from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeaturespolynomial_svm_clfPipeline(((poly_features,PolynomialFeatures(degree3)),(scaler ,StandardScaler()),(svm_clf,LinearSVC(C10,losshinge))))polynomial_svm_clf.fit(x,y) def plot_predictions(clf,axes):x0snp.linspace(axes[0],axes[1],100)x1snp.linspace(axes[2],axes[3],100)x0,x1np.meshgrid(x0s,x1s)xnp.c_[x0.ravel(),x1.ravel()]y_predclf.predict(x).reshape(x0.shape)plt.contourf(x0,x1,y_pred,cmapplt.cm.brg,alpha0.2)plot_predictions(polynomial_svm_clf,[-1.5,2.5,-1,1.5]) plot_dataset(x,y,[-1.5,2.5,-1,1.5]) 4.3、多项式核函数 poly_kernel_svm_clfPipeline([(scaler,StandardScaler()),(svm_clf,SVC(kernelpoly,degree3,coef01,C5)) ])poly_kernel_svm_clf.fit(x,y) poly100_kernel_svm_clfPipeline([(scaler,StandardScaler()),(svm_clf,SVC(kernelpoly,degree10,coef0100,C5)) ])poly100_kernel_svm_clf.fit(x,y) plt.figure(figsize(11,4))plt.subplot(121) plot_predictions(poly_kernel_svm_clf,[-1.5,2.5,-1,1.5]) plot_dataset(x,y,[-1.5,2.5,-1,1.5]) plt.title(r$d3,r1,C5$)plt.subplot(122) plot_predictions(poly100_kernel_svm_clf,[-1.5,2.5,-1,1.5]) plot_dataset(x,y,[-1.5,2.5,-1,1.5]) plt.title(r$d10,r100,C5$)plt.show() 4.4、高斯(径向基)RBF核函数 import numpy as np from matplotlib import pyplot as plt## 构造数据 X1D np.linspace(-4, 4, 9).reshape(-1, 1) X2D np.c_[X1D, X1D ** 2] y np.array([0, 0, 1, 1, 1, 1, 1, 0, 0]) from sklearn.datasets import make_moonsX, y make_moons(n_samples100, noise0.15, random_state42) #指定两个环形测试数据from sklearn.svm import SVC from sklearn.pipeline import Pipeline ##使用操作流水线 from sklearn.preprocessing import StandardScaler## 通过设置degree值来进行对比实验 poly_kernel_svm_clf Pipeline([(scaler, StandardScaler()),(svm_clf, SVC(kernelpoly, degree3, coef01, C5)) ##coef0表示偏置项 ]) poly_kernel_svm_clf.fit(X, y)poly100_kernel_svm_clf Pipeline([(scaler, StandardScaler()),(svm_clf, SVC(kernelpoly, degree100, coef01, C5)) ]) poly100_kernel_svm_clf.fit(X, y)# 制图展示对比结果 def plot_predictions(clf, axes):xOs np.linspace(axes[0], axes[1], 100)x1s np.linspace(axes[2], axes[3], 100)x0, x1 np.meshgrid(xOs, x1s) ##构建坐标棋盘X np.c_[x0.ravel(), x1.ravel()]y_pred clf.predict(X).reshape(x0.shape) #一定要对预测结果进行reshape操作plt.contourf(x0, x1, y_pred, cmapplt.cm.brg, alpha0.2)def plot_dataset(X, y, axes):plt.plot(X[:, 0][y 0], X[:, 1][y 0], bs)plt.plot(X[:, 0][y 1], X[:, 1][y 1], g^)plt.axis(axes)plt.grid(True, whichboth)plt.xlabel(r$x_1$, fontsize20)plt.ylabel(r$x_2$, fontsize20, rotation0)plt.figure(figsize(11, 4)) plt.subplot(121) plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5]) plot_dataset(X, y, [-1.5, 2.5, -1, 1.5]) plt.title(r$d3,r1,C5$, fontsize18) plt.subplot(122) plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5]) plot_dataset(X, y, [-1.5, 2.5, -1, 1.5]) plt.title(r$d10,r100,C5$, fontsize18) plt.show() # 定义高斯核函数 def gaussian_rbf(x, landmark, gamma)::param x: 待变换数据:param landmark:当前选择位置:param gamma:不同γ值对公式会产生不同的影响:return:return np.exp(-gamma * np.linalg.norm(x - landmark, axis1) ** 2) gamma 0.3x1s np.linspace(-4.5, 4.5, 200).reshape(-1, 1) ##分别选择不同的地标将数据进行映射 x2s gaussian_rbf(x1s, -2, gamma) x3s gaussian_rbf(x1s, 1, gamma)XK np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)] yk np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])plt.figure(figsize(11, 4))###绘制变换前数据分布已经变换过程 plt.subplot(121) plt.grid(True, whichboth) plt.axhline(y0, colork) plt.scatter(x[-2, 1], y[0, 0], s150, alpha0.5, cred) plt.plot(X1D[:, 0][yk 0], np.zeros(4), bs) plt.plot(X1D[:, 0][yk 1],np.zeros(5), g^) plt.plot(x1s, x2s, g-) plt.plot(x1s, x3s, b:) plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1]) plt.xlabel(r$x_1$, fontsize20) plt.ylabel(rSimilarity, fontsize14) plt.annotate(r$\mathbf{x}$,xy(X1D[3, 0], 0),xytext(-0.5, 0.20),hacenter,arrowpropsdict(facecolorblack, shrink0.1),fontsize18, ) plt.text(-2, 0.9, Sx_2s, hacenter, fontsize20) plt.text(1, 0.9, Sx_3S, hacenter, fontsize20) plt.axis([-4.5, 4.5, -0.1, 1.1]) ###绘制最终结果与分界线 plt.subplot(122) plt.grid(True, whichboth) plt.axhline(y0, colork) plt.axvline(x0, colork) plt.plot(XK[:, 0][yk 0], XK[:, 1][yk 0], bs) plt.plot(XK[:, 0][yk 1], XK[:, 1][yk 1], g^) plt.xlabel(r$x_2$, fontsize20) plt.ylabel(r$x_3$, fontsize20, rotation0) plt.annotate(r$\phi\left (\mathbf{x}\right)$,xy(XK[3, 0], XK[3, 1]),xytext(0.65, 0.50),hacenter,arrowpropsdict(facecolorblack, shrink0.1),fontsize18, ) plt.plot([-0.1, 1.1], [0.57, -0.1], r--, linewidth3) plt.axis([-0.1, 1.1, -0.1, 1.1])plt.subplots_adjust(right1)plt.show() ### 探讨γ值与C值对模型结果的影响 from sklearn.svm import SVCgamma1, gamma2 0.1, 5 C1, C2 0.001, 1000 hyperparams (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)svm_clfs [] for gamma, C in hyperparams:rbf_kernel_svm_clf Pipeline([(scaler, StandardScaler()),(svm_clf, SVC(kernelrbf, gammagamma, CC))])rbf_kernel_svm_clf.fit(X, y)svm_clfs.append(rbf_kernel_svm_clf) plt.figure(figsize(11, 7))for i, svm_clf in enumerate(svm_clfs):plt.subplot(221 i)plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])gamma, C hyperparams[i]plt.title(r$\gamma{},C{}$.format(gamma, C), fontsize16) plt.show() 旧梦可以重温且看机器学习五 -- 监督学习7 --SVM1 欲知后事如何且看
http://www.zqtcl.cn/news/199498/

相关文章:

  • 网站建设用模板好吗罗湖网站制作费用
  • 网站图片延时加载app推广视频
  • 郑州设计师网站个人搭建网站要多少钱
  • 网站制作成品下载wordpress怎么更改样式
  • 河北省城乡和建设厅网站首页网站维护属于什么部门
  • 西安建网站公司哪家好网站导航条设计欣赏
  • 张家港网站网络优化济南网站建设0531soso
  • 关于网站的建设深圳搜索优化排名
  • 网站建设的布局建设通破解vip
  • 怎样做公司网站介绍网站百度排名优化
  • 广州网站建设工作室招聘wordpress在哪里设置编辑器
  • 苏州网站建设功能大宗交易平台软件
  • 无域名网站 能否被百度品牌营销优化
  • 做爰全过程免费的网站视频做网站视频背景
  • 网站布局设计分析特点手机网站设计欣赏网站
  • 建设网站对服务器有什么要求灌南县规划局网站一品嘉苑规划建设
  • 常平镇仿做网站wordpress教程 菜单
  • 大气的企业网站做网站服务怎么赚钱
  • 如何用网站做淘宝客网易企业邮箱怎么修改密码
  • 白酒网站设计wordpress增加网址大全
  • 网站上图片可以做商业作品吗成都十大景观设计公司
  • 自助建站网站哪个好2017织梦网站怎么做seo
  • 佛山新网站建设咨询做业精灵官方网站
  • 大庆网站设计费用asp网站仿制
  • 革吉网站建设网页游戏中心大全
  • 好的网站特点京东物流网站建设特点
  • 昆明企业自助建站系统网站建设技术交流
  • 卖网站模板网站哪家做的比较好
  • 舟山网站网站建设视频网站建设应该注意什么
  • 网站建设 思维导图免费flash网站源码