Advertisement
lucaswiman

Platt sigmoid estimation with scipy.optimize.fmin_bfgs

May 18th, 2011
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. from math import log
  2. import numpy as np
  3. from scipy.optimize import fmin_bfgs
  4.  
  5. def bfgs_sigmoid_train(F, Y, use_grad=True):
  6.     # Reference: Platt, "Probabilistic Outputs for Support Vector Machines"
  7.  
  8.     # Bayesian priors (see Platt end of section 2.2)
  9.     prior0 = sum(1.0 for y in Y if y <=0)
  10.     prior1 = Y.shape[0] - prior0
  11.     T = np.zeros(Y.shape)
  12.     T[Y > 0] = (prior1 + 1) / (prior1 + 2)
  13.     T[Y <= 0] = 1 / (prior0 + 2)
  14.     T1 = 1.0 - T
  15.    
  16.     AB0 = np.array([0.0, log((prior0 + 1.0) / (prior1 + 1.0))])
  17.  
  18.     def objective(AB):
  19.         # From Platt (beginning of Section 2.2)
  20.         E = np.exp(AB[0] * F + AB[1])
  21.         P = 1.0 / (1.0 + E)
  22.         return -(np.dot(T, np.log(P)) + np.dot(T1, np.log(1.0 - P)))
  23.  
  24.     def grad(AB):
  25.         # gradient of the objective function
  26.         E = np.exp(AB[0] * F + AB[1])
  27.         P = 1.0 / (1.0 + E)
  28.         TEP_minus_T1P = P * (T * E - T1)
  29.         dA = np.dot(TEP_minus_T1P, F)
  30.         dB = np.sum(TEP_minus_T1P)
  31.         return np.array([dA, dB])
  32.  
  33.     if use_grad:
  34.         return fmin_bfgs(objective, AB0, fprime=grad)
  35.     else:
  36.         return fmin_bfgs(objective, AB0)
  37.  
  38.  
  39.  
  40. if __name__ == '__main__':
  41.     exF = np.array([5, -4, 1.0])
  42.     exY = np.array([1, -1, -1])
  43.     # computed from my python port of the C++ code in LibSVM
  44.     lin_libsvm_solution = np.array([-0.20261354391187855, 0.65236314980010512])
  45.     assert np.linalg.norm(lin_libsvm_solution - bfgs_sigmoid_train(exF, exY, use_grad=True)) < 0.001
  46.     assert np.linalg.norm(lin_libsvm_solution - bfgs_sigmoid_train(exF, exY, use_grad=False)) < 0.001
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement