scikit-learn svm初探 分类:机器学习 Sklearn

来源:互联网 发布:极小化极大算法 编辑:程序博客网 时间:2024/05/17 03:33
下面的代码仅仅作为伪代码来看,因为拟合效果不好,思考是优化求解的问题,
仅有w_bar_2_1的解是收敛的,但是拟合效果很差。
svm实现要进一步思考。

[python] view plain copy
print?
  1. import numpy as np  
  2. from sklearn import svm  
  3. from scipy.optimize import minimize  
  4. from numpy.linalg import norm  
  5. from sklearn import datasets  
  6.   
  7. from functools import partial  
  8. import copy  
  9.   
  10. iris = datasets.load_iris()  
  11. print iris.data.shape, iris.target.shape  
  12.   
  13. #w_bar is [b ,w]  
  14. def func(w_bar):  
  15.  return norm(w_bar[1:]) ** 2 / 2  
  16.   
  17. def strain(data, target, w_bar):  
  18.  return target * np.dot(data, w_bar) - 1  
  19.   
  20. #print strain(np.array([[0, 1], [2, 3]]), np.array([0, 1]), np.array([0, 1]))  
  21.   
  22. #print np.unique(iris.target, return_counts = True)  
  23. data = np.append(iris.data, iris.target.reshape(iris.target.shape[0], 1), axis = 1)  
  24.   
  25. data_0 = np.ndarray(shape = (05))  
  26. data_1 = np.ndarray(shape = (05))  
  27. data_2 = np.ndarray(shape = (05))  
  28.   
  29.   
  30. for i in range(data.shape[0]):  
  31.  data_for_append = data[i,:].reshape(1, data[i,:].shape[0])  
  32.  if data[i,-1] == 0:  
  33.   data_0 = np.append(data_0, data_for_append, axis = 0)  
  34.  elif data[i,-1] == 1:  
  35.   data_1 = np.append(data_1, data_for_append, axis = 0)  
  36.  else:  
  37.   data_2 = np.append(data_2, data_for_append, axis = 0)  
  38.   
  39.   
  40. def generate_one_svm(X_y):  
  41.   
  42.  #print X_y  
  43.  X = np.ones([X_y.shape[0], X_y.shape[1]])  
  44.  X[:,1:] = X_y[:,:-1]  
  45.  y = X_y[:,-1].reshape(X_y.shape[0])  
  46.   
  47.  strain_0 = partial(strain, X, y)  
  48.   
  49.  cons = ({  
  50.    ’type’‘ineq’,  
  51.    ’fun’: strain_0  
  52.   },)  
  53.   
  54.  res = minimize(func, np.ones([X.shape[1]]), constraints = cons ,\  
  55.    method = ’SLSQP’, options = {‘disp’True})  
  56.   
  57.  print “w_bar :”  
  58.  print res.x  
  59.   
  60.  return res.x  
  61.   
  62.   
  63. data_True = copy.deepcopy(data_1)  
  64. data_False = copy.deepcopy(data_0)  
  65. data_mix = np.append(data_True, data_False, axis = 0)  
  66. w_bar_1_0 = generate_one_svm(data_mix)  
  67.   
  68. data_True = copy.deepcopy(data_2)  
  69. data_False = copy.deepcopy(data_1)  
  70. data_mix = np.append(data_True, data_False, axis = 0)  
  71. w_bar_2_1 = generate_one_svm(data_mix)  
  72.   
  73. data_True = copy.deepcopy(data_2)  
  74. data_False = copy.deepcopy(data_0)  
  75. data_mix = np.append(data_True, data_False, axis = 0)  
  76. w_bar_2_0 = generate_one_svm(data_mix)  
  77.   
  78. data_predict = np.ndarray(shape = data.shape)  
  79. data_predict[:,:-1] = data[:,:-1]  
  80.   
  81.   
  82. for i in range(data_predict.shape[0]):  
  83.  data_row = np.ones([data_predict.shape[1]])  
  84.  data_row[1:] = data_predict[i,:-1]  
  85.   
  86.  print  
  87.  if np.dot(data_row, w_bar_1_0) > 0:  
  88.   print “np.dot(data_row, w_bar_1_0) > 0”  
  89.   if np.dot(data_row, w_bar_2_1)> 0:  
  90.    print “np.dot(data_row, w_bar_2_1) > 0”  
  91.    data_predict[i,-1] = 2  
  92.   else:  
  93.    print “else”  
  94.    data_predict[i,-1] = 1  
  95.  else:  
  96.   print “else”  
  97.   if np.dot(data_row, w_bar_2_0)> 0:  
  98.    print “np.dot(data_row, w_bar_2_0) > 0”  
  99.    data_predict[i,-1] = 2  
  100.   else:  
  101.    print “else”  
  102.    data_predict[i,-1] = 0  
  103.  print  
  104.   
  105. print data_predict  
  106. print np.unique(data_pr  
import numpy as npfrom sklearn import svmfrom scipy.optimize import minimizefrom numpy.linalg import normfrom sklearn import datasetsfrom functools import partialimport copyiris = datasets.load_iris()print iris.data.shape, iris.target.shape
#w_bar is [b ,w]def func(w_bar): return norm(w_bar[1:]) ** 2 / 2def strain(data, target, w_bar): return target * np.dot(data, w_bar) - 1#print strain(np.array([[0, 1], [2, 3]]), np.array([0, 1]), np.array([0, 1]))#print np.unique(iris.target, return_counts = True)data = np.append(iris.data, iris.target.reshape(iris.target.shape[0], 1), axis = 1)data_0 = np.ndarray(shape = (0, 5))data_1 = np.ndarray(shape = (0, 5))data_2 = np.ndarray(shape = (0, 5))for i in range(data.shape[0]): data_for_append = data[i,:].reshape(1, data[i,:].shape[0]) if data[i,-1] == 0:  data_0 = np.append(data_0, data_for_append, axis = 0) elif data[i,-1] == 1:  data_1 = np.append(data_1, data_for_append, axis = 0) else:  data_2 = np.append(data_2, data_for_append, axis = 0)def generate_one_svm(X_y): #print X_y X = np.ones([X_y.shape[0], X_y.shape[1]]) X[:,1:] = X_y[:,:-1] y = X_y[:,-1].reshape(X_y.shape[0]) strain_0 = partial(strain, X, y) cons = ({   'type': 'ineq',   'fun': strain_0  },) res = minimize(func, np.ones([X.shape[1]]), constraints = cons ,\   method = 'SLSQP', options = {'disp': True}) print "w_bar :" print res.x return res.xdata_True = copy.deepcopy(data_1)data_False = copy.deepcopy(data_0)data_mix = np.append(data_True, data_False, axis = 0)w_bar_1_0 = generate_one_svm(data_mix)data_True = copy.deepcopy(data_2)data_False = copy.deepcopy(data_1)data_mix = np.append(data_True, data_False, axis = 0)w_bar_2_1 = generate_one_svm(data_mix)data_True = copy.deepcopy(data_2)data_False = copy.deepcopy(data_0)data_mix = np.append(data_True, data_False, axis = 0)w_bar_2_0 = generate_one_svm(data_mix)data_predict = np.ndarray(shape = data.shape)data_predict[:,:-1] = data[:,:-1]for i in range(data_predict.shape[0]): data_row = np.ones([data_predict.shape[1]]) data_row[1:] = data_predict[i,:-1] print if np.dot(data_row, w_bar_1_0) > 0:  print "np.dot(data_row, w_bar_1_0) > 0"  if np.dot(data_row, w_bar_2_1)> 0:   print "np.dot(data_row, w_bar_2_1) > 0"   data_predict[i,-1] = 2  else:   print "else"   data_predict[i,-1] = 1 else:  print "else"  if np.dot(data_row, w_bar_2_0)> 0:   print "np.dot(data_row, w_bar_2_0) > 0"   data_predict[i,-1] = 2  else:   print "else"   data_predict[i,-1] = 0 printprint data_predictprint np.unique(data_pr


下面对对偶问题求解,可是算法不收敛,而且由于维数过大,导致求解时间很长:
[python] view plain copy
print?
  1. from scipy.optimize import minimize  
  2. import numpy as np  
  3. from sklearn import datasets  
  4. from functools import partial  
  5. from numpy.linalg import norm  
  6. from math import exp  
  7.   
  8. iris = datasets.load_iris()  
  9.   
  10. data = np.append(iris.data, iris.target.reshape(iris.target.shape[0], 1),axis = 1)  
  11.   
  12. data_True = np.ndarray(shape = (0, data.shape[1]))  
  13. data_False = np.ndarray(shape = (0, data.shape[1]))  
  14.   
  15. for i in range(data.shape[0]):  
  16.  data_for_append = data[i,:].reshape(1, data.shape[1])  
  17.  if data[i][-1] == 1:  
  18.   data_for_append[0, -1] = 1  
  19.   data_True = np.append(data_True, data_for_append, axis = 0)  
  20.  elif data[i][-1] == 0:  
  21.   data_for_append[0, -1] = -1  
  22.   data_False = np.append(data_False, data_for_append, axis = 0)  
  23.   
  24. data = np.append(data_True, data_False, axis = 0)  
  25.   
  26. def kernel_matrix(X):  
  27.  require = np.ndarray(shape = (X.shape[0], X.shape[0]))  
  28.  for i in range(require.shape[0]):  
  29.   for j in range(require.shape[1]):  
  30.    #require[i][j] = np.dot(X[i,:], X[j,:])  
  31.    require[i][j] = exp(-1 * norm(X[i,:] - X[j,:]) ** 2 / 2)  
  32.   
  33.  return require  
  34.   
  35. def func(X, y, alpha):  
  36.  return np.dot(np.dot(alpha.T, kernel_matrix(X)), alpha) - np.dot(np.ones([X.shape[0]]), alpha)  
  37.   
  38. def eq_strain(y, alpha):  
  39.  return np.dot(y, alpha)  
  40.   
  41.   
  42. y = data[:,-1]  
  43. X = data[:,1:]  
  44. eq_strain = partial(eq_strain, y)  
  45.   
  46. #set C val  
  47. C = 10  
  48.   
  49. cons_list = [{  
  50.   ’type’‘eq’,  
  51.   ’fun’: eq_strain  
  52.  },]  
  53.   
  54. for i in range(y.shape[0]):  
  55.  cons_list.append({  
  56.    ’type’‘ineq’,  
  57.    ’fun’lambda alpha: alpha[i]  
  58.   })  
  59.  cons_list.append({  
  60.    ’type’‘ineq’,  
  61.    ’fun’lambda alpha: C - alpha[i]  
  62.   })  
  63.   
  64. cons = tuple(cons_list)  
  65. func = partial(func, X, y)  
  66.   
  67. init_alpha = np.ones([y.shape[0]])  
  68.   
  69.   
  70. res = minimize(func, init_alpha, constraints = cons,\  
  71.     method = ’SLSQP’, options = {‘disp’True})  
  72.   
  73.   
  74. print res.x  
from scipy.optimize import minimizeimport numpy as npfrom sklearn import datasetsfrom functools import partialfrom numpy.linalg import normfrom math import expiris = datasets.load_iris()data = np.append(iris.data, iris.target.reshape(iris.target.shape[0], 1),axis = 1)data_True = np.ndarray(shape = (0, data.shape[1]))data_False = np.ndarray(shape = (0, data.shape[1]))for i in range(data.shape[0]): data_for_append = data[i,:].reshape(1, data.shape[1]) if data[i][-1] == 1:  data_for_append[0, -1] = 1  data_True = np.append(data_True, data_for_append, axis = 0) elif data[i][-1] == 0:  data_for_append[0, -1] = -1  data_False = np.append(data_False, data_for_append, axis = 0)data = np.append(data_True, data_False, axis = 0)def kernel_matrix(X): require = np.ndarray(shape = (X.shape[0], X.shape[0])) for i in range(require.shape[0]):  for j in range(require.shape[1]):   #require[i][j] = np.dot(X[i,:], X[j,:])   require[i][j] = exp(-1 * norm(X[i,:] - X[j,:]) ** 2 / 2) return requiredef func(X, y, alpha): return np.dot(np.dot(alpha.T, kernel_matrix(X)), alpha) - np.dot(np.ones([X.shape[0]]), alpha)def eq_strain(y, alpha): return np.dot(y, alpha)y = data[:,-1]X = data[:,1:]eq_strain = partial(eq_strain, y)
#set C valC = 10cons_list = [{  'type': 'eq',  'fun': eq_strain },]for i in range(y.shape[0]): cons_list.append({   'type': 'ineq',   'fun': lambda alpha: alpha[i]  }) cons_list.append({   'type': 'ineq',   'fun': lambda alpha: C - alpha[i]  })cons = tuple(cons_list)func = partial(func, X, y)init_alpha = np.ones([y.shape[0]])res = minimize(func, init_alpha, constraints = cons,\    method = 'SLSQP', options = {'disp': True})print res.x


这里对参数的约束写法有问题,可能导致迭代速度慢,kernel Matrix写的也不对(漏掉了符号),可能导致得不到收敛值。后面对其进行修改。






下面对二分类问题的对偶形式实现了SVC算法,并进行了检验,得到了正确的结果。
[python] view plain copy
print?
  1. from scipy.optimize import minimize  
  2. import numpy as np  
  3. from sklearn import datasets  
  4. from functools import partial  
  5. from numpy.linalg import norm  
  6. from math import exp  
  7.   
  8. iris = datasets.load_iris()  
  9.   
  10. data = np.append(iris.data, iris.target.reshape(iris.target.shape[0], 1),axis = 1)  
  11.   
  12. data_True = np.ndarray(shape = (0, data.shape[1]))  
  13. data_False = np.ndarray(shape = (0, data.shape[1]))  
  14.   
  15. for i in range(data.shape[0]):  
  16.  data_for_append = data[i,:].reshape(1, data.shape[1])  
  17.  if data[i][-1] == 1:  
  18.   data_for_append[0, -1] = 1  
  19.   data_True = np.append(data_True, data_for_append, axis = 0)  
  20.  elif data[i][-1] == 0:  
  21.   data_for_append[0, -1] = -1  
  22.   data_False = np.append(data_False, data_for_append, axis = 0)  
  23.   
  24. data = np.append(data_True, data_False, axis = 0)  
  25.   
  26. def kernel_matrix(X, y):  
  27.  require = np.ndarray(shape = (X.shape[0], X.shape[0]))  
  28.  for i in range(require.shape[0]):  
  29.   for j in range(require.shape[1]):  
  30.    require[i][j] = np.dot(X[i,:], X[j,:]) * y[i] * y[j]  
  31.   
  32.  return require  
  33.   
  34. def func(X, y, alpha):  
  35.  return np.dot(np.dot(alpha.T, kernel_matrix(X, y)), alpha) - np.dot(np.ones([X.shape[0]]), alpha)  
  36.   
  37. def eq_strain(y, alpha):  
  38.  return np.dot(y, alpha)  
  39.   
  40.   
  41. y = data[:,-1]  
  42. X = data[:,1:]  
  43. eq_strain = partial(eq_strain, y)  
  44.   
  45. #set C val  
  46. C = 10  
  47.   
  48. cons = ({  
  49.   ’type’‘eq’,  
  50.   ’fun’: eq_strain  
  51.  },)  
  52.   
  53. bnds_list = []  
  54.   
  55.   
  56. for i in range(y.shape[0]):  
  57.  bnds_list.append((0, C))  
  58.   
  59. bnds = tuple(bnds_list)  
  60. func = partial(func, X, y)  
  61.   
  62. init_alpha = np.ones([y.shape[0]])  
  63.   
  64.   
  65. res = minimize(func, init_alpha, constraints = cons, bounds = bnds, \  
  66.     method = ’SLSQP’, options = {‘disp’True})  
  67.   
  68.   
  69. alpha = res.x  
  70.   
  71. #we have a success converge  
  72. #return vector y_hat  
  73. def decision_func(X, y, alpha):  
  74.  y_hat_list = []  
  75.   
  76.  j = 0  
  77.  for i in range(y.shape[0]):  
  78.   if alpha[j] > 0 and alpha[j]< C:  
  79.    j = i  
  80.    break  
  81.   
  82.  role = 0  
  83.  for i in range(y.shape[0]):  
  84.   role += y[i] * alpha[i] * np.dot(X[i,:], X[j,:])  
  85.   
  86.  role = y[j] - role  
  87.   
  88.  for i in range(y.shape[0]):  
  89.   SUM = 0  
  90.   for j in range(y.shape[0]):  
  91.    SUM += y[j] * alpha[j] * np.dot(X[j,:],X[i,:])  
  92.   SUM += role  
  93.   
  94.   y_hat_list.append((SUM + role > 0and 1 or -1)  
  95.   
  96.  return np.array(y_hat_list)  
  97.   
  98. y_hat = decision_func(X, y, alpha)  
  99.   
  100. #Test Func  
  101. print np.unique(y * y_hat, return_counts = True)  
from scipy.optimize import minimizeimport numpy as npfrom sklearn import datasetsfrom functools import partialfrom numpy.linalg import normfrom math import expiris = datasets.load_iris()data = np.append(iris.data, iris.target.reshape(iris.target.shape[0], 1),axis = 1)data_True = np.ndarray(shape = (0, data.shape[1]))data_False = np.ndarray(shape = (0, data.shape[1]))for i in range(data.shape[0]): data_for_append = data[i,:].reshape(1, data.shape[1]) if data[i][-1] == 1:  data_for_append[0, -1] = 1  data_True = np.append(data_True, data_for_append, axis = 0) elif data[i][-1] == 0:  data_for_append[0, -1] = -1  data_False = np.append(data_False, data_for_append, axis = 0)data = np.append(data_True, data_False, axis = 0)def kernel_matrix(X, y): require = np.ndarray(shape = (X.shape[0], X.shape[0])) for i in range(require.shape[0]):  for j in range(require.shape[1]):   require[i][j] = np.dot(X[i,:], X[j,:]) * y[i] * y[j] return requiredef func(X, y, alpha): return np.dot(np.dot(alpha.T, kernel_matrix(X, y)), alpha) - np.dot(np.ones([X.shape[0]]), alpha)def eq_strain(y, alpha): return np.dot(y, alpha)y = data[:,-1]X = data[:,1:]eq_strain = partial(eq_strain, y)
#set C valC = 10cons = ({  'type': 'eq',  'fun': eq_strain },)bnds_list = []for i in range(y.shape[0]): bnds_list.append((0, C))bnds = tuple(bnds_list)func = partial(func, X, y)init_alpha = np.ones([y.shape[0]])res = minimize(func, init_alpha, constraints = cons, bounds = bnds, \    method = 'SLSQP', options = {'disp': True})alpha = res.x#we have a success converge#return vector y_hatdef decision_func(X, y, alpha): y_hat_list = [] j = 0 for i in range(y.shape[0]):  if alpha[j] > 0 and alpha[j]< C:   j = i   break role = 0 for i in range(y.shape[0]):  role += y[i] * alpha[i] * np.dot(X[i,:], X[j,:]) role = y[j] - role for i in range(y.shape[0]):  SUM = 0  for j in range(y.shape[0]):   SUM += y[j] * alpha[j] * np.dot(X[j,:],X[i,:])  SUM += role  y_hat_list.append((SUM + role > 0) and 1 or -1) return np.array(y_hat_list)y_hat = decision_func(X, y, alpha)#Test Funcprint np.unique(y * y_hat, return_counts = True)





  












更多了解请浏览:http://blog.csdn.net/sinat_30665603

原创粉丝点击