SlideShare une entreprise Scribd logo
1  sur  91
Télécharger pour lire hors ligne
Ruby-us Hagrid
Writing Harry Potter with Ruby
@alexpeattiealexpeattie.com/hp
Why should we do it?
What can we achieve?
How can we do it?
Writing Harry Potter with Ruby
Why should we do it?
Category A
The “Potheads”
Category B
The “Notters”
“Ouch, my heart” “Is that Yoda?”
What can we achieve?
(Spoiler!)
Neville, Seamus and Dean were muttering but did
not speak when Harry had told Fudge mere weeks
ago that Malfoy was crying, actually crying tears,
streaming down the sides of their heads. “They
revealed a spell to make your bludger” said Harry,
anger rising once more.
How can we do it?
“They revealed a spell to make your bludger” said
Harry, anger rising once more.
Key idea 1: Tell the story word by word
Key idea 2: Let’s take inspiration from our phones
Ruby-us Hagrid: Writing Harry Potter with Ruby
After “birthday”, I’ve used the word:
- “party” 30 times
- “cake” 20 times
- “wishes” 10 times
After “golden”, J.K. used the word:
- “egg” 13 times
- “snitch” 11 times
- “plates” 10 times
The world “golden” appears in the Harry
Potter books 226 times.
After “golden”, J.K. used the word:
- “egg” 13 times
- “snitch” 11 times
- “plates” 10 times
The world “golden” appears in the Harry
Potter books 226 times.
Head
Continuations
Step 1
Learn
Step 2
Generate
Key idea 3
golden egg
snitch
plates
light
⋮
liquid
13
11
10
9
1
goldfish out
any
bowls
above
1
1
1
1
golf balls 2
⋮
21,814 words
⋮
{
:golden => {
:egg => 13,
:snitch => 11,
:plates => 10,
:light => 9,
:liquid => 1
},
:goldfish => {
:out => 1,
:any => 1,
:of => 1,
:bowls => 1
},
:golf => {
:balls => 2
}
}
alexpeattie.com/hp
def tokenize(text)
text.downcase.split(/[^a-z]+/).reject(&:empty?).map(&:to_sym)
end
"Mr. and Mrs. Dursley, of number four, Privet Drive,
were proud to say that they were perfectly normal"
[:mr, :and, :mrs, :dursley, :of, :number, :four, :privet, :drive,
:were, :proud, :to, :say, :that, :they, :were, :perfectly, :normal]
text = tokenize "The cat sat on the mat.
The cat was happy."
stats = {}
text.each_cons(2) do |head, continuation|
stats[head] ||= Hash.new(0)
stats[head][continuation] += 1
end
text = tokenize "The cat sat on the mat.
The cat was happy."
stats = {}
text.each_cons(2) do |head, continuation|
stats[head] ||= Hash.new(0)
stats[head][continuation] += 1
end
[:the, :cat]
head continuation
{
:the => {
:cat => 1
}
}
text = tokenize "The cat sat on the mat.
The cat was happy."
stats = {}
text.each_cons(2) do |head, continuation|
stats[head] ||= Hash.new(0)
stats[head][continuation] += 1
end
[:cat, :sat]
head continuation
{
:the => {
:cat => 1
},
:cat => {
:sat => 1
}
}
text = tokenize "The cat sat on the mat.
The cat was happy."
stats = {}
text.each_cons(2) do |head, continuation|
stats[head] ||= Hash.new(0)
stats[head][continuation] += 1
end
{
:the => {
:cat => 2,
:mat => 1
},
:cat => {
:sat => 1,
:was => 1
},
:sat => {
:on => 1
},
:on => {
:the => 1
},
:mat => {
:the => 1
},
:was => {
:happy => 1
}
}
Step 1
Learn ✅
Step 2
Generate
Greedy algorithm
Pick most
frequent
continuation
Pick most
frequent
continuation
def pick_next_word_greedily(head)
continuations = stats[head]
chosen_word, count = continuations.max_by { |word, count| count }
return chosen_word
end
story = [stats.keys.sample] # start with a random word from corpus
1.upto(50) do # 50 word story
story << pick_next_word_greedily(story.last)
end
puts story.join(" ")
Drumroll….
“Oh no” said Harry. A few seconds later they
were all the door and the door and the door
and the door and the door.
Take two….
Surreptitiously, several of the door and the
door and the door and the door and the door
and the door and the door.
Ruby-us Hagrid: Writing Harry Potter with Ruby
several
of
the
door
and
conference enchantingly nasty little more
than ever since he was a few seconds later
they were all the door and…
conference
Greedy algorithm
Let’s get random
Uniform random algorithm
Pick randomly w/equal probability
Pick randomly w/equal probability
⅓
⅓ ⅓
Pick randomly w/equal probability
egg
snitch
plates
light
⋮
liquid
1/117
1/117
1/117
1/117
1/117
112 more
def pick_random_next_word(head)
continuations = stats[head]
return continuations.keys.sample
end
Debris from boys or accompany him bodily
from Ron, yell the waters. Harry laughing
together soon father would then bleated the
smelly cloud.
What’s the problem?
house elf
102 times
~1/200
chance
prices
1 time
~1/200
chance
Let’s get (a bit less) random
Weighted random algorithm
house elf
102 times
prices
1 time
~1/200
chance
~1/200
chance
734 times
house elf
102 times
prices
1 time
~1/7
chance
~1/700
chance
734 times
Pick randomly w/weighted probabilities
½
⅓ ⅙
def pick_next_word_weighted_randomly(head)
continuations = stats[head]
continuations.flat_map { |word, count| [word] * count }.sample
end
Springing forward as though they had a bite of the
hippogriff, he staggered blindly retorting Harry
some pumpkin tart.
One last big idea…
Ruby-us Hagrid: Writing Harry Potter with Ruby
Ruby-us Hagrid: Writing Harry Potter with Ruby
Key idea 4: Improve output by looking at more
than just 1 previous word
{
:golden => {
:egg => 12,
:snitch => 11,
:plates => 10,
:light => 9,
:liquid => 1
},
:goldfish => {
:out => 1,
:any => 1,
:of => 1,
:bowls => 1
},
:golf => {
:balls => 2
}
}
Two words
bi·gram
two word
{
[:golden, :egg] => {
:harry => 1,
:very => 1,
:and => 2,
:which => 1,
:upstairs => 1,
:does => 1,
:he => 2,
:said => 1,
:still => 1,
:fell => 1
},
[:golden, :snitch] => {
:and => 1,
:had => 1,
:said => 1,
:it => 1,
:a => 1,
:with => 1,
:was => 1,
:where => 1,
:worked => 1
}
}
321,727 entriestri·gram
three word
Three words
stats = {}

