Class: SVMKit::KernelMachine::KernelSVC

Inherits:
Object
  • Object
show all
Includes:
Base::BaseEstimator, Base::Classifier
Defined in:
lib/svmkit/kernel_machine/kernel_svc.rb

Overview

KernelSVC is a class that implements (Nonlinear) Kernel Support Vector Classifier with the Pegasos algorithm.

Reference

    1. Shalev-Shwartz, Y. Singer, N. Srebro, and A. Cotter, "Pegasos: Primal Estimated sub-GrAdient SOlver for SVM," Mathematical Programming, vol. 127 (1), pp. 3--30, 2011.

Examples:

training_kernel_matrix = SVMKit::PairwiseMetric::rbf_kernel(training_samples)
estimator =
  SVMKit::KernelMachine::KernelSVC.new(reg_param: 1.0, max_iter: 1000, random_seed: 1)
estimator.fit(training_kernel_matrix, traininig_labels)
testing_kernel_matrix = SVMKit::PairwiseMetric::rbf_kernel(testing_samples, training_samples)
results = estimator.predict(testing_kernel_matrix)

Instance Attribute Summary collapse

Attributes included from Base::BaseEstimator

#params

Instance Method Summary collapse

Constructor Details

#new(reg_param: 1.0, max_iter: 1000, random_seed: 1) ⇒ KernelSVC

Create a new classifier with Kernel Support Vector Machine by the Pegasos algorithm.

Parameters:

  • params (Hash) (defaults to: {})

    The parameters for Kernel SVC.

Options Hash (params):

  • :reg_param (Float) — default: 1.0

    The regularization parameter.

  • :max_iter (Integer) — default: 1000

    The maximum number of iterations.

  • :random_seed (Integer) — default: nil

    The seed value using to initialize the random generator.



46
47
48
49
50
51
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 46

def initialize(params = {})
  self.params = DEFAULT_PARAMS.merge(Hash[params.map { |k, v| [k.to_sym, v] }])
  self.params[:random_seed] ||= srand
  @weight_vec = nil
  @rng = Random.new(self.params[:random_seed])
end

Instance Attribute Details

#rngRandom (readonly)

Return the random generator for performing random sampling in the Pegasos algorithm.

Returns:

  • (Random)


36
37
38
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 36

def rng
  @rng
end

#weight_vecNMatrix (readonly)

Return the weight vector for Kernel SVC.

Returns:

  • (NMatrix)

    (shape: [1, n_trainig_sample])



32
33
34
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 32

def weight_vec
  @weight_vec
end

Instance Method Details

#decision_function(x) ⇒ NMatrix

Calculate confidence scores for samples.

Parameters:

  • x (NMatrix)

    (shape: [n_testing_samples, n_training_samples]) The kernel matrix between testing samples and training samples to compute the scores.

Returns:

  • (NMatrix)

    (shape: [1, n_testing_samples]) Confidence score per sample.



87
88
89
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 87

def decision_function(x)
  @weight_vec.dot(x.transpose)
end

#fit(x, y) ⇒ KernelSVC

Fit the model with given training data.

Parameters:

  • x (NMatrix)

    (shape: [n_training_samples, n_training_samples]) The kernel matrix of the training data to be used for fitting the model.

  • y (NMatrix)

    (shape: [1, n_training_samples]) The labels to be used for fitting the model.

Returns:

  • (KernelSVC)

    The learned classifier itself.



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 59

def fit(x, y)
  # Generate binary labels
  negative_label = y.uniq.sort.shift
  bin_y = y.to_flat_a.map { |l| l != negative_label ? 1 : -1 }
  # Initialize some variables.
  n_training_samples = x.shape[0]
  rand_ids = []
  weight_vec = NMatrix.zeros([1, n_training_samples])
  # Start optimization.
  params[:max_iter].times do |t|
    # random sampling
    rand_ids = [*0...n_training_samples].shuffle(random: @rng) if rand_ids.empty?
    target_id = rand_ids.shift
    # update the weight vector
    func = (weight_vec * bin_y[target_id]).dot(x.row(target_id).transpose).to_f
    func *= bin_y[target_id] / (params[:reg_param] * (t + 1))
    weight_vec[target_id] += 1.0 if func < 1.0
  end
  # Store the learned model.
  @weight_vec = weight_vec * NMatrix.new([1, n_training_samples], bin_y)
  self
end

#marshal_dumpHash

Dump marshal data.

Returns:

  • (Hash)

    The marshal data about KernelSVC.



114
115
116
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 114

def marshal_dump
  { params: params, weight_vec: Utils.dump_nmatrix(@weight_vec), rng: @rng }
end

#marshal_load(obj) ⇒ nil

Load marshal data.

Returns:

  • (nil)


120
121
122
123
124
125
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 120

def marshal_load(obj)
  self.params = obj[:params]
  @weight_vec = Utils.restore_nmatrix(obj[:weight_vec])
  @rng = obj[:rng]
  nil
end

#predict(x) ⇒ NMatrix

Predict class labels for samples.

Parameters:

  • x (NMatrix)

    (shape: [n_testing_samples, n_training_samples]) The kernel matrix between testing samples and training samples to predict the labels.

Returns:

  • (NMatrix)

    (shape: [1, n_testing_samples]) Predicted class label per sample.



96
97
98
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 96

def predict(x)
  decision_function(x).map { |v| v >= 0 ? 1 : -1 }
end

#score(x, y) ⇒ Float

Claculate the mean accuracy of the given testing data.

Parameters:

  • x (NMatrix)

    (shape: [n_testing_samples, n_training_samples]) The kernel matrix between testing samples and training samples.

  • y (NMatrix)

    (shape: [1, n_testing_samples]) True labels for testing data.

Returns:

  • (Float)

    Mean accuracy



106
107
108
109
110
# File 'lib/svmkit/kernel_machine/kernel_svc.rb', line 106

def score(x, y)
  p = predict(x)
  n_hits = (y.to_flat_a.map.with_index { |l, n| l == p[n] ? 1 : 0 }).inject(:+)
  n_hits / y.size.to_f
end