Docsity

Collective Intelligence, Summaries of Computer Engineering and Programming

Partial preview of the text

Download Collective Intelligence and more Summaries Computer Engineering and Programming in PDF only on Docsity!

Praise for Programming Collective Intelligence

“I review a few books each year, and naturally, I read a fair number during the course of my work. And I have to admit that I have never had quite as much fun reading a preprint of a book as I have in reading this. Bravo! I cannot think of a better way for a developer to first learn these algorithms and methods, nor can I think of a better way for me (an old AI dog) to reinvigorate my knowledge of the details.” — Dan Russell, Uber Tech Lead, Google

“Toby’s book does a great job of breaking down the complex subject matter of machine- learning algorithms into practical, easy-to-understand examples that can be used directly to analyze social interaction across the Web today. If I had this book two years ago, it would have saved me precious time going down some fruitless paths.” — Tim Wolters, CTO, Collective Intellect

“ Programming Collective Intelligence is a stellar achievement in providing a comprehensive collection of computational methods for relating vast amounts of data. Specifically, it applies these techniques in context of the Internet, finding value in otherwise isolated data islands. If you develop for the Internet, this book is a must-have.” — Paul Tyma, Senior Software Engineer, Google

Programming Collective Intelligence

Other resources from O’Reilly

Related titles Web 2.0 Report Learning Python Mastering Algorithms with C

AI for Game Developers Mastering Algorithms with Perl

oreilly.com oreilly.com is more than a complete catalog of O’Reilly books. You’ll also find links to news, events, articles, weblogs, sample chapters, and code examples.

oreillynet.com is the essential portal for developers interested in open and emerging technologies, including new platforms, pro- gramming languages, and operating systems.

Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in document- ing the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit conferences.oreilly.com for our upcoming events.

Safari Bookshelf ( safari.oreilly.com ) is the premier online refer- ence library for programmers and IT professionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or sim- ply flip to the page you need. Try it today for free.

Programming Collective Intelligence by Toby Segaran

Copyright © 2007 Toby Segaran. All rights reserved. Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( safari.oreilly.com ). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected].

Editor: Mary Treseler O’Brien Production Editor: Sarah Schneider Copyeditor: Amy Thomson Proofreader: Sarah Schneider

Indexer: Julie Hawks Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrators: Robert Romano and Jessamyn Read

Printing History:

August 2007: First Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming Collective Intelligence , the image of King penguins, and related trade dress are trademarks of O’Reilly Media, Inc.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps.

While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

This book uses RepKover™, a durable and flexible lay-flat binding.

ISBN-10: 0-596-52932- ISBN-13: 978-0-596-52932- [M]

vii

Table of Contents

    1. Introduction to Collective Intelligence Preface xiii
    • What Is Collective Intelligence?
    • What Is Machine Learning?
    • Limits of Machine Learning
    • Real-Life Examples
    • Other Uses for Learning Algorithms
    1. Making Recommendations
    • Collaborative Filtering
    • Collecting Preferences
    • Finding Similar Users
    • Recommending Items
    • Matching Products
    • Building a del.icio.us Link Recommender
    • Item-Based Filtering
    • Using the MovieLens Dataset
    • User-Based or Item-Based Filtering?
    • Exercises
    1. Discovering Groups
    • Supervised versus Unsupervised Learning
    • Word Vectors
    • Hierarchical Clustering
    • Drawing the Dendrogram
    • Column Clustering
    • K-Means Clustering viii | Table of Contents
    • Clusters of Preferences
    • Viewing Data in Two Dimensions
    • Other Things to Cluster
    • Exercises
    1. Searching and Ranking
    • What’s in a Search Engine?
    • A Simple Crawler
    • Building the Index
    • Querying
    • Content-Based Ranking
    • Using Inbound Links
    • Learning from Clicks
    • Exercises
    1. Optimization
    • Group Travel
    • Representing Solutions
    • The Cost Function
    • Random Searching
    • Hill Climbing
    • Simulated Annealing
    • Genetic Algorithms
    • Real Flight Searches
    • Optimizing for Preferences
    • Network Visualization
    • Other Possibilities
    • Exercises
    1. Document Filtering
    • Filtering Spam
    • Documents and Words
    • Training the Classifier
    • Calculating Probabilities
    • A Naïve Classifier
    • The Fisher Method
    • Persisting the Trained Classifiers
    • Filtering Blog Feeds
    • Improving Feature Detection Table of Contents | ix
    • Using Akismet
    • Alternative Methods
    • Exercises
    1. Modeling with Decision Trees
    • Predicting Signups
    • Introducing Decision Trees
    • Training the Tree
    • Choosing the Best Split
    • Recursive Tree Building
    • Displaying the Tree
    • Classifying New Observations
    • Pruning the Tree
    • Dealing with Missing Data
    • Dealing with Numerical Outcomes
    • Modeling Home Prices
    • Modeling “Hotness”
    • When to Use Decision Trees
    • Exercises
    1. Building Price Models
    • Building a Sample Dataset
    • k-Nearest Neighbors
    • Weighted Neighbors
    • Cross-Validation
    • Heterogeneous Variables
    • Optimizing the Scale
    • Uneven Distributions
    • Using Real Data—the eBay API
    • When to Use k-Nearest Neighbors
    • Exercises
    1. Advanced Classification: Kernel Methods and SVMs
    • Matchmaker Dataset
    • Difficulties with the Data
    • Basic Linear Classification
    • Categorical Features
    • Scaling the Data
    • Understanding Kernel Methods x | Table of Contents
    • Support-Vector Machines
    • Using LIBSVM
    • Matching on Facebook
    • Exercises
    1. Finding Independent Features
    • A Corpus of News
    • Previous Approaches
    • Non-Negative Matrix Factorization
    • Displaying the Results
    • Using Stock Market Data
    • Exercises
    1. Evolving Intelligence
    • What Is Genetic Programming?
    • Programs As Trees
    • Creating the Initial Population
    • Testing a Solution
    • Mutating Programs
    • Crossover
    • Building the Environment
    • A Simple Game
    • Further Possibilities
    • Exercises
    1. Algorithm Summary
    • Bayesian Classifier
    • Decision Tree Classifier
    • Neural Networks
    • Support-Vector Machines
    • k-Nearest Neighbors
    • Clustering
    • Multidimensional Scaling
    • Non-Negative Matrix Factorization
    • Optimization

