Advertisement
Guest User

Untitled

a guest
Jan 27th, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. from sklearn.svm import SVC
  4. import numpy as np
  5.  
  6. #Set up toy SVC problem
  7. X = np.random.random(size=(1000,2))
  8. Y = [1.0 if x1 + x2 > 1 else -1.0 for x1, x2 in X]
  9. C = 10e9
  10.  
  11. #Calculate the constant term for linear SVC using alphas, support vectors, and weights
  12. clf = SVC(C=C, kernel='linear', verbose=True)
  13. clf.fit(X, Y)
  14.  
  15. nSV = sum(clf.n_support_)
  16. b, soft = 0.0, 0.0
  17. for m in range(nSV):
  18.   if np.abs(clf.dual_coef_[0][m]) < C:
  19.     b += (Y[clf.support_[m]] - np.dot(X[clf.support_[m]], np.transpose(clf.coef_)))
  20.   else:
  21.     soft += 1
  22. b /= (nSV - soft)
  23. print "b = %f, clf.intercept_ = %f" % (b, clf.intercept_)
  24.  
  25. #Calculate the constant term for polynomial SVC using alphas and support vectors
  26. coef0, Q = 1.0, 3.0
  27. Kpoly = lambda X, X_dash: (np.dot(X, X_dash) + coef0)**Q
  28. clf = SVC(C=C, kernel='poly', coef0=coef0, degree=Q, verbose=True)
  29. clf.fit(X, Y)
  30.  
  31. nSV = sum(clf.n_support_)
  32. b, soft = 0.0, 0.0
  33. for m in range(nSV):
  34.   if np.abs(clf.dual_coef_[0][m]) < C:
  35.     b += (Y[clf.support_[m]] - np.dot(clf.dual_coef_,
  36.                     [Kpoly(sv, X[clf.support_[m]]) for sv in clf.support_vectors_]))
  37.   else:
  38.     soft += 1
  39. b /= (nSV - soft)
  40. print "b = %f, clf.intercept_ = %f" % (b, clf.intercept_)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement