二.代码实现
  
  import numpy as np
  
  from sklearn import datasets
  
  from sklearn.model_selection import train_test_split
  
  from sklearn.linear_model import LogisticRegression
  
  import warnings
  
  warnings.filterwarnings('ignore')
  
  data = datasets.load_breast_cancer()
  
  x = data.data;y = data.target
  
  y[y==0] = -1
  
  x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=1)
  
  omega = np.zeros(x.shape[1])
  
  b = 0
  
  lr = 0.01
  
  C = 1
  
  maxgen = 500
  
  for L in range(maxgen):
  
      error = 1 - (np.dot(x_train,omega)+b)*y_train
  
      index = np.argmax(error)
  
      if error[index] > 0:
  
          omega = (1-lr)*omega + lr*C*y_train[index]*x_train[index,:]
  
          b = b + lr*C*y_train[index]
  
      else:
  
          break
  
  predict_train = np.sign(np.dot(x_train,omega)+b)
  
  train_acc = len(np.where(predict_train==y_train)[0])/len(y_train)
  
  predict_test = np.sign(np.dot(x_test,omega)+b)
  
  test_acc = len(np.where(predict_test==y_test)[0])/len(y_test)
  
  print('Train acc = ',round(train_acc,4),' Test acc = ',round(test_acc,4))
  
  三.SMO算法实现
  
  import numpy as np
  
  from sklearn import datasets
  
  from sklearn import preprocessing
  
  from sklearn.model_selection import train_test_split
  
  from sklearn.svm import SVC
  
  import warnings
  
  warnings.filterwarnings('ignore')
  
  data = datasets.load_breast_cancer()
  
  x = data.data;x = preprocessing.MinMaxScaler().fit_transform(x)
  
  y = data.target;y[y==0] = -1
  
  x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=1)
  
  alpha = np.zeros(x_train.shape[0])
  
  b = 0
  
  C = 1
  
  p = np.zeros(x_train.shape[0])
  
  maxgen = 100
  
  def gramMat(x):
  
      v = []
  
      for i in x:
  
          for j in x:
  
              k = np.dot(i,j.T)
  
              v.append(k)
  
      gram = np.array(v).reshape(len(x),len(x))
  
      return gram
  
  K = gramMat(x_train)
  
  def selectFirstSample(K,y,p,alpha,b,C):
  
      threshold = 0.001
  
      c = y*p-1
  
      c1 = c.copy();c2=c.copy();c3=c.copy()
  
      c1[(alpha > 0) & (c >= 0)] = 0
  
      c2[((alpha==0) | (alpha==C)) & (c==0)] = 0
  
      c3[(alpha < 0) & (c www.tiaotiaoylzc.com/ <= 0)] = 0
  
      error = c1**2+c2**2+c3**2
  
      index = np.argmax(error)
  
      if error[index] >= threshold:
  
          return index
  
      else:
  
          return None
  
  def selectSecondSample(id1,y_train):
  
      id2 = np.random.randint(www.ysyl157.com len(y_train))
  
      while id1 == id2:
  
          id2 = np.random.randint(len(y_train))
  
      return id2
  
  def boundary(y,id1,id2,C):
  
      if y[id1] =www.xgll521.com= y[id2]:
  
          lb = max(0,alpha[id1]+alpha[id2]-C)
  
          ub = min(C,alpha[id1]+alpha[id2])
  
      else:
  
          lb = max(0,alpha[id2]-alpha[id1])
  
          ub = min(C,C+alpha[id2]-alpha[id1])
  
      return lb,ub
  
  def updateAlpha(K,y,p,id1,id2,lb,ub,C):
  
      old_alpha1 = alpha[id1];old_alpha2 = alpha[id2]
  
      p1 = p[id1];p2 = p[id2]
  
      y1 = y[id1];y2 = y[id2]
  
      E1 = p1 - y1;E2 = p2 - y2
  
      beta = 2*K[id1,id2] - K[id1,id1] - K[id2,id2]
  
      new_alpha2 = old_alpha2 - y2*(E1-E2)/beta
  
      if new_alpha2 > ub:
  
          new_alpha2 = ub
  
      if new_alpha2 < lb:
  
          new_alpha2 www.taohuaqing178.com= lb
  
      alpha[id2] = new_alpha2
  
      new_alpha1 = old_alpha1 - y1*y2*(new_alpha2 - old_alpha2)
  
      alpha[id1] = new_alpha1
  
      deta1 = new_alpha1 - old_alpha1
  
      deta2 = new_alpha2 - old_alpha2
  
      dw = [y1*deta1,y2*deta2]
  
      b1 = -E1 - y1*K[id1,id1]*deta1 - y2*K[id1,id2]*deta2
  
      b2 = -E2 - y1*K[id1,id2]*deta1 - y2*K[id2,id2]*deta2
  
      if new_alpha1 >=0 and new_alpha1 <= C:
  
          db = b1
  
      elif new_alpha2 >www.thd178.com/ =0 and new_alpha2 <= C:
  
          db = b2
  
      else:
  
          db = (b1 + b2)/2
  
      p = p + dw[0]*K[id1,:].T + dw[1]*K[id2,:].T + db
  
      return p
  
  for L in range(maxgen):
  
      id1 = selectFirstSample(K,y_train,p,alpha,b,C)
  
      id2 = selectSecondSample(id1,y_train)
  
      lb,ub = boundary(y_train,id1,id2,C)
  
      p = updateAlpha(K,y,p,id1,id2,lb,ub,C)
  
  index = np.argmax((alpha!=0)&(alpha!=C))
  
  b = y_train[index] - np.sum(alpha*y_train*K[:,index])
  
  predict_train = np.sign(np.sum(alpha*y_train*K,axis=0)+b)
  
  train_acc = len(np.where(predict_train==y_train)[0])/len(y_train)
  
  predict_test = []
  
  for arr in x_test:
  
      v = np.sum(alpha*y_train*np.dot(x_train,arr.T))+b
  
      predict_test.append(np.sign(v))   
  
  test_acc = len(np.where(predict_test==y_test)[0])/len(y_test)
  
  print('self-written ==> Train acc = ',round(train_acc,4),' Test acc = ',round(test_acc,4))
  
  model = SVC()
  
  model.fit(x_train,y_train)
  
  train_acc = model.score(x_train,y_train)
  
  test_acc = model.score(x_test,y_test)
  
  print('sklearn ==> Train acc = ',round(train_acc,4),' Test acc = ',round(test_acc,4))

