Class: Ebooks::MarkovModel
- Inherits:
-
Object
- Object
- Ebooks::MarkovModel
- Defined in:
- lib/twitter_ebooks/markov.rb
Constant Summary collapse
- INTERIM =
Special token marking newline/^/$ boundaries
:interim
Instance Attribute Summary collapse
-
#depth ⇒ Object
readonly
Returns the value of attribute depth.
-
#tokens ⇒ Object
Returns the value of attribute tokens.
Instance Method Summary collapse
- #chain(tokens) ⇒ Object
- #consume(tokenized, depth = 2) ⇒ Object
- #deserialize(data) ⇒ Object
- #generate ⇒ Object
- #represent(token) ⇒ Object
- #serialize ⇒ Object
Instance Attribute Details
#depth ⇒ Object (readonly)
Returns the value of attribute depth.
6 7 8 |
# File 'lib/twitter_ebooks/markov.rb', line 6 def depth @depth end |
#tokens ⇒ Object
Returns the value of attribute tokens.
5 6 7 |
# File 'lib/twitter_ebooks/markov.rb', line 5 def tokens @tokens end |
Instance Method Details
#chain(tokens) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/twitter_ebooks/markov.rb', line 51 def chain(tokens) next_token = nil @depth.downto(1).each do |i| next if tokens.length < i matches = @model[tokens.last(i)] if matches #p tokens.last(i) #puts "=> #{matches.inspect}" next_token = matches.sample break end end raise ArgumentError if next_token.nil? if next_token == INTERIM return tokens else return chain(tokens + [next_token]) end end |
#consume(tokenized, depth = 2) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/twitter_ebooks/markov.rb', line 16 def consume(tokenized, depth=2) @tokens = [INTERIM] @depth = depth tokenized.each do |tokens| @tokens += tokens @tokens << INTERIM end @model = {} @tokens.each_with_index do |token, i| prev_tokens = [] @depth.downto(1) do |j| if i-j < 0; next else; prev = represent(@tokens[i-j]) end prev_tokens << prev end 1.upto(@depth) do |j| break if j > prev_tokens.length ngram = prev_tokens.last(j) unless ngram == INTERIM && prev_tokens[-1] == INTERIM @model[ngram] ||= [] @model[ngram] << represent(token) end end end self end |
#deserialize(data) ⇒ Object
83 84 85 86 87 |
# File 'lib/twitter_ebooks/markov.rb', line 83 def deserialize(data) @model = data['model'] @depth = data['depth'] self end |
#generate ⇒ Object
73 74 75 76 |
# File 'lib/twitter_ebooks/markov.rb', line 73 def generate tokens = chain([@model[[INTERIM]].sample]) NLP.reconstruct(tokens) end |
#represent(token) ⇒ Object
8 9 10 11 12 13 14 |
# File 'lib/twitter_ebooks/markov.rb', line 8 def represent(token) if token.nil? || token == "\n" || token.empty? INTERIM else token end end |
#serialize ⇒ Object
78 79 80 81 |
# File 'lib/twitter_ebooks/markov.rb', line 78 def serialize { 'model' => @model, 'depth' => @depth } end |