Class: Spark::Mllib::SVMModel

Inherits:
ClassificationModel show all
Defined in:
lib/spark/mllib/classification/svm.rb

Overview

SVMModel

A support vector machine.

Examples:

Spark::Mllib.import

# Dense vectors
data = [
    LabeledPoint.new(0.0, [0.0]),
    LabeledPoint.new(1.0, [1.0]),
    LabeledPoint.new(1.0, [2.0]),
    LabeledPoint.new(1.0, [3.0])
]
svm = SVMWithSGD.train($sc.parallelize(data))

svm.predict([1.0])
# => 1
svm.clear_threshold
svm.predict([1.0])
# => 1.25...

# Sparse vectors
data = [
    LabeledPoint.new(0.0, SparseVector.new(2, {0 => -1.0})),
    LabeledPoint.new(1.0, SparseVector.new(2, {1 => 1.0})),
    LabeledPoint.new(0.0, SparseVector.new(2, {0 => 0.0})),
    LabeledPoint.new(1.0, SparseVector.new(2, {1 => 2.0}))
]
svm = SVMWithSGD.train($sc.parallelize(data))

svm.predict(SparseVector.new(2, {1 => 1.0}))
# => 1
svm.predict(SparseVector.new(2, {0 => -1.0}))
# => 0

Instance Attribute Summary

Attributes inherited from ClassificationModel

#intercept, #threshold, #weights

Instance Method Summary collapse

Methods inherited from ClassificationModel

#clear_threshold

Constructor Details

#initialize(*args) ⇒ SVMModel

Returns a new instance of SVMModel.



44
45
46
47
# File 'lib/spark/mllib/classification/svm.rb', line 44

def initialize(*args)
  super
  @threshold = 0.0
end

Instance Method Details

#predict(vector) ⇒ Object

Predict values for a single data point or an RDD of points using the model trained.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/spark/mllib/classification/svm.rb', line 51

def predict(vector)
  vector = Spark::Mllib::Vectors.to_vector(vector)
  margin = weights.dot(vector) + intercept

  if threshold.nil?
    return margin
  end

  if margin > threshold
    1
  else
    0
  end
end