Class: Inferx

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

Defined Under Namespace

Modules: Complementary Classes: Adapter, Categories, Category

Constant Summary collapse

VERSION =
'0.2.3'

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)
  • :namespace (String)

    namespace of keys to be used to Redis

  • :manual (Boolean)

    whether manual save, defaults to false



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

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

Instance Attribute Details

#categoriesObject (readonly)

Returns the value of attribute categories.



21
22
23
# File 'lib/inferx.rb', line 21

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:



41
42
43
44
# File 'lib/inferx.rb', line 41

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:



53
54
55
56
57
# File 'lib/inferx.rb', line 53

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



28
29
30
31
32
33
# File 'lib/inferx.rb', line 28

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