Adding English novels + Spanish and English static texts

master
ana mertens 3 years ago
parent af88f77222
commit 9c6b716535

@ -0,0 +1,191 @@
1. Introduction
Walk along the trees of Madrid is a book in the 'An Algoliterary Publishing House: making kin with trees'.
The author of this book is the Markov chains algorithm. It simultaneously generates a poem and a walk along the trees of the neighbourhood Las Letras in the centre of Madrid.
The poem is created from a novel chosen by the reader. The reader has the choice between two novels by great Spanish writers of the 19th century:
- 'The Swan of Vila Morta' by the feminist writer Emilia Pardo Bazán published in 1891.
- 'Marianela' by the writer Benito Pérez Galdós, published in 1878.
The walk is generated from the database with trees in Madrid, Un Alcorque, un Árbol <http://www-2.munimadrid.es/DGPVE_WUAUA/welcome.do>. Each significant word - noun, adjective, verb or adverb - is related to a tree in Madrid's neighbourhood las Letras. The other words create the path between the different trees. Thus one can walk through the neighbourhood reciting parts of the poem to each tree along the promenade.
This book is by definition infinite and unique.
It is created by Anaïs Berck. It is a pseudonym that represents a collaboration between humans, algorithms and trees. Anaïs Berck explores the specificities of human intelligence in the company of artificial and plant intelligences.
An Algoliterary Publishing is a collection of publications in which algorithms are the authors of unusual books. This book was created as part of a residency at the center for contemporary arts Medialab Prado in Madrid. The residency was granted by the programme "Residency Digital Culture" initiated by the Flemish Government.
In this work Anaïs Berck is represented by:
- the Markov chains algorithm, of which a description is given in this book
- the trees of Madrid, which are geolocated between Medialab Prado, Plaza del Sol and Atocha Renfe, and present in the database Un Alcorque, un Árbol <http://www-2.munimadrid.es/DGPVE_WUAUA/welcome.do>.
- the human beings Emilia Pardo Bazán, Benito Pérez Gáldos, Jaime Munárriz, Luis Morell, An Mertens, Eva Marina Gracia, Gijs de Heij, Ana Isabel Garrido Mártinez, Alfredo Calosci, Daniel Arribas Hedo.
2. Poem & Walk
3. General description of the Markov Chains
Sources
https://spectrum.ieee.org/andrey-markov-and-claude-shannon-built-the-first-language-generation-models
http://langvillea.people.cofc.edu/MCapps7.pdf
https://www.irishtimes.com/news/science/that-s-maths-andrey-markov-s-brilliant-ideas-are-still-bearing-fruit-1.3220929
http://www.alpha60.de/research/markov/DavidLink_TracesOfTheMouth_2006.pdf
3.1. Histories
Andrey Andreyevich Markov was a Russian mathematician who lived between 1856 and 1922. His most famous studies were with Markov chains, an algorithm that allows to predict future changes once one knows the current state . The first paper on the subject was published in 1906. He was also interested in literature. He tried establishing a linguistic mathematical model using Markov Chains by manually counting letters of Alexander Pusjkins verse novel Eugene Onegin. Next, he applied the method to the novel Childhood Years of Bagrov's Grandson by S.T. Aksakov. This links the Markov Chains directly to the field of literature, text and language. And the link will live firmly throughout the history of this algorithm.
The following text is based on Oscar Schwartz' article for IEEE Spectrum, 'Andrey Markov & Claude Shannon Counted Letters to Build the First Language-Generation Models' <https://spectrum.ieee.org/andrey-markov-and-claude-shannon-built-the-first-language-generation-models>.
In 1913, Andrey Markov sat down in his study in St. Petersburg with a copy of Alexander Pushkins 19th century verse novel, Eugene Onegin <https://en.wikipedia.org/wiki/Eugene_Onegin>, a literary classic at the time. This work comprises almost 400 stanzas of iambic tetrameter. Markov, however, did not start reading Pushkins famous text. Rather, he took a pen and piece of drafting paper, and wrote out the first 20,000 letters of the book in one long string of letters, eliminating all punctuation and spaces. Then he arranged these letters in 200 grids (10-by-10 characters each) and began counting the vowels in every row and column, tallying the results.
In separating the vowels from the consonants, Markov was testing a theory of probability that he had developed in 1906 and that we now call a Markov Process or Markov Chain. Up until that point, the field of probability had been mostly limited to analyzing phenomena like roulette or coin flipping, where the outcome of previous events does not change the probability of current events. But Markov felt that most things happen in chains of causality and are dependent on prior outcomes. He wanted a way of modeling these occurrences through probabilistic analysis.
Language, Markov believed, was an example of a system where past occurrences partly determine present outcomes. To demonstrate this, he wanted to show that in a text like Pushkins novel, the chance of a certain letter appearing at some point in the text is dependent, to some extent, on the letter that came before it.
To do so, Markov began counting vowels in Eugene Onegin, and found that 43 percent of letters were vowels and 57 percent were consonants. Then Markov separated the 20,000 letters into pairs of vowels and consonant combinations. He found that there were 1,104 vowel-vowel pairs, 3,827 consonant-consonant pairs, and 15,069 vowel-consonant and consonant-vowel pairs. What this demonstrated, statistically speaking, was that for any given letter in Pushkins text, if it was a vowel, odds were that the next letter would be a consonant, and vice versa.
Markov used this analysis to demonstrate that Pushkins Eugene Onegin wasnt just a random distribution of letters but had some underlying statistical qualities that could be modeled. The enigmatic research paper that came out of this study, entitled “An Example of Statistical Investigation of the Text Eugene Onegin Concerning the Connection of Samples in Chains,” <http://cs.petrsu.ru/~olbgvl/greatapp/my_project/example_eng.html> was not widely cited in Markovs lifetime, and not translated to English until 2006. Markov was forced to stop his letter-counting experiments, when he had nearly completely lost his sight due to glaucoma. Even if Markov had had more time and better eyesight to carry his experiments further, extensions would have been very difficult to complete, given the precomputer era he lived in, when computational
efforts had to be paid in man-years.
//IMAGES CAPTION: shows Markovs original notes in computing the probabilities needed for his Pushkin chain.//
3.2. Influence
Some of Markov's central concepts around probability and language spread across the globe, eventually finding re-articulation in Claude Shannons hugely influential paper, “A Mathematical Theory of Communication,” (<https://people.math.harvard.edu/~ctm/home/text/others/shannon/entropy/entropy.pdf>) which came out in 1948.
Shannons paper outlined a way to precisely measure the quantity of information in a message, and in doing so, set the foundations for a theory of information that would come to define the digital age. Shannon was fascinated by Markovs idea that in a given text, the likelihood of some letter or word appearing could be approximated. Like Markov, Shannon demonstrated this by performing some textual experiments that involved making a statistical model of language, then took a step further by trying to use the model to generate text according to those statistical rules.
In an initial control experiment, he started by generating a sentence by picking letters randomly from a 27-symbol alphabet (26 letters, plus a space), and got the following output:
XFOML RXKHRJFFJUJ ZLPWCFWKCYJ FFJEYVKCQSGHYD QPAAMKBZAACIBZLHJQD
The sentence was meaningless noise, Shannon said, because when we communicate we dont choose letters with equal probability. As Markov had shown, consonants are more likely than vowels. But at a greater level of granularity, Es are more common than Ss which are more common than Qs. To account for this, Shannon amended his original alphabet so that it modeled the probability of English more closely—he was 11 percent more likely to draw an E from the alphabet than a Q. When he again drew letters at random from this recalibrated corpus he got a sentence that came a bit closer to English.
OCRO HLI RGWR NMIELWIS EU LL NBNESEBYA TH EEI ALHENHTTPA OOBTTVA NAH BRL.
In a series of subsequent experiments, Shannon demonstrated that as you make the statistical model even more complex, you get increasingly more comprehensible results. Shannon, via Markov, revealed a statistical framework for the English language, and showed that by modeling this framework—by analyzing the dependent probabilities of letters and words appearing in combination with each other—he could actually generate language.
The more complex the statistical model of a given text, the more accurate the language generation becomes—or as Shannon put it, the greater “resemblance to ordinary English text.” In the final experiment, Shannon drew from a corpus of words instead of letters and achieved the following:
THE HEAD AND IN FRONTAL ATTACK ON AN ENGLISH WRITER THAT THE CHARACTER OF THIS POINT IS THEREFORE ANOTHER METHOD FOR THE LETTERS THAT THE TIME OF WHO EVER TOLD THE PROBLEM FOR AN UNEXPECTED.
For both Shannon and Markov, the insight that languages statistical properties could be modeled offered a way to re-think broader problems that they were working on. For Markov, it extended the study of stochasticity beyond mutually independent events, paving the way for a new era in probability theory. For Shannon, it helped him formulate a precise way of measuring and encoding units of information in a message, which revolutionized telecommunications and, eventually, digital communication. But their statistical approach to language modeling and generation also ushered in a new era for natural language processing, which has ramified through the digital age to this day. As David Link notes in his article, Traces of the Mouth, Markov's efforts in retrospect “represent an early and momentous attempt to understand the phenomenon of language in mathematical terms.” It's not an exaggeration to say that Markov's analysis of text is in principle similar to what Google and other firms now routinely carry out on a massive scale: analyzing words in books and internet documents, the order in which the words occur, analyzing search phrases, detecting spam and so on.
3.2. Applications
Since Markov chains can be designed to model many real-world processes, they are used in a wide variety of situations. They appear in physics and chemistry when probabilities are used for unknown quantities. In information processing, they have a role in pattern recognition, automatic speech analysis and synthesis and data compression. They are used by meteorologists, ecologists and biologists. Other applications include the control of driverless cars, machine translation, queuing patterns, and prediction of population growth, asset prices, currency exchange rates and market upheavals. Also artists have used Markov chains, such as musician Iannis Xenakis who developed “Free Stochastic Music” based on Markov chains.
In 2006 the 100th anniversary of Markov's paper Philipp Von Hilgers and Amy Langville summarized the five greatest applications of Markov chains <http://langvillea.people.cofc.edu/MCapps7.pdf>. This includes the one that is used by most of us on a daily basis, Google's Page Rank. Every time we search on the internet, the ranking of webpages is based on the solution to massive Markov chain. You can say that all the web pages are states, and the links between them are transitions possessing specific probabilities. In other words, we can say that no matter what youre searching on Google, theres a finite probability of you ending up on a particular web page. If you use Gmail, you mustve noticed their Auto-fill feature. This feature automatically predicts your sentences to help you write emails quickly.
And last but not least, have you ever wondered why spam has all those hilarious nonsensical strings of words in it? Theyre pretty odd constructions, not as random as if you picked words randomly out of a hat, almost grammatical much of the time, but still clearly gibberish. Also here the Markov chains have taken on a lot of the work.
4. Technical description of the Markov Chains
Sources:
https://en.wikipedia.org/wiki/Examples_of_Markov_chains
https://higherkindedtripe.wordpress.com/2012/02/26/markov-chains-or-daddy-where-does-spam-come-from/
https://towardsdatascience.com/predicting-the-weather-with-markov-chains-a34735f0c4df
In a Markov process we can predict future changes once we know the current state. Wikipedia gives a very good description of the difference between Markov chains and other systems: 'A game of snakes and ladders or any other game whose moves are determined entirely by dice is a Markov chain, indeed, an absorbing Markov chain. This is in contrast to card games such as blackjack, where the cards represent a 'memory' of the past moves. To see the difference, consider the probability for a certain event in the game. In the above-mentioned dice games, the only thing that matters is the current state of the board. The next state of the board depends on the current state, and the next roll of the dice. It doesn't depend on how things got to their current state. In a game such as blackjack, a player can gain an advantage by remembering which cards have already been shown (and hence which cards are no longer in the deck), so the next state (or hand) of the game is not independent of the past states.'
So, for a Markov process, only the current state determines the next state; the history of the system has no impact. For that reason we describe a Markov process as memoryless. What happens next is determined completely by the current state and the transition probabilities.
In what follows, we describe a classic working of the Markov chains, next to a simplified version we used to develop a Markov game and the code for this book.
4.1. Classic version
This example is taken from the following source: <https://higherkindedtripe.wordpress.com/2012/02/26/markov-chains-or-daddy-where-does-spam-come-from/>
You take a piece of “training” text.
You make a list of all the words in it.
For each word, make a list of all the other words that come after it, with the number of times each word appears. So with the sentence: “the quick brown fox jumped over the lazy dog”, you would end up with the list:
1. the -> (1, quick), (1, lazy)
2. quick -> (1, brown)
3. brown -> (1, fox)
4. fox -> (1, jumped)
5. jumped -> (1, over)
6. over -> (1, the)
7. lazy -> (1, dog)
8. dog ->
Turn the list into a matrix, where the rows represent the “leading” words and the columns represent “following” words, and each number in the matrix says how many times the following word appeared after the leading word. You will get:
the quick brown fox jumped over lazy dog
the 0 1 0 0 0 0 1 0
quick 0 0 1 0 0 0 0 0
brown 0 0 0 1 0 0 0 0
fox 0 0 0 0 1 0 0 0
jumped 0 0 0 0 0 1 0 0
over 0 0 0 0 0 0 1 0
lazy 0 0 0 0 0 0 0 1
dog 0 0 0 0 0 0 0 0
Divide every number in the matrix by the total of its row, and youll notice that each row becomes a sort of probability distribution.
the quick brown fox jumped over lazy dog
the 0 0.5 0 0 0 0 0.5 0
quick 0 0 1 0 0 0 0 0
brown 0 0 0 1 0 0 0 0
fox 0 0 0 0 1 0 0 0
jumped 0 0 0 0 0 1 0 0
over 0 0 0 0 0 0 1 0
lazy 0 0 0 0 0 0 0 1
dog 0 0 0 0 0 0 0 0
You can interpret this as saying “if the first word is a the theres a 50% chance the next word is quick, and a 50% chance the next word is lazy. For all the other words, there is only one possible word following it.”
Almost every word has only one possible following word because the text is so short. But, if you train it with a larger text, and interpret the rows as a probability distribution, you can start to see for every word what sort of word tends to follow it. This gives a very interesting insight into the nature of written text.
If you take that big “transition matrix” youve trained from a large text, you can use it to actually generate new text in the following way:
1. Pick a “seed” word from the text at random. For best results use one with many possible following words.
2. Find the row in the matrix corresponding to that word. Choose the next word at random, weighted according to the probabilities in the row. That is, if the column corresponding to the word “blue” has the number .05 in it, you have a 5% chance of picking “blue” as the next word, and so on (when we divided each number by the total of its row we made sure that these probabilities would add up to 1).
3. Go back to step 2 using this second word as the new “seed” word. Continue this process to generate as long a string of words as you want. If you end up with a word for which no other words follow it (uncommon when you train on a large test, but possible imagine if the last word of a novel was the only occurrence of the word “xylophone”, or whatever), just pick a random word.
You can see how strings of words generated with this method will follow the “trends” of the training data, meaning that if you were to generate a new transition matrix from the generated words it would, on average, look the same as the original transition matrix since you picked the words according to those weights. This completely mechanical process can generate data which looks, statistically, like meaningful English. Of course, it is not necessarily grammatical, and is certainly devoid of higher meaning since it was generated through this simplistic process.
Those “chains” of words constructed by the above process are an example of Markov chains. And they are also the answer to the question “where does spam come from?”. Those uncannily-almost-grammatical ramblings below the “Viagra” ads, generated through the above process, are the spam-creators way of fooling your spam filter. They include these chains to give their advertisements statistical similarity to meaningful human correspondence. This works because the spam filters are (at least in part) using probabilistic models that depend on word-transitions and word frequencies to classify incoming email as spam. The spammers and the filter-writers are engaged in an eternal game of randomly-generated cat-and-mouse.
4.2. Simplified version
With Algolit <https://algolit.net>, an artistic research group on libre code and literature based in Brussels, we developed a Markov Chain game with sentences and cards. This happened as part of the festival Désert Numérique, in La Drôme in France in 2014. The game was developed by Brendan Howell, Catherine Lenoble and An Mertens. You can listen back to the radio show: <http://desert.numerique.free.fr//archives/?id=1011&ln=fr>.
Next, the game was presented at Transmediale in Berlin in 2015, respecting the following rules.
1. We take a text, for example:
“Cqrrelations read as poetry to statisticians. Can statisticians read poetry with machines?
Cqrrelations is a practise for artists, for datatravellers, statisticians and other lovers of machines to explore a world of blurry categorisations and crummylations.
Machines correlate to dissidents, dissidents correlate to statisticians.”
2. We create a database for this text; each word is an entry and takes the following word as a possible value. The entry for Cqrrelations will have two values:
1. read
2. is
3. Once the database is created, we choose a starting word for a new text, for ex. Cqrrelations.
4. We roll the dice, odd numbers will give read as the 2nd word of our text; even numbers will give is as the 2nd word.
5. We roll the dice again, and choose a word amongst the values of the chosen word. This gives the next word of our sentence.
6. We continue 5 till we arrive at a word with a period (.)
7. We can repeat rule 3 till 6 until we are satisfied with the amount of generated sentences
Based on the input text the output at Transmediale was: “A world of blurry categorisations and other lovers of blurry categorisations and other lovers of blurry categorisations and other lovers of machines. Cqrrelations read poetry to dissidents correlate to machines. Lovers of machines to statisticians.”
5. Code of the book
6. Credits
This book is a creation of Anaïs Berck for Medialab as part of the programme "Residency Digital Cultur" initiated by the Flemish Government.
In this work Anaïs Berck is represented by:
- the Markov chains algorithm, of which a description is given in this book
- the trees of Madrid, which are geolocated between Medialab Prado, Plaza del Sol and Atocha Renfe, and present in the database Un Alcorque, un Árbol <http://www-2.munimadrid.es/DGPVE_WUAUA/welcome.do>.
- the human beings Emilia Pardo Bazán, Benito Pérez Gáldos, Jaime Munárriz, Luis Morell, An Mertens, Eva Marina Gracia, Gijs de Heij, Ana Isabel Garrido Mártinez, Alfredo Calosci, Daniel Arribas Hedo.
The copy of this book is unique and the print run is by definition infinite.
This copy is the XXX number of copies downloaded.
Collective terms of (re)use (CC4r), 2021
Copyleft with a difference: You are invited to copy, distribute, and modify this work under the terms of the
work under the terms of the CC4r: https://gitlab.constantvzw.org/unbound/cc4r