n = 3
corpus.each_cons(n) do |*head, continuation|
stats[head] ||= Hash.new(0)
stats[head][continuation] += 1
end
Added splat
[[:the, :cat], :sat]
head continuation
{
[:the, :cat] => {
:sat => 1
}
}
stats = {}

n = 3
corpus.each_cons(n) do |*head, continuation|
stats[head] ||= Hash.new(0)
stats[head][continuation] += 1
end
Normally when Dudley found his voice barely
louder than before. “Dementors” said Dumbledore
steadily, he however found all this mess is utterly
worthless. Harry looked at him, put Slughorn into
his bag more securely on to bigger and bigger until
their blackness swallowed Harry whole and started
emptying his drawers.
— trigram model
Neville, Seamus and Dean were muttering but did
not speak when Harry had told Fudge mere weeks
ago that Malfoy was crying, actually crying tears,
streaming down the sides of their heads. “They
revealed a spell to make your bludger” said Harry,
anger rising once more.
— 4-gram model
def tokenize(sentence)
sentence.downcase.split(/[^a-z]+/).reject(&:empty?).map(&:to_sym)
end
def pick_next_word_weighted_randomly(head, stats)
continuations = stats[head]
continuations.flat_map { |word, count | [word] * count }.sample
end
text = tokenize(IO.read('hp.txt'))
stats = {}
n = 3
text.each_cons(n) do |*head, continuation|
stats[head] ||= Hash.new(0)
stats[head][continuation] += 1
end
story = stats.keys.sample
1.upto(50) do
story << pick_next_word_weighted_randomly(story.last(n - 1), stats)
end
puts story.join(" ")
20 lines
Harry Potter
Harry Potter
Hard Problems
Ruby-us Hagrid: Writing Harry Potter with Ruby
Ruby-us Hagrid: Writing Harry Potter with Ruby
1. Understand how to break down the
….problem
2. Pay attention to your failures
3. Find the right metaphor
1. Understand how to break down the
….problem
2. Pay attention to your failures
3. Find the right metaphor
How do you eat an elephant? One
bite at a time.
— Proverb
Ruby-us Hagrid: Writing Harry Potter with Ruby
Obvious
1 bite = 1 move
Ruby-us Hagrid: Writing Harry Potter with Ruby
Less obvious
1 bite = 1 turn
⏎
Ruby-us Hagrid: Writing Harry Potter with Ruby
Less obvious still
1 bite = 1 landmark
“What are the building blocks for solving
this problem?”
1. Understand how to break down the
….problem
2. Pay attention to your failures
3. Find the right metaphor
Ruby-us Hagrid: Writing Harry Potter with Ruby
several
of
the
door
and
“Why didn’t this work?”
1. Understand how to break down the
….problem
2. Pay attention to your failures
3. Find the right metaphor
Ruby-us Hagrid: Writing Harry Potter with Ruby
Keeps the essential parts of the problem.
Keeps the essential parts of the problem.
Can play around with the metaphor, and learn more
about the problem.
Harry Potions
Hermione Potions
Neville Potions
Hermione Arithmancy
Hermione Ancient Runes
Neville Herbology
Harry Herbology
Harry Divination
Harry Potions
Hermione Potions
Neville Potions
Hermione Arithmancy
Hermione Ancient Runes
Neville Herbology
Harry Herbology
Harry Divination
Whoops
Herbology
Divination
Potions
Ancient Runes
Arithmancy
Herbology
Divination
Potions
Ancient Runes
Arithmancy
Herbology
Divination
Potions
Ancient Runes
Arithmancy
“What’s a good metaphor for this problem?”
1. Understand how to break down the
….problem
2. Pay attention to your failures
3. Find the right metaphor
Hard Problems
alexpeattie.com/hp
Thank you!
Slides and notes online at:

