Class: GooglePrediction::Classifier

Inherits:
Object
  • Object
show all
Defined in:
lib/google_prediction/classifier.rb

Overview

the Classifier class encapsulates one predictive model.

Constant Summary collapse

HEADERS =
{'Content-Type' => 'application/json'}

Instance Method Summary collapse

Constructor Details

#initialize(login, password, bucket, object) ⇒ Classifier

Create a new Classifier.

Args:

- login: your google login (passed to GData)
- password: your google password.
- bucket: the Google Storage bucket where the training data lives.
- object: the name of the training data, including file extension.


38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/google_prediction/classifier.rb', line 38

def initialize(, password, bucket, object)

  # Use the GData gem to authenticate over HTTP.
  @login = GData::Auth::ClientLogin.new('xapi')
  @login.get_token(, password, '')

  @service = GData::HTTP::DefaultService.new
  @bucket = bucket
  @object = object
  @base_uri = "https://www.googleapis.com/prediction/v1/training"
  @model = "#{@bucket}%2F#{@object}"
end

Instance Method Details

#checkObject

Send a check request for the status/accuracy of the model.

Returns:

A hash with information about the model. See web API documentation.


68
69
70
71
# File 'lib/google_prediction/classifier.rb', line 68

def check
  req = GData::HTTP::Request.new(@base_uri + '/' + @model)
  sign_and_request(req)
end

#predict(*signals) ⇒ Object

Send a predict request to the API.

Args:

- signals: a variable number of text and numeric features.

Returns:

- The output label as a String.

Raises:

- ClassifierException. Catch this and wait/retry if hitting rate limit.


84
85
86
87
88
89
90
91
92
93
94
# File 'lib/google_prediction/classifier.rb', line 84

def predict(*signals)
  body = {:data => {:input => {:text => [signals]}}}.to_json
  req = GData::HTTP::Request.new(@base_uri + '/' + @model + "/predict",
            {:method => :post, :body => body, :headers => HEADERS})
  hsh = sign_and_request(req)

  return hsh['data']['output']['output_label'] if hsh['data']
  if hsh['error']
    raise ClassifierException, hsh['error']['message']
  end
end

#train!Object

Send a request to start training on the model in @bucket/@object.

Returns:

Hash of response from server. See web API documentation.


56
57
58
59
60
61
# File 'lib/google_prediction/classifier.rb', line 56

def train!
  body = {:data => {}}.to_json
  req = GData::HTTP::Request.new(@base_uri + '?data=' + @model,
            {:method => :post, :body => body, :headers => HEADERS})
  sign_and_request(req)
end