xiii

Preface 1

The increasing number of people contributing to the Internet, either deliberately or incidentally, has created a huge set of data that gives us millions of potential insights into user experience, marketing, personal tastes, and human behavior in general. This book provides an introduction to the emerging field of collective intelligence. It covers ways to get hold of interesting datasets from many web sites you’ve probably heard of, ideas on how to collect data from users of your own applications, and many different ways to analyze and understand the data once you’ve found it.

This book’s goal is to take you beyond simple database-backed applications and teach you how to write smarter programs to take advantage of the information you and others collect every day.

Prerequisites

The code examples in this book are written in Python, and familiarity with Python programming will help, but I provide explanations of all the algorithms so that pro- grammers of other languages can follow. The Python code will be particularly easy to follow for those who know high-level languages like Ruby or Perl. This book is not intended as a guide for learning programming, so it’s important that you’ve done enough coding to be familiar with the basic concepts. If you have a good understand- ing of recursion and some basic functional programming, you’ll find the material even easier.

This book does not assume you have any prior knowledge of data analysis, machine learning, or statistics. I’ve tried to explain mathematical concepts in as simple a manner as possible, but having some knowledge of trigonometry and basic statistics will be help you understand the algorithms.

Preface | xv

implement one may use a different paradigm than another. Sometimes it’s use- ful to pass around functions as parameters and other times to capture state in an object. Python supports both approaches.

Multiplatform and free Python has a single reference implementation for all the major platforms and is free for all of them. The code described in this book will work on Windows, Linux, and Macintosh.

Python Tips

For beginners interested in learning about programming in Python, I recommend reading Learning Python by Mark Lutz and David Ascher (O’Reilly), which gives an excellent overview. Programmers of other languages should find the Python code rel- atively easy to follow, although be aware that throughout this book I use some of Python’s idiosyncratic syntax because it lets me more directly express the algorithm or fundamental concepts. Here’s a quick overview for those of you who aren’t Python programmers:

List and dictionary constructors

Python has a good set of primitive types and two that are used heavily throughout this book are list and dictionary. A list is an ordered list of any type of value, and it is constructed with square brackets:

number_list=[1,2,3,4] string_list=['a', 'b', 'c', 'd'] mixed_list=['a', 3, 'c', 8]

A dictionary is an unordered set of key/value pairs, similar to a hash map in other languages. It is constructed with curly braces:

ages={'John':24,'Sarah':28,'Mike':31}

The elements of lists and dictionaries can be accessed using square brackets after the list name:

string_list[2] # returns 'b' ages['Sarah'] # returns 28

Significant Whitespace

Unlike most languages, Python actually uses the indentation of the code to define code blocks. Consider this snippet:

if x==1: print 'x is 1' print 'Still in if block' print 'outside if block'

xvi | Preface

The interpreter knows that the first two print statements are executed when x is 1 because the code is indented. Indentation can be any number of spaces, as long as it is consistent. This book uses two spaces for indentation. When entering the code you’ll need to be careful to copy the indentation correctly.