机器学习模型-支持向量机(SVM)的更多相关文章

  1. 机器学习之支持向量机—SVM原理代码实现

    支持向量机—SVM原理代码实现 本文系作者原创,转载请注明出处:https://www.cnblogs.com/further-further-further/p/9596898.html 1. 解决 ...

  2. 机器学习:支持向量机(SVM)

    SVM,称为支持向量机,曾经一度是应用最广泛的模型,它有很好的数学基础和理论基础,但是它的数学基础却比以前讲过的那些学习模型复杂很多,我一直认为它是最难推导,比神经网络的BP算法还要难懂,要想完全懂这 ...

  3. 机器学习算法 - 支持向量机SVM

    在上两节中,我们讲解了机器学习的决策树和k-近邻算法,本节我们讲解另外一种分类算法:支持向量机SVM. SVM是迄今为止最好使用的分类器之一,它可以不加修改即可直接使用,从而得到低错误率的结果. [案 ...

  4. 【机器学习】支持向量机SVM

    关于支持向量机SVM,这里也只是简单地作个要点梳理,尤其是要注意的是SVM的SMO优化算法.核函数的选择以及参数调整.在此不作过多阐述,单从应用层面来讲,重点在于如何使用libsvm,但对其原理算法要 ...

  5. python机器学习之支持向量机SVM

    支持向量机SVM(Support Vector Machine) 关注公众号"轻松学编程"了解更多. [关键词]支持向量,最大几何间隔,拉格朗日乘子法 一.支持向量机的原理 Sup ...

  6. 机器学习(十一) 支持向量机 SVM(上)

    一.什么是支撑向量机SVM (Support Vector Machine) SVM(Support Vector Machine)指的是支持向量机,是常见的一种判别方法.在机器学习领域,是一个有监督 ...

  7. 机器学习-5 支持向量机SVM

    一.概念和背景 SVM:Support Vector Machine 支持向量机. 最早是由Vladimir N. Vapnik和Alexey Ya. Chervonenkis在1963年提出的. 目 ...

  8. 机器学习(十一) 支持向量机 SVM(下)

    支持向量机通过某非线性变换 φ( x) ,将输入空间映射到高维特征空间.特征空间的维数可能非常高.如果支持向量机的求解只用到内积运算,而在低维输入空间又存在某个函数 K(x, x′) ,它恰好等于在高 ...

  9. 吴裕雄--天生自然python机器学习:支持向量机SVM

    基于最大间隔分隔数据 import matplotlib import matplotlib.pyplot as plt from numpy import * xcord0 = [] ycord0 ...

随机推荐

  1. Tornado异步之-协程与回调

    回调处理异步请求 回调 callback 处理异步官方例子 # 导入所需库 from tornado.httpclient import AsyncHTTPClient def asynchronou ...

  2. ECSHOP和SHOPEX快递单号查询国际EMS插件V8.6专版

    发布ECSHOP说明: ECSHOP快递物流单号查询插件特色 本ECSHOP快递物流单号跟踪插件提供国内外近2000家快递物流订单单号查询服务例如申通快递.顺丰快递.圆通快递.EMS快递.汇通快递.宅 ...

  3. Cent OS 下 VI 使用方法

    vi的基本概念  基本上vi可以分为三种状态,分别是命令模式(command mode).插入模式(Insert mode)和底行模式(last line mode),各模式的功能区分如下: 1) 命 ...

  4. 学习RUNOOB.COM进度二

    MongoDB 概念解析 SQL术语/概念 MongoDB术语/概念 解释/说明 database database 数据库 table collection 数据库表/集合 row document ...

  5. go学习笔记-流程控制(if/else,for/range)

    流程控制(if/else,for/range) if if条件判断语句的语法概括起来就是:如果满足条件就做某事,否则做另一件事. func testIf() { num := 10 if num &l ...

  6. (数据科学学习手札06)Python在数据框操作上的总结(初级篇)

    数据框(Dataframe)作为一种十分标准的数据结构,是数据分析中最常用的数据结构,在Python和R中各有对数据框的不同定义和操作. Python 本文涉及Python数据框,为了更好的视觉效果, ...

  7. 三角形xjoi 8.14

    问题描述:离圣诞节只有一个月了,家里要你准备一个很大的星星,然后把它粘在圣诞树的顶端.你已经准备好了一个三角形的银色包装纸来做星星,可忽然有一天你发现在这张大纸上被弄了好多的小洞,原来是你的弟弟妹妹已 ...

  8. 关于 SSH Server 的整体设定

    # . 关于 SSH Server 的整体设定,包含使用的 port 啦,以及使用的密码演算方式 Port # SSH 预设使用 这个 port,您也可以使用多的 port ! # 亦即重复使用 po ...

  9. 快速平方根算法的javascript实现

    前几天看见了一个来自雷神之槌的平方根源码,原理多方有介绍,不赘述. 源码是c语言写的,我思考后发现这样的算法在javascript中也是可以完成的. function InvSqrt(x){ var ...

  10. Jmeter从文件中读取参数值

    1. 通过函数助手,从本地文件中取值选项->函数助手对话框->选择__CSVRead函数->调用参数其中,函数助手对话框中,第一栏填写本地文件所在地址,第二栏写需要入参的值,有点类似 ...