Hello, my name is Christian Rudder, and I was one of the founders of OkCupid. It's now one of the biggest dating sites in the United States. Like most everyone at the site, I was a math major, As you may expect, we're known for the analytic approach we take to love. We call it our matching algorithm. Basically, OkCupid's matching algorithm helps us decide whether two people should go on a date. We built our entire business around it. Now, algorithm is a fancy word, and people like to drop it like it's this big thing. But really, an algorithm is just a systematic, step-by-step way to solve a problem. It doesn't have to be fancy at all. Here in this lesson, I'm going to explain how we arrived at our particular algorithm, so you can see how it's done. Now, why are algorithms even important? Why does this lesson even exist? Well, notice one very significant phrase I used above: they are a step-by-step way to solve a problem, and as you probably know, computers excel at step-by-step processes. A computer without an algorithm is basically an expensive paperweight. And since computers are such a pervasive part of everyday life, algorithms are everywhere. The math behind OkCupid's matching algorithm is surprisingly simple. It's just some addition, multiplication, a little bit of square roots. The tricky part in designing it was figuring out how to take something mysterious, human attraction, and break it into components that a computer can work with. The first thing we needed to match people up was data, something for the algorithm to work with. The best way to get data quickly from people is to just ask for it. So we decided that OkCupid should ask users questions, stuff like, "Do you want to have kids one day?" "How often do you brush your teeth?" "Do you like scary movies?" And big stuff like, "Do you believe in God?" Now, a lot of the questions are good for matching like with like, that is, when both people answer the same way. For example, two people who are both into scary movies are probably a better match than one person who is and one who isn't. But what about a question like, "Do you like to be the center of attention?" If both people in a relationship are saying yes to this, they're going to have massive problems. We realized this early on, and so we decided we needed a bit more data from each question. We had to ask people to specify not only their own answer, but the answer they wanted from someone else. That worked really well. But we needed one more dimension. Some questions tell you more about a person than others. For example, a question about politics, something like, "Which is worse: book burning or flag burning?" might reveal more about someone than their taste in movies. And it doesn't make sense to weigh all things equally, so we added one final data point. For everything that OkCupid asks you, you have a chance to tell us the role it plays in your life. And this ranges from irrelevant to mandatory. So now, for every question, we have three things for our algorithm: first, your answer; second, how you want someone else -- your potential match -- to answer; and third, how important the question is to you at all. With all this information, OkCupid can figure out how well two people will get along. The algorithm crunches the numbers and gives us a result. As a practical example, let's look at how we'd match you with another person. Let's call him "B." Your match percentage with B is based on questions you've both answered. Let's call that set of common questions "s." As a very simple example, we use a small set "s" with just two questions in common, and compute a match from that. Here are our two example questions. The first one, let's say, is, "How messy are you?" And the answer possibilities are: very messy, average and very organized. And let's say you answered "very organized," and you'd like someone else to answer "very organized," and the question is very important to you. Basically, you're a neat freak. You're neat, you want someone else to be neat, and that's it. And let's say B is a little bit different. He answered "very organized" for himself, but "average" is OK with him as an answer from someone else, and the question is only a little important to him. Let's look at the second question, from our previous example: "Do you like to be the center of attention?" The answers are "yes" and "no." You've answered "no," you want someone else to answer "no," and the question is only a little important to you. Now B, he's answered "yes." He wants someone else to answer "no," because he wants the spotlight on him, and the question is somewhat important to him. So, let's try to compute all of this. Our first step is, since we use computers to do this, we need to assign numerical values to ideas like "somewhat important" and "very important," because computers need everything in numbers. We at OkCupid decided on the following scale: "Irrelevant" is worth 0. "A little important" is worth 1. "Somewhat important" is worth 10. "Very important" is 50. And "absolutely mandatory" is 250. Next, the algorithm makes two simple calculations. The first is: How much did B's answers satisfy you? That is, how many possible points did B score on your scale? Well, you indicated that B's answer to the first question, about messiness, was very important to you. It's worth 50 points and B got that right. The second question is worth only 1, because you said it was only a little important. B got that wrong, so B's answers were 50 out of 51 possible points. That's 98% satisfactory. Pretty good. The second question the algorithm looks at is: How much did you satisfy B? Well, B placed 1 point on your answer to the messiness question and 10 on your answer to the second. Of those 11, that's 1 plus 10, you earned 10 -- you guys satisfied each other on the second question. So your answers were 10 out of 11 equals 91 percent satisfactory to B. That's not bad. The final step is to take these two match percentages and get one number for the both of you. To do this, the algorithm multiplies your scores, then takes the nth root, where "n" is the number of questions. Because s, which is the number of questions in this sample, is only 2, we have: match percentage equals the square root of 98 percent times 91 percent. That equals 94 percent. That 94 percent is your match percentage with B. It's a mathematical expression of how happy you'd be with each other, based on what we know. Now, why does the algorithm multiply, as opposed to, say, average the two match scores together, and do the square-root business? In general, this formula is called the geometric mean. It's a great way to combine values that have wide ranges and represent very different properties. In other words, it's perfect for romantic matching. You've got wide ranges and you've got tons of different data points, like I said, about movies, politics, religion -- everything. Intuitively, too, this makes sense. Two people satisfying each other 50 percent should be a better match than two others who satisfy 0 and 100, because affection needs to be mutual. After adding a little correction for margin of error, in the case where we have a small number of questions, like we do in this example, we're good to go. Any time OkCupid matches two people, it goes through the steps we just outlined. First it collects data about your answers, then it compares your choices and preferences to other people's in simple, mathematical ways. This, the ability to take real-world phenomena and make them something a microchip can understand, is, I think, the most important skill anyone can have these days. Like you use sentences to tell a story to a person, you use algorithms to tell a story to a computer. If you learn the language, you can go out and tell your stories. I hope this will help you do that.
Hola, soy Christian Rudder y fui uno de los fundadores de OK Cupid. Hoy es uno de los sitios de citas más grande de Estados Unidos. Como casi todos en el sitio, tenía un título en matemáticas y, como era de esperar, éramos conocidos por el enfoque analítico que tenemos del amor. Le llamamos el algoritmo de compatibilidad. En esencia el algoritmo de compatibilidad de OK Cupid nos ayuda a decidir si dos personas debieran tener una cita. Sobre esa base construimos todo nuestro negocio. Ahora, algoritmo es una palabra pomposa y la gente tiende a ignorarla por ampulosa, pero en realidad, un algoritmo es solo una forma sistemática de resolver problemas paso a paso. No tiene que ser nada pomposo. Aquí en esta lección, explicaré cómo concebimos nuestro algoritmo, así lo podrás entender. Ahora, ¿por qué son importantes los algoritmos? ¿Para qué existe esta lección? Bueno, nota una frase muy significativa que usé arriba: una forma de resolver problemas paso a paso, y como probablemente sepas, las computadoras se lucen en los procesos paso a paso. Una computadora sin un algoritmo es en esencia un pisapapeles caro. Y dado que las computadoras son una parte tan dominante de la vida cotidiana, los algoritmos están dondequiera. La matemática subyacente al algoritmo de compatibilidad de OK Cupid es sorprendentemente sencilla. Son solo unas sumas, multiplicaciones, y unas cuantas raíces cuadradas. Aunque el truco de diseño estaba en averiguar cómo tomar algo tan misterioso, como la atracción humana, y separarlo en sus componentes para que una computadora pueda trabajar con ellos. Bueno, lo primero que necesitamos para aparejar personas son datos, algo que el algoritmo necesita. El mejor modo de conseguir datos de la gente es simplemente preguntando. Así, decidimos que OK Cupid debería preguntar a los usuarios cosas como, "¿quieres tener hijos algún día?" y "¿con qué frecuencia te cepillas los dientes?", "¿te gustan las películas de terror?", y grandes temas como: "¿Crees en Dios?" Ahora, muchas de las preguntas son buenas para aparear entre iguales, es decir cuando ambas personas contestan igual. Por ejemplo, dos personas a las que les gustan las películas de terror probablemente hacen mejor pareja que una persona que le gusta y otra que no. Pero qué pasa con una pregunta como, "¿te gusta ser el centro de atención?" Si ambos en una relación dicen que sí, entonces tendremos problemas grandes. Pronto nos dimos cuenta de esto, así que decidimos que necesitábamos un poco más de datos para cada pregunta. Teníamos que pedir que especificaran no solo su propia respuesta, sino la respuesta que querían del otro. Eso funcionó muy bien, pero necesitamos una dimensión más. Algunas preguntas dicen más de una persona que otras. Por ejemplo, una pregunta de política, algo como, "¿qué es peor: quemar un libro o una bandera?", puede revelar más de alguien que su gusto fílmico. Y no tiene sentido ponderar todo por igual, así que sumamos un punto final de datos. Por cada cosa que pregunta OK Cupid, tienen una oportunidad de decirnos el rol que juega en sus vidas, y esto varía desde lo irrelevante a lo obligatorio. Ahora pues, por cada pregunta, tenemos tres cosas para nuestro algoritmo: primero, tu respuesta; segundo, cómo quieres que el otro, tu pareja potencial, responda; y tercero, qué tan importante es la pregunta para ti. Con toda esta información, OO Cupid puede averiguar qué tan bien se llevarán dos personas. El algoritmo desmenuza los números y les da un resultado. Como un ejemplo práctico, veamos cómo te apareamos con otra persona, que llamaremos "B". Tu porcentaje de compatibilidad con B se basa en preguntas que ambos respondieron. Que llamaremos el conjunto de preguntas comunes, "s". Como un ejemplo muy sencillo, usaremos un conjunto pequeño "s" con solo dos preguntas en común y calcularemos de eso, una pareja. He aquí nuestros dos preguntas ejemplo. La primera, digamos, "¿qué tan desordenado eres?" y las posibles respuestas son: muy desordenado, promedio y muy ordenado. Digamos que contestas "muy ordenado", y quisieras a alguien que conteste, "muy ordenado", y la preguntas es muy importante para ti. En suma tienes manía por el orden. Eres ordenada, quieres a alguien ordenado, sin más. Digamos que B es un poquito diferente. Responde que es muy ordenado consigo mismo pero promedio le parece bien como respuesta del otro. Y la pregunta le es poco relevante. Miremos la segunda pregunta, es la del ejemplo anterior: "¿te gusta ser el centro de atención?" Las respuestas son sí y no. Ahora si contestas "no", cómo quieres que sea el "no" del otro. Y la pregunta tiene poca relevancia para ti. Ahora B, contesta "sí", quiere a alguien que conteste "no", porque quiere destacarse, y la pregunta le es relevante. Intentemos calcular todo esto. Nuestro primer paso es, dado que usamos computadoras, necesitamos asignar valores numéricos a ideas como "algo importante" y "muy importante" porque las computadoras necesitan todo en números. Nosotros en OK Cupid elegimos la siguiente escala: irrelevante equivale a 0, un poco importante equivale a 1, algo importante equivale a 10, muy importante equivale a 50, y es absolutamente obligatorio a 250. Siguiente paso, el algoritmo hace dos simples cálculos. El primero es qué tanto te gustaron las respuestas de B, esto es, ¿cuántos puntos posibles obtuvo B en tu escala? Bueno, tú indicaste que la respuesta de B a la primera pregunta sobre el desorden era muy importante para ti. Lo que equivale a 50 puntos y B acertó. La segunda pregunta equivale solo a 1 porque dijiste que era solo poco relevante, y B la tiene mal. Así, las respuestas de B fueron 50 de 51 puntos posibles. Esto es 98 % satisfactorio, lo cual es bastante bueno. Y la segunda pregunta del algoritmo ve qué tanto le satisfaces a B. Bueno, B te dio 1 punto en tu respuesta a la pregunta del desorden y 10 en la respuesta a la segunda. De esos 11, es decir 1 más 10, te ganaste 10, de la segunda pregunta ambos están satisfechos entre sí. Entonces sus respuestas fueron 10 de 11 que equivale al 91% de satisfacción para B. No está mal. El paso final es tomar estos dos porcentajes de compatibilidad y obtener un número para ambos. Para hacer esto, el algoritmo multiplica sus resultados, hace la raíz de n, donde n es el número de preguntas. Dado que s, es el número de preguntas, en este ejemplo, es solamente 2, tenemos porcentajes de compatibilidad que equivalen a la raíz cuadrada de 98 % por 91 %, que equivale a 94 %. Este 94 % es tu porcentaje de compatibilidad con B. Es una expresión matemática de qué tan feliz serían entre sí con base a lo que sabemos. Ahora bien, ¿por qué el algoritmo se multiplica opuesto a, digamos, el promedio de los dos resultados de compatibilidad juntos y por qué la raíz cuadrada? En general, esta fórmula se llama media geométrica, que es un gran camino para combinar valores que tienen rangos amplios y representan propiedades muy diferentes. Es decir, es perfecto para relaciones románticas. Tenemos rangos amplios y tenemos toneladas de datos diferentes, como dije, de películas, de política, de religión, de todo. Intuitivamente, a su vez, tiene sentido. Dos personas que se satisfecen en 50 % a la otra debieran ser una mejor pareja que otros dos que se satisfacen entre 0 y 100, porque el afecto necesita ser mutuo. Pero sumando una pequeña corrección de margen de error, en el caso que haya una pequeña cantidad de preguntas, como hicimos en este ejemplo, estamos listos para salir. Cada vez que OK Cupid junta a dos personas, prosigue con los pasos que acabamos de esbozar. Primero se recolectan los datos de sus respuestas, luego se comparan sus elecciones y preferencias con las de otros en modo simple y matemático. Esto, la habilidad de tomar fenómenos del mundo real y hacer que un microchip los pueda entender, es, creo, la destreza más importante que uno puede tener en la actualidad. Así como usas oraciones para contar una historia a una persona, usas algoritmos para contar una historia a una computadora. Si aprendes el lenguaje, puedes salir y contar tus historias. Espero que esto te sirva para hacerlo.