List comprehensions

A list comprehension is a convenient way of converting one list to another by filtering and applying functions to it. A list comprehension is written as:

[ expression for variable in list ]

or:

[ expression for variable in list if condition ]

For example, the following code:

l1=[1,2,3,4,5,6,7,8,9] print [v*10 for v in l1 if v1>4]

would print this list:

[50,60,70,80,90]

List comprehensions are used frequently in this book because they are an extremely concise way to apply a function to an entire list or to remove bad items. The other manner in which they are often used is with the dict constructor:

l1=[1,2,3,4,5,6,7,8,9] timesten=dict([(v,v*10) for v in l1])

This code will create a dictionary with the original list being the keys and each item multiplied by 10 as the value:

{1:10,2:20,3:30,4:40,5:50,6:60,7:70,8:80,9:90}

Open APIs

The algorithms for synthesizing collective intelligence require data from many users. In addition to machine-learning algorithms, this book discusses a number of Open Web APIs (application programming interfaces). These are ways that companies allow you to freely access data from their web sites by means of a specified protocol; you can then write programs that download and process the data. This data usually consists of contributions from the site’s users, which can be mined for new insights. In some cases, there is a Python library available to access these APIs; if not, it’s pretty straightforward to create your own interface to access the data using Python’s built-in libraries for downloading data and parsing XML.

Here are some of the web sites with open APIs that you’ll see in this book:

xviii | Preface

Chapter 4, Searching and Ranking Describes the various parts of a search engine including the crawler, indexer, and query engine. It covers the PageRank algorithm for scoring pages based on inbound links and shows you how to create a neural network that learns which keywords are associated with different results.

Chapter 5, Optimization Introduces algorithms for optimization , which are designed to search millions of possible solutions to a problem and choose the best one. The wide variety of uses for these algorithms is demonstrated with examples that find the best flights for a group of people traveling to the same location, find the best way of match- ing students to dorms, and lay out a network with the minimum number of crossed lines. Chapter 6, Document Filtering Demonstrates Bayesian filtering , which is used in many free and commercial spam filters for automatically classifying documents based on the type of words and other features that appear in the document. This is applied to a set of RSS search results to demonstrate automatic classification of the entries.

Chapter 7, Modeling with Decision Trees Introduces decision trees as a method not only of making predictions, but also of modeling the way the decisions are made. The first decision tree is built with hypothetical data from server logs and is used to predict whether or not a user is likely to become a premium subscriber. The other examples use data from real web sites to model real estate prices and “hotness.”

Chapter 8, Building Price Models Approaches the problem of predicting numerical values rather than classifica- tions using k-nearest neighbors techniques, and applies the optimization algorithms from Chapter 5. These methods are used in conjunction with the eBay API to build a system for predicting eventual auction prices for items based on a set of properties.

Chapter 9, Advanced Classification: Kernel Methods and SVMs Shows how support-vector machines can be used to match people in online dat- ing sites or when searching for professional contacts. Support-vector machines are a fairly advanced technique and this chapter compares them to other methods.

Chapter 10, Finding Independent Features Introduces a relatively new technique called non-negative matrix factorization , which is used to find the independent features in a dataset. In many datasets the items are constructed as a composite of different features that we don’t know in advance; the idea here is to detect these features. This technique is demon- strated on a set of news articles, where the stories themselves are used to detect themes, one or more of which may apply to a given story.

Preface | xix

Chapter 11, Evolving Intelligence Introduces genetic programming , a very sophisticated set of techniques that goes beyond optimization and actually builds algorithms using evolutionary ideas to solve a particular problem. This is demonstrated by a simple game in which the computer is initially a poor player that improves its skill by improving its own code the more the game is played. Chapter 12, Algorithm Summary Reviews all the machine-learning and statistical algorithms described in the book and compares them to a set of artificial problems. This will help you understand how they work and visualize the way that each of them divides data. Appendix A, Third-Party Libraries Gives information on third-party libraries used in the book, such as where to find them and how to install them.

Appendix B, Mathematical Formulas Contains formulae, descriptions, and code for many of the mathematical concepts introduced throughout the book.

Exercises at the end of each chapter give ideas of ways to extend the algorithms and make them more powerful.

Conventions

The following typographical conventions are used in this book:

Plain text Indicates menu titles, menu options, menu buttons, and keyboard accelerators (such as Alt and Ctrl). Italic Indicates new terms, URLs, email addresses, filenames, file extensions, path- names, directories, and Unix utilities.

Constant width Indicates commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, macros, the contents of files, or the output from commands. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values.

This icon signifies a tip, suggestion, or general note.