Class: Inferx

Inherits:
Object
  • Object
show all
Defined in:
lib/inferx.rb,
lib/inferx/version.rb,
lib/inferx/category.rb,
lib/inferx/categories.rb,
lib/inferx/category/complementary.rb

Defined Under Namespace

Classes: Categories, Category

Constant Summary collapse

VERSION =
'0.2.4'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Inferx

Returns a new instance of Inferx.

Parameters:

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

    other options are passed to Redis#initialize in redis

Options Hash (options):

  • :complementary (Boolean)

    use complementary Bayes classifier

  • :namespace (String)

    namespace of keys to be used to Redis

  • :manual (Boolean)

    whether manual save, defaults to false



14
15
16
17
# File 'lib/inferx.rb', line 14

def initialize(options = {})
  @complementary = !!options[:complementary]
  @categories = Categories.new(Redis.new(options), options)
end

Instance Attribute Details

#categoriesObject (readonly)

Returns the value of attribute categories.



19
20
21
# File 'lib/inferx.rb', line 19

def categories
  @categories
end

Instance Method Details

#classifications(words) ⇒ Hash<String, Float>

Get a score for each category according to a set of words.

Parameters:

  • words (Array<String>)

    a set of words

Returns:

  • (Hash<String, Float>)

    scores to key a category

See Also:



39
40
41
42
# File 'lib/inferx.rb', line 39

def classifications(words)
  words = words.uniq
  Hash[@categories.map { |category| [category.name, score(category, words)] }]
end

#classify(words) ⇒ String

Classify words to any one category.

Parameters:

  • words (Array<String>)

    a set of words

Returns:

  • (String)

    most high-scoring category name

See Also:



51
52
53
54
55
# File 'lib/inferx.rb', line 51

def classify(words)
  method_name = @complementary ? :min_by : :max_by
  category = classifications(words).__send__(method_name) { |score| score[1] }
  category ? category[0] : nil
end

#score(category, words) ⇒ Float

Get a score of a category according to a set of words.

Parameters:

  • category (Inferx::Category)

    a category for scoring

  • words (Array<String>)

    a set of words

Returns:

  • (Float)

    a score of the category



26
27
28
29
30
31
# File 'lib/inferx.rb', line 26

def score(category, words)
  size = category.size.to_f
  return -Float::INFINITY unless size > 0
  scores = category.scores(words)
  scores.inject(0.0) { |s, score| s + Math.log((score || 0.1) / size) }
end