Contenu connexe

Plus de Pivorak MeetUp

Plus de Pivorak MeetUp (20)

Ruby Summer Course by #pivorak & OnApp - OOP Basics in Ruby
Ruby Summer Course by #pivorak & OnApp - OOP Basics in RubyRuby Summer Course by #pivorak & OnApp - OOP Basics in Ruby
Ruby Summer Course by #pivorak & OnApp - OOP Basics in Ruby
 
The Saga Pattern: 2 years later by Robert Pankowecki
The Saga Pattern: 2 years later by Robert PankoweckiThe Saga Pattern: 2 years later by Robert Pankowecki
The Saga Pattern: 2 years later by Robert Pankowecki
 
Data and Bounded Contexts by Volodymyr Byno
Data and Bounded Contexts by Volodymyr BynoData and Bounded Contexts by Volodymyr Byno
Data and Bounded Contexts by Volodymyr Byno
 
Successful Remote Development by Alex Rozumii
Successful Remote Development by Alex RozumiiSuccessful Remote Development by Alex Rozumii
Successful Remote Development by Alex Rozumii
 
Origins of Elixir programming language
Origins of Elixir programming languageOrigins of Elixir programming language
Origins of Elixir programming language
 
Functional Immutable CSS
Functional Immutable CSS Functional Immutable CSS
Functional Immutable CSS
 
Multi language FBP with Flowex by Anton Mishchuk
Multi language FBP with Flowex by Anton Mishchuk Multi language FBP with Flowex by Anton Mishchuk
Multi language FBP with Flowex by Anton Mishchuk
 
Detective story of one clever user - Lightning Talk By Sergiy Kukunin
Detective story of one clever user - Lightning Talk By Sergiy KukuninDetective story of one clever user - Lightning Talk By Sergiy Kukunin
Detective story of one clever user - Lightning Talk By Sergiy Kukunin
 
CryptoParty: Introduction by Olexii Markovets
CryptoParty: Introduction by Olexii MarkovetsCryptoParty: Introduction by Olexii Markovets
CryptoParty: Introduction by Olexii Markovets
 
How to make first million by 30 (or not, but tryin') - by Marek Piasecki
How to make first million by 30 (or not, but tryin') - by Marek PiaseckiHow to make first million by 30 (or not, but tryin') - by Marek Piasecki
How to make first million by 30 (or not, but tryin') - by Marek Piasecki
 
GIS on Rails by Oleksandr Kychun
GIS on Rails by Oleksandr Kychun GIS on Rails by Oleksandr Kychun
GIS on Rails by Oleksandr Kychun
 
Unikernels - Keep It Simple to the Bare Metal
Unikernels - Keep It Simple to the Bare MetalUnikernels - Keep It Simple to the Bare Metal
Unikernels - Keep It Simple to the Bare Metal
 
HTML Canvas tips & tricks - Lightning Talk by Roman Rodych
 HTML Canvas tips & tricks - Lightning Talk by Roman Rodych HTML Canvas tips & tricks - Lightning Talk by Roman Rodych
HTML Canvas tips & tricks - Lightning Talk by Roman Rodych
 
Linux Tracing Superpowers by Eugene Pirogov
Linux Tracing Superpowers by Eugene PirogovLinux Tracing Superpowers by Eugene Pirogov
Linux Tracing Superpowers by Eugene Pirogov
 
Pivorak How to write better sentences in English
Pivorak How to write better sentences in EnglishPivorak How to write better sentences in English
Pivorak How to write better sentences in English
 
Pivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro Bignyak
 
Building component based rails applications. part 1.
Building component based rails applications. part 1.Building component based rails applications. part 1.
Building component based rails applications. part 1.
 
Building Component Based Rails Applications. Part 2.
Building Component Based Rails Applications. Part 2.Building Component Based Rails Applications. Part 2.
Building Component Based Rails Applications. Part 2.
 
Права інтелектуальної власності в IT сфері.
Права інтелектуальної власності  в IT сфері.Права інтелектуальної власності  в IT сфері.
Права інтелектуальної власності в IT сфері.
 
"Ruby meets Event Sourcing" by Anton Paisov
"Ruby meets Event Sourcing" by Anton Paisov"Ruby meets Event Sourcing" by Anton Paisov
"Ruby meets Event Sourcing" by Anton Paisov
 

Dernier

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Ruby-us Hagrid: Writing Harry Potter with Ruby