@ -0,0 +1,189 @@
1. Introducción
Paseo por los árboles de Madrid es un libro en la 'Editorial Algoliteraria: crear alianzas con los árboles'.
El autor de este libro es el algoritmo de las cadenas de Markov. Genera simultáneamente un poema y un paseo por los árboles del barrio de Las Letras, en el centro de Madrid.
El poema se crea a partir de una novela elegida por el lector. Éste tiene la opción entre dos novelas de grandes escritores españoles del siglo 19:
- La madre naturaleza de la escritora feminista Emilia Pardo Bazán publicada en 1887. Usa en esta obra una prosa poética y descriptiva, y en sus páginas se siente el amor que profesa al paisaje gallego, con un conocimiento de la botánica y de las costumbres rurales muy superior al de sus contemporáneos.
- Miau del escritor Benito Pérez Galdós publicada en 1888. Enmarcada en el género realista, satiriza el Madrid burocrático de finales del siglo XIX a partir de las vicisitudes vitales de su protagonista, Ramón Villaamil, un competente exempleado del Ministerio de Hacienda, al que una serie de intrigas han dejado cesante.
El paseo se genera a partir de la base de datos con árboles en Madrid, Un Alcorque, un Árbol <http://www-2.munimadrid.es/DGPVE_WUAUA/welcome.do>. Cada palabra significativa - sustantivo, adjetivo, verbo o adverbio - está relacionada a un árbol en el Barrio de las Letras de Madrid. Las otras palabras crean el camino entre los diferentes árboles. Así se puede ir caminando por el barrio recitando partes del poema a cada árbol que se encuentra en el paseo.
Este libro es por definición infinito y único.
Está creada por Anaïs Berck. Es un seudónimo que representa una colaboración entre humanos, algoritmos y árboles. Anaïs Berck explora las especificidades de la inteligencia humana en compañía de las inteligencias artificiales y vegetales.
La Editorial Algoliteraria es una colección de publicaciones en las cuales los algoritmos son los autores de libros inusuales. Este libro fue creado como parte de una residencia en el centro de arte contemporáneo Medialab Prado en Madrid. La residencia fue concedida por el programa "Residencia Cultura Digital" iniciado por el Gobierno Flamenco.
En esta obra Anaïs Berck está representadx por:
el algoritmo de las cadenas de Markov del cual se encuentra una descripción en este libro
los árboles de Madrid, que tienen su geolocalización entre Medialab Prado, Plaza del Sol y Atocha Renfe, dentro de la base de datos Un Alcorque, un Árbol <http://www-2.munimadrid.es/DGPVE_WUAUA/welcome.do>
los seres humanos Emilia Pardo Bazán, Benito Pérez Gáldos, Jaime Munárriz, Luis Morell, An Mertens, Eva Marina Gracia, Gijs de Heij, Ana Isabel Garrido Mártinez, Alfredo Calosci, Daniel Arribas Hedo.
2. Poema & Paseo
3. Descripción general de las cadenas de Markov
Fuentes
https://spectrum.ieee.org/andrey-markov-and-claude-shannon-built-the-first-language-generation-models
http://langvillea.people.cofc.edu/MCapps7.pdf
https://www.irishtimes.com/news/science/that-s-maths-andrey-markov-s-brilliant-ideas-are-still-bearing-fruit-1.3220929
http://www.alpha60.de/research/markov/DavidLink_TracesOfTheMouth_2006.pdf
3.1. Historias
Andrey Andreyevich Markov fue un matemático ruso que vivió entre 1856 y 1922. Sus estudios más famosos fueron con las cadenas de Markov, un algoritmo que permite predecir los cambios futuros una vez que se conoce el estado actual. El primer trabajo sobre el tema se publicó en 1906. También se interesó por la literatura. Intentó establecer un modelo matemático lingüístico mediante cadenas de Markov contando manualmente las letras de la novela en verso de Alexander Pusjkin, Eugene Onegin. A continuación, aplicó el método a la novela Años de infancia del nieto de Bagrov, de S.T. Aksakov. Esto vincula las cadenas de Markov directamente con el campo de la literatura, el texto y el lenguaje. Y el vínculo vivirá firmemente a lo largo de la historia de este algoritmo.
El siguiente texto se basa en el artículo de Oscar Schwartz para IEEE Spectrum, 'Andrey Markov & Claude Shannon Counted Letters to Build the First Language-Generation Models' <https://spectrum.ieee.org/andrey-markov-and-claude-shannon-built-the-first-language-generation-models>.
En 1913, Andrey Markov se sentó en su estudio de San Petersburgo con un ejemplar de la novela en verso del siglo XIX de Alexander Pushkin, Eugene Onegin <https://en.wikipedia.org/wiki/Eugene_Onegin>, un clásico literario de la época. Esta obra consta de casi 400 estrofas de tetrámetro yámbico. Sin embargo, Markov no se puso a leer el famoso texto de Pushkin. Más bien, tomó un bolígrafo y un trozo de papel, y escribió las primeras 20.000 letras del libro en una larga cadena de letras, eliminando todos los signos de puntuación y los espacios. A continuación, dispuso estas letras en 200 cuadrículas (de 10 por 10 caracteres cada una) y comenzó a contar las vocales en cada fila y columna, contabilizando los resultados.
Al separar las vocales de las consonantes, Markov ponía a prueba una teoría de la probabilidad que había desarrollado en 1906 y que ahora llamamos Proceso de Markov o Cadena de Markov. Hasta ese momento, el campo de la probabilidad se había limitado principalmente a analizar fenómenos como la ruleta o el lanzamiento de una moneda, en los que el resultado de eventos anteriores no cambia la probabilidad de los eventos actuales. Pero Markov pensaba que la mayoría de las cosas ocurren en cadenas de causalidad y dependen de resultados anteriores. Quería una forma de modelar estos sucesos mediante un análisis probabilístico.
Markov creía que el lenguaje era un ejemplo de sistema en el que los sucesos pasados determinan en parte los resultados presentes. Para demostrarlo, quería mostrar que en un texto como la novela de Pushkin, la probabilidad de que una determinada letra aparezca en algún momento del texto depende, hasta cierto punto, de la letra que la precede.
Para ello, Markov comenzó a contar las vocales en Eugene Onegin, y descubrió que el 43% de las letras eran vocales y el 57% consonantes. A continuación, Markov separó las 20.000 letras en pares de combinaciones de vocales y consonantes. Descubrió que había 1.104 pares vocal-vocal, 3.827 pares consonante-consonante y 15.069 pares vocal-consonante y consonante-vocal. Lo que esto demostró, estadísticamente hablando, fue que para cualquier letra del texto de Pushkin, si era una vocal, las probabilidades eran que la siguiente letra fuera una consonante, y viceversa.
Markov utilizó este análisis para demostrar que Eugene Onegin de Pushkin no era sólo una distribución aleatoria de letras, sino que tenía algunas cualidades estadísticas subyacentes que podían modelarse. El enigmático trabajo de investigación que surgió de este estudio, titulado "An Example of Statistical Investigation of the Text Eugene Onegin Concerning the Connection of Samples in Chains" (Un ejemplo de investigación estadística del texto Eugene Onegin sobre la conexión de muestras en cadenas), <http://cs.petrsu.ru/~olbgvl/greatapp/my_project/example_eng.html> no fue muy citado en vida de Markov, y no se tradujo al inglés hasta 2006. Markov se vio obligado a interrumpir sus experimentos de recuento de letras, cuando había perdido casi por completo la vista debido a un glaucoma. Aunque Markov hubiera tenido más tiempo y mejor vista para llevar a cabo sus experimentos, las extensiones habrían sido muy difíciles de completar, dada la época preinformática en la que vivió, en la que los esfuerzos
computacionales debían pagarse en años-hombre.
//IMAGES CAPTION: Las notas originales de Markov para calcular las probabilidades necesarias para su cadena Pushkin.//
3.2. Influencia
Algunos de los conceptos centrales de Markov en torno a la probabilidad y el lenguaje se extendieron por el mundo entero, y acabaron encontrando su rearticulación en el enormemente influyente documento de Claude Shannon, "A Mathematical Theory of Communication" (<https://people.math.harvard.edu/~ctm/home/text/others/shannon/entropy/entropy.pdf>), que se publicó en 1948.
El documento de Shannon esbozaba una forma de medir con precisión la cantidad de información en un mensaje y, al hacerlo, sentaba las bases de una teoría de la información que llegaría a definir la era digital. A Shannon le fascinaba la idea de Markov de que, en un texto dado, se podía aproximar la probabilidad de que apareciera alguna letra o palabra. Al igual que Markov, Shannon lo demostró realizando algunos experimentos textuales (en inglés) que implicaban la elaboración de un modelo estadístico del lenguaje, y luego dio un paso más al tratar de utilizar el modelo para generar texto de acuerdo con esas reglas estadísticas.
En un primer experimento de control, empezó generando una frase eligiendo letras al azar de un alfabeto de 27 símbolos (26 letras, más un espacio), y obtuvo el siguiente resultado:
XFOML RXKHRJFFJUJ ZLPWCFWKCYJ FFJEYVKCQSGHYD QPAAMKBZAACIBZLHJQD
La frase era ruido sin sentido, dijo Shannon, porque cuando nos comunicamos no elegimos las letras con igual probabilidad. Como había demostrado Markov, las consonantes son más probables que las vocales. Pero a un mayor nivel de granularidad, las E son más comunes que las S, que son más comunes que las Q. Para tener en cuenta este hecho, Shannon modificó su alfabeto original para que se ajustara más a la probabilidad del inglés: era un 11% más probable sacar una E del alfabeto que una Q. Cuando volvió a sacar letras al azar de este corpus recalibrado, obtuvo una frase que se acercaba un poco más al inglés.
OCRO HLI RGWR NMIELWIS EU LL NBNESEBYA TH EEI ALHENHTTPA OOBTTVA NAH BRL.
In a series of subsequent experiments, Shannon demonstrated that as you make the statistical model even more complex, you get increasingly more comprehensible results. Shannon, via Markov, revealed a statistical framework for the English language, and showed that by modeling this framework—by analyzing the dependent probabilities of letters and words appearing in combination with each other—he could actually generate language.
Cuanto más complejo sea el modelo estadístico de un texto dado, más precisa será la generación del lenguaje, o como dijo Shannon, mayor será el "parecido con el texto inglés ordinario". En el experimento final, Shannon recurrió a un corpus de palabras en lugar de letras y consiguió lo siguiente:
THE HEAD AND IN FRONTAL ATTACK ON AN ENGLISH WRITER THAT THE CHARACTER OF THIS POINT IS THEREFORE ANOTHER METHOD FOR THE LETTERS THAT THE TIME OF WHO EVER TOLD THE PROBLEM FOR AN UNEXPECTED.
Tanto para Shannon como para Markov, la idea de que las propiedades estadísticas del lenguaje podían ser modeladas ofrecía una forma de replantear problemas más amplios en los que estaban trabajando. Para Markov, amplió el estudio de la estocasticidad más allá de los eventos mutuamente independientes, abriendo el camino para una nueva era en la teoría de la probabilidad. Para Shannon, le ayudó a formular una forma precisa de medir y codificar unidades de información en un mensaje, lo que revolucionó las telecomunicaciones y, finalmente, la comunicación digital. Pero su enfoque estadístico en la modelación y la generación del lenguaje también marcó el comienzo de una nueva era para el procesamiento del lenguaje natural, que se ha ramificado en la era digital hasta nuestros días. Como señala David Link en su artículo Traces of the Mouth, los esfuerzos de Markov en retrospectiva "representan un intento temprano y trascendental de entender el fenómeno del lenguaje en términos matemáticos". No es exagerado decir que el análisis de texto de Markov es, en principio, similar a lo que Google y otras empresas llevan a cabo ahora de forma rutinaria y a gran escala: analizar las palabras de los libros y los documentos de Internet, el orden en que aparecen las palabras, analizar las frases de búsqueda, detectar el spam, etc.
3.2. Applicaciones
Dado que las cadenas de Markov pueden diseñarse para modelar muchos procesos del mundo real, se utilizan en una gran variedad de situaciones. Aparecen en física y química cuando se utilizan probabilidades para cantidades desconocidas. En el tratamiento de la información, desempeñan un papel en el reconocimiento de patrones, el análisis y la síntesis automática del habla y la compresión de datos. Los meteorólogos, ecologistas y biólogos los utilizan. Otras aplicaciones son el control de coches sin conductor, la traducción automática, los patrones de colas y la predicción del crecimiento de la población, los precios de los activos, los cambios de moneda y las crísis del mercado. También artistas han utilizado las cadenas de Markov, como el músico Iannis Xenakis, que desarrolló la "Música estocástica libre" basada en las cadenas de Markov.
En 2006 - el centenario del artículo de Markov - Philipp Von Hilgers y Amy Langville resumieron las cinco mayores aplicaciones de las cadenas de Markov <http://langvillea.people.cofc.edu/MCapps7.pdf>. Entre ellas se encuentra la que utilizamos la mayoría de nosotros a diario: el Page Rank de Google. Cada vez que buscamos en Internet, la clasificación de las páginas web se basa en una solución de la cadena de Markov masiva. Se puede decir que todas las páginas web son estados, y los enlaces entre ellas son transiciones que poseen probabilidades específicas. En otras palabras, podemos decir que, independientemente de lo que busques en Google, hay una probabilidad finita de que acabes en una página web concreta. Si utilizas Gmail, habrás notado su función de autorrelleno. Esta función predice automáticamente tus frases para ayudarte a escribir correos electrónicos rápidamente. Las cadenas de Markov ayudan considerablemente en este sector, ya que pueden proporcionar predicciones de este tipo de forma eficaz.
Y por último, pero no menos importante, ¿te has preguntado alguna vez por qué el spam tiene todas esas divertidas cadenas de palabras sin sentido? Son construcciones bastante extrañas, no tan aleatorias como si se sacaran palabras al azar de un sombrero, casi gramaticales la mayor parte de las veces, pero aún así son un claro galimatías. También aquí las cadenas de Markov han asumido gran parte del trabajo.
4. Descripción técnica de las cadenas de Markov
Sources:
https://en.wikipedia.org/wiki/Examples_of_Markov_chains
https://higherkindedtripe.wordpress.com/2012/02/26/markov-chains-or-daddy-where-does-spam-come-from/
https://towardsdatascience.com/predicting-the-weather-with-markov-chains-a34735f0c4df
En un proceso de Markov podemos predecir los cambios futuros una vez que conocemos el estado actual. Wikipedia describe muy bien la diferencia entre las cadenas de Markov y otros sistemas: "Un juego de serpientes y escaleras o cualquier otro juego cuyas jugadas se determinan enteramente por los dados es una cadena de Markov, de hecho, una cadena de Markov absorbente. Esto contrasta con los juegos de cartas, como el blackjack, donde las cartas representan una "memoria" de las jugadas anteriores. Para ver la diferencia, considere la probabilidad de un determinado evento en el juego. En los juegos de dados mencionados, lo único que importa es el estado actual del tablero. El siguiente estado del tablero depende del estado actual y de la siguiente tirada de dados. No depende de cómo han llegado las cosas a su estado actual. En un juego como el blackjack, un jugador puede obtener ventaja recordando qué cartas se han mostrado ya (y, por tanto, qué cartas ya no están en la baraja), por lo que el siguiente estado (o mano) del juego no es independiente de los estados pasados".
Así, para un proceso de Markov, sólo el estado actual determina el siguiente estado; la historia del sistema no tiene ningún impacto. Por eso describimos un proceso de Markov como sin memoria. Lo que ocurre a continuación viene determinado completamente por el estado actual y las probabilidades de transición.
A continuación, describimos un funcionamiento clásico de las cadenas de Markov, junto a una versión simplificada que hemos utilizado para desarrollar un juego de Markov y el código de este libro.
4.1. Versión clásica
Este ejemplo está tomado de la siguiente fuente: <https://higherkindedtripe.wordpress.com/2012/02/26/markov-chains-or-daddy-where-does-spam-come-from/>
Coge un texto de "entrenamiento".
Haz una lista de todas las palabras que contiene.
Para cada palabra, haga una lista de todas las demás palabras que vienen después de ella, con el número de veces que aparece cada palabra. Así, con la frase "the quick brown fox jumped over the lazy dog", acabarías con la lista:
1. the -> (1, quick), (1, lazy)
2. quick -> (1, brown)
3. brown -> (1, fox)
4. fox -> (1, jumped)
5. jumped -> (1, over)
6. over -> (1, the)
7. lazy -> (1, dog)
8. dog ->
Convierte la lista en una matriz, en la que las filas representan las palabras "principales" y las columnas representan las palabras "siguientes", y cada número de la matriz dice cuántas veces apareció la palabra siguiente después de la palabra principal. Obtendrás:
the quick brown fox jumped over lazy dog
the 0 1 0 0 0 0 1 0
quick 0 0 1 0 0 0 0 0
brown 0 0 0 1 0 0 0 0
fox 0 0 0 0 1 0 0 0
jumped 0 0 0 0 0 1 0 0
over 0 0 0 0 0 0 1 0
lazy 0 0 0 0 0 0 0 1
dog 0 0 0 0 0 0 0 0
Divide cada número de la matriz por el total de su fila y verás que cada fila se convierte en una especie de distribución de probabilidad.
the quick brown fox jumped over lazy dog
the 0 0.5 0 0 0 0 0.5 0
quick 0 0 1 0 0 0 0 0
brown 0 0 0 1 0 0 0 0
fox 0 0 0 0 1 0 0 0
jumped 0 0 0 0 0 1 0 0
over 0 0 0 0 0 0 1 0
lazy 0 0 0 0 0 0 0 1
dog 0 0 0 0 0 0 0 0
Se puede interpretar como que "si la primera palabra es un 'the', hay un 50% de posibilidades de que la siguiente palabra sea 'quick', y un 50% de posibilidades de que la siguiente palabra sea 'lazy'. Para todas las demás palabras, sólo hay una palabra posible a continuación".
Casi todas las palabras tienen sólo una posible palabra siguiente porque el texto es muy corto. Pero si se entrena con un texto más extenso y se interpretan las filas como una distribución de probabilidades, se puede empezar a ver para cada palabra qué tipo de palabra tiende a seguirla. Esto ofrece una visión muy interesante del carácter del texto escrito.
Si tomas esa gran "matriz de transición" que has entrenado a partir de un texto grande, puedes usarla para generar realmente un nuevo texto de la siguiente manera:
1. Elija al azar una palabra "semilla" del texto. Para obtener los mejores resultados, utilice una con muchas palabras siguientes posibles.
2. Encuentre la fila de la matriz correspondiente a esa palabra. Elija la siguiente palabra al azar, ponderada según las probabilidades de la fila. Es decir, si la columna correspondiente a la palabra "azul" tiene el número 0,05, tienes un 5% de posibilidades de elegir "azul" como siguiente palabra, y así sucesivamente (al dividir cada número por el total de su fila nos aseguramos de que estas probabilidades sumen 1).
3. Vuelve al paso 2 utilizando esta segunda palabra como la nueva palabra "semilla". Continúe este proceso para generar una cadena de palabras tan larga como desee. Si acaba con una palabra a la que no le siguen otras (algo poco común cuando se entrena con una prueba grande, pero posible: imagine que la última palabra de una novela fuera la única ocurrencia de la palabra "xilófono", o lo que sea), simplemente elija una palabra al azar.
Se puede ver cómo las cadenas de palabras generadas con este método seguirán las "tendencias" de los datos de entrenamiento, lo que significa que si se generara una nueva matriz de transición a partir de las palabras generadas, ésta tendría, en promedio, el mismo aspecto que la matriz de transición original, ya que se eligieron las palabras de acuerdo con esos pesos. Este proceso completamente mecánico puede generar datos que se parecen, estadísticamente, a un idioma significativo. Por supuesto, no es necesariamente gramatical, y está ciertamente desprovisto de significado superior, ya que fue generado a través de este proceso simplista.
Esas "cadenas" de palabras construidas por el proceso anterior son un ejemplo de cadenas de Markov. Y también son la respuesta a la pregunta "¿de dónde viene el spam?". Esas divagaciones casi gramaticales debajo de los anuncios de "Viagra", generadas mediante el proceso anterior, son la forma que tienen los creadores de spam de engañar a su filtro de spam. Incluyen estas cadenas para dar a sus anuncios una similitud estadística con la correspondencia humana significativa. Esto funciona porque los filtros de spam utilizan (al menos en parte) modelos probabilísticos que dependen de las transiciones y frecuencias de las palabras para clasificar el correo electrónico entrante como spam. Los emisores de spam y los redactores de los filtros se enzarzan en un eterno juego del gato y el ratón generado aleatoriamente.
4.2. Versión simplificada
Con Algolit <https://algolit.net>, un grupo de investigación artística sobre código y literatura libres con sede en Bruselas, desarrollamos un juego de cadenas de Markov con frases y cartas. Esto ocurrió como parte del festival Désert Numérique, en La Drôme en Francia en 2014. El juego fue desarrollado por Brendan Howell, Catherine Lenoble y An Mertens. Puedes escuchar el programa de radio: <http://desert.numerique.free.fr//archives/?id=1011&ln=fr>.
A continuación, el juego se presentó en Transmediale, en Berlín, en 2015, respetando las siguientes reglas.
1. Tomamos un texto, por ejemplo:
“Cqrrelations read as poetry to statisticians. Can statisticians read poetry with machines?
Cqrrelations is a practise for artists, for datatravellers, statisticians and other lovers of machines to explore a world of blurry categorisations and crummylations.
Machines correlate to dissidents, dissidents correlate to statisticians.”
2. Creamos una base de datos para este texto; cada palabra es una entrada y toma la palabra siguiente como valor posible. La entrada de "Cqrrelations" tendrá dos valores:
1. read
2. is
3. Una vez creada la base de datos, elegimos una palabra inicial para un nuevo texto, por ejemplo Cqrrelations.
4. Tiramos el dado, los números impares darán "leer" como 2ª palabra de nuestro texto; los números pares darán "es" como 2ª palabra.
5. Volvemos a tirar el dado y elegimos una palabra entre los valores de la palabra elegida. Esto da la siguiente palabra de nuestra frase.
6. Continuamos 5 hasta llegar a una palabra con un punto (.)
7. Podemos repetir la regla 3 hasta la 6 hasta que estemos satisfechos con la cantidad de frases generadas
Basado en el texto de entrada el resultado en Transmediale fue: “A world of blurry categorisations and other lovers of blurry categorisations and other lovers of blurry categorisations and other lovers of machines. Cqrrelations read poetry to dissidents correlate to machines. Lovers of machines to statisticians.”
5. Código
6. Créditos
Este libro es una creación de Anaïs Berck para Medialab como parte del programa "Residencia Cultura Digital" iniciado por el Gobierno Flamenco.
En esta obra Anaïs Berck está representadx por:
el algoritmo de las cadenas de Markov del cual se encuentra una descripción en este libro
los árboles de Madrid, que tienen su geolocalización entre Medialab Prado, Plaza del Sol y Atocha Renfe, dentro de la base de datos Un Alcorque, un Árbol <http://www-2.munimadrid.es/DGPVE_WUAUA/welcome.do>
los seres humanos Emilia Pardo Bazán, Benito Pérez Gáldos, Jaime Munárriz, Luis Morell, An Mertens, Eva Marina Gracia, Gijs de Heij, Ana Isabel Garrido Mártinez, Alfredo Calosci, Daniel Arribas Hedo.
La copia de este libro es única y el tiraje es por definición infinito.
Esta copia es el número XXX de copias descargadas.
Condiciones colectivas de (re)uso (CC4r), 2021
Copyleft con una diferencia: Se le invita a copiar, distribuir y modificar esta
obra bajo los términos de la CC4r: https://gitlab.constantvzw.org/unbound/cc4r
Loading…
Cancel
Save