Mahout 简明教程
Mahout - Introduction
我们生活在一个信息无限丰富的时代。信息过载已达到如此高的程度,以至于有时管理我们的小小邮箱都变得困难!想象一下 Facebook、Twitter 和 Youtube 等一些流行网站必须每天收集和管理的数据和记录量。即使是鲜为人知的网站也会收到大量信息也不是什么新鲜事。
We are living in a day and age where information is available in abundance. The information overload has scaled to such heights that sometimes it becomes difficult to manage our little mailboxes! Imagine the volume of data and records some of the popular websites (the likes of Facebook, Twitter, and Youtube) have to collect and manage on a daily basis. It is not uncommon even for lesser known websites to receive huge amounts of information in bulk.
通常,我们会使用数据挖掘算法来分析大量数据以识别趋势并得出结论。但是,没有哪种数据挖掘算法能够高效地处理非常大型的数据集并快速提供结果,除非计算任务在分布在云端的多台机器上运行。
Normally we fall back on data mining algorithms to analyze bulk data to identify trends and draw conclusions. However, no data mining algorithm can be efficient enough to process very large datasets and provide outcomes in quick time, unless the computational tasks are run on multiple machines distributed over the cloud.
我们现在有了能够将计算任务分解成多个部分并让这些部分在不同机器上运行的新框架。 Mahout 就是这样的一个数据挖掘框架,通常与 Hadoop 基础设施结合在背景下运行,用于管理海量的数据。
We now have new frameworks that allow us to break down a computation task into multiple segments and run each segment on a different machine. Mahout is such a data mining framework that normally runs coupled with the Hadoop infrastructure at its background to manage huge volumes of data.
What is Apache Mahout?
马豪特是训象者。名称源自其与使用大象作为其标志的 Apache Hadoop 的紧密关联。
A mahout is one who drives an elephant as its master. The name comes from its close association with Apache Hadoop which uses an elephant as its logo.
Hadoop 是 Apache 的开源框架,它允许使用简单的编程模型在计算机集群的分布式环境中存储和处理大数据。
Hadoop is an open-source framework from Apache that allows to store and process big data in a distributed environment across clusters of computers using simple programming models.
Apache Mahout 是一个开源项目,主要用于创建可扩展的机器学习算法。它实现了流行的机器学习技术,例如:
Apache Mahout is an open source project that is primarily used for creating scalable machine learning algorithms. It implements popular machine learning techniques such as:
-
Recommendation
-
Classification
-
Clustering
Apache Mahout 于 2008 年作为 Apache Lucene 的子项目启动。2010 年,Mahout 成为 Apache 的一个顶级项目。
Apache Mahout started as a sub-project of Apache’s Lucene in 2008. In 2010, Mahout became a top level project of Apache.
Features of Mahout
以下列出了 Apache Mahout 的基本功能。
The primitive features of Apache Mahout are listed below.
-
The algorithms of Mahout are written on top of Hadoop, so it works well in distributed environment. Mahout uses the Apache Hadoop library to scale effectively in the cloud.
-
Mahout offers the coder a ready-to-use framework for doing data mining tasks on large volumes of data.
-
Mahout lets applications to analyze large sets of data effectively and in quick time.
-
Includes several MapReduce enabled clustering implementations such as k-means, fuzzy k-means, Canopy, Dirichlet, and Mean-Shift.
-
Supports Distributed Naive Bayes and Complementary Naive Bayes classification implementations.
-
Comes with distributed fitness function capabilities for evolutionary programming.
-
Includes matrix and vector libraries.
Applications of Mahout
-
Companies such as Adobe, Facebook, LinkedIn, Foursquare, Twitter, and Yahoo use Mahout internally.
-
Foursquare helps you in finding out places, food, and entertainment available in a particular area. It uses the recommender engine of Mahout.
-
Twitter uses Mahout for user interest modelling.
-
Yahoo! uses Mahout for pattern mining.
Mahout - Machine Learning
Apache Mahout 是一个高度可扩展的机器学习库,使开发人员能够使用经过优化的算法。Mahout 实现了流行的机器学习技术,例如推荐、分类和聚类。因此,在继续深入之前,有必要简要了解一下机器学习。
Apache Mahout is a highly scalable machine learning library that enables developers to use optimized algorithms. Mahout implements popular machine learning techniques such as recommendation, classification, and clustering. Therefore, it is prudent to have a brief section on machine learning before we move further.
What is Machine Learning?
机器学习是计算机科学的一个分支,它通过编程系统的方式使其能够通过经验自动学习和改进。这里的学习是指识别和理解输入数据,并根据所提供的数据做出明智的决策。
Machine learning is a branch of science that deals with programming the systems in such a way that they automatically learn and improve with experience. Here, learning means recognizing and understanding the input data and making wise decisions based on the supplied data.
根据所有可能的输入迎合所有决策非常困难。为了解决这个问题,开发了算法。这些算法根据特定的数据和过去经验以及统计学、概率论、逻辑学、组合优化、搜索、强化学习和控制论的原则来构建知识。
It is very difficult to cater to all the decisions based on all possible inputs. To tackle this problem, algorithms are developed. These algorithms build knowledge from specific data and past experience with the principles of statistics, probability theory, logic, combinatorial optimization, search, reinforcement learning, and control theory.
已开发的算法形成各种应用的基础,如:
The developed algorithms form the basis of various applications such as:
-
Vision processing
-
Language processing
-
Forecasting (e.g., stock market trends)
-
Pattern recognition
-
Games
-
Data mining
-
Expert systems
-
Robotics
机器学习是一个广阔的领域,涵盖其所有功能超出了本教程的范围。有多种方法可用于实现机器学习技术,但最常用的方法是 supervised 和 unsupervised learning 。
Machine learning is a vast area and it is quite beyond the scope of this tutorial to cover all its features. There are several ways to implement machine learning techniques, however the most commonly used ones are supervised and unsupervised learning.
Supervised Learning
监督学习涉及从可用的训练数据中学习函数。监督学习算法分析训练数据并生成一个推断函数,该函数可用于映射新示例。监督学习的常见示例包括:
Supervised learning deals with learning a function from available training data. A supervised learning algorithm analyzes the training data and produces an inferred function, which can be used for mapping new examples. Common examples of supervised learning include:
-
classifying e-mails as spam,
-
labeling webpages based on their content, and
-
voice recognition.
有许多监督学习算法,例神经网络、支持向量机 (SVM) 和朴素贝叶斯分类器。Mahout 实现了朴素贝叶斯分类器。
There are many supervised learning algorithms such as neural networks, Support Vector Machines (SVMs), and Naive Bayes classifiers. Mahout implements Naive Bayes classifier.
Unsupervised Learning
无监督学习可以理解未标记数据,而无需任何预定义的数据集进行训练。无监督学习是一种非常强大的工具,可用于分析可用数据并查找模式和趋势。它最常用于将相似的输入聚类到逻辑组中。无监督学习的常见方法包括:
Unsupervised learning makes sense of unlabeled data without having any predefined dataset for its training. Unsupervised learning is an extremely powerful tool for analyzing available data and look for patterns and trends. It is most commonly used for clustering similar input into logical groups. Common approaches to unsupervised learning include:
-
k-means
-
self-organizing maps, and
-
hierarchical clustering
Recommendation
推荐是一种流行的技术,它根据用户的购买记录、点击和评级等信息提供密切的建议。
Recommendation is a popular technique that provides close recommendations based on user information such as previous purchases, clicks, and ratings.
-
Amazon uses this technique to display a list of recommended items that you might be interested in, drawing information from your past actions. There are recommender engines that work behind Amazon to capture user behavior and recommend selected items based on your earlier actions.
-
Facebook uses the recommender technique to identify and recommend the “people you may know list”.

Classification
分类也称为 categorization ,是一种机器学习技术,该技术使用已知数据确定如何将新数据分类到一组现有类别中。分类是一种监督学习形式。
Classification, also known as categorization, is a machine learning technique that uses known data to determine how the new data should be classified into a set of existing categories. Classification is a form of supervised learning.
-
Mail service providers such as Yahoo! and Gmail use this technique to decide whether a new mail should be classified as a spam. The categorization algorithm trains itself by analyzing user habits of marking certain mails as spams. Based on that, the classifier decides whether a future mail should be deposited in your inbox or in the spams folder.
-
iTunes application uses classification to prepare playlists.

Clustering
聚类用于根据共同特征形成相似数据的组或群集。聚类是一种无监督学习形式。
Clustering is used to form groups or clusters of similar data based on common characteristics. Clustering is a form of unsupervised learning.
-
Search engines such as Google and Yahoo! use clustering techniques to group data with similar characteristics.
-
Newsgroups use clustering techniques to group various articles based on related topics.
聚类引擎会完全遍历输入数据,并根据数据的特征决定将其归入哪个群集中。请看以下示例。
The clustering engine goes through the input data completely and based on the characteristics of the data, it will decide under which cluster it should be grouped. Take a look at the following example.

我们的教程库中包含各种主题。我们收到 TutorialsPoint 中的新教程时,它将由聚类引擎进行处理,基于其内容决定将其分组到何处。
Our library of tutorials contains topics on various subjects. When we receive a new tutorial at TutorialsPoint, it gets processed by a clustering engine that decides, based on its content, where it should be grouped.
Mahout - Environment
本章将教你如何设置 Mahout。Java 和 Hadoop 是 Mahout 的先决条件。以下是下载并安装 Java、Hadoop 和 Mahout 的步骤。
This chapter teaches you how to setup mahout. Java and Hadoop are the prerequisites of mahout. Below given are the steps to download and install Java, Hadoop, and Mahout.
Pre-Installation Setup
在将 Hadoop 安装到 Linux 环境之前,我们需要使用 ssh (安全外壳)设置 Linux。按照以下步骤设置 Linux 环境。
Before installing Hadoop into Linux environment, we need to set up Linux using ssh (Secure Shell). Follow the steps mentioned below for setting up the Linux environment.
Creating a User
建议为 Hadoop 创建一个独立用户,以将 Hadoop 文件系统与 Unix 文件系统隔离。请按照以下步骤创建用户:
It is recommended to create a separate user for Hadoop to isolate the Hadoop file system from the Unix file system. Follow the steps given below to create a user:
-
Open root using the command “su”.
. Create a user from the root account using the command “useradd username”.
-
Now you can open an existing user account using the command “su username”.
-
Open the Linux terminal and type the following commands to create a user.
$ su
password:
# useradd hadoop
# passwd hadoop
New passwd:
Retype new passwd
SSH Setup and Key Generation
执行群集上的不同操作(如启动、停止和分布式守护程序 shell 操作)需要进行 SSH 设置。为了对 Hadoop 的不同用户进行身份验证,需要为 Hadoop 用户提供公钥/私钥对并将其与不同的用户共享。
SSH setup is required to perform different operations on a cluster such as starting, stopping, and distributed daemon shell operations. To authenticate different users of Hadoop, it is required to provide public/private key pair for a Hadoop user and share it with different users.
以下命令用于使用 SSH 生成密钥值对,将公钥 id_rsa.pub 复制到 authorized_keys,并分别为 authorized_keys 文件提供所有者、读取和写入权限。
The following commands are used to generate a key value pair using SSH, copy the public keys form id_rsa.pub to authorized_keys, and provide owner, read and write permissions to authorized_keys file respectively.
$ ssh-keygen -t rsa
$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
$ chmod 0600 ~/.ssh/authorized_keys
Installing Java
Java 是 Hadoop 和 HBase 的主要先决条件。首先,你应该使用 “java -version” 验证系统中是否存在 Java。Java version 命令的语法如下。
Java is the main prerequisite for Hadoop and HBase. First of all, you should verify the existence of Java in your system using “java -version”. The syntax of Java version command is given below.
$ java -version
它应该生成以下输出。
It should produce the following output.
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b13)
Java HotSpot(TM) Client VM (build 25.0-b02, mixed mode)
如果你的系统中未安装 Java,请按照以下步骤安装 Java。
If you don’t have Java installed in your system, then follow the steps given below for installing Java.
Step 1
Step 1
访问以下链接下载 java (JDK <最新版本> - X64.tar.gz) : Oracle
Download java (JDK <latest version> - X64.tar.gz) by visiting the following link: Oracle
然后 jdk-7u71-linux-x64.tar.gz is downloaded 到你的系统。
Then jdk-7u71-linux-x64.tar.gz is downloaded onto your system.
Step 2
Step 2
通常情况下,你会在下载文件夹中找到下载的 Java 文件。使用以下命令验证并解压 jdk-7u71-linux-x64.gz 文件。
Generally, you find the downloaded Java file in the Downloads folder. Verify it and extract the jdk-7u71-linux-x64.gz file using the following commands.
$ cd Downloads/
$ ls
jdk-7u71-linux-x64.gz
$ tar zxf jdk-7u71-linux-x64.gz
$ ls
jdk1.7.0_71 jdk-7u71-linux-x64.gz
Step 3
Step 3
为了使所有用户可以使用 Java,你需要将其移动到 “/usr/local/”位置。打开 root,然后键入以下命令。
To make Java available to all the users, you need to move it to the location “/usr/local/”. Open root, and type the following commands.
$ su
password:
# mv jdk1.7.0_71 /usr/local/
# exit
Step 4
Step 4
要设置 PATH 和 JAVA_HOME 变量,请将以下命令添加到 ~/.bashrc file 中。
For setting up PATH and JAVA_HOME variables, add the following commands to ~/.bashrc file.
export JAVA_HOME=/usr/local/jdk1.7.0_71
export PATH= $PATH:$JAVA_HOME/bin
现在,如上所述,从终端验证 java -version 命令。
Now, verify the java -version command from terminal as explained above.
Downloading Hadoop
安装 Java 后,你需要首先安装 Hadoop。使用如下所示的 “Hadoop version” 命令验证 Hadoop 的存在。
After installing Java, you need to install Hadoop initially. Verify the existence of Hadoop using “Hadoop version” command as shown below.
hadoop version
它应生成以下输出:
It should produce the following output:
Hadoop 2.6.0
Compiled by jenkins on 2014-11-13T21:10Z
Compiled with protoc 2.5.0
From source with checksum 18e43357c8f927c0695f1e9522859d6a
This command was run using /home/hadoop/hadoop/share/hadoop/common/hadoopcommon-2.6.0.jar
如果你的系统无法找到 Hadoop,请下载 Hadoop 并安装在你的系统上。按照以下给出的命令操作。
If your system is unable to locate Hadoop, then download Hadoop and have it installed on your system. Follow the commands given below to do so.
使用以下命令从 Apache 软件基础下载并解压 hadoop-2.6.0。
Download and extract hadoop-2.6.0 from apache software foundation using the following commands.
$ su
password:
# cd /usr/local
# wget http://mirrors.advancedhosters.com/apache/hadoop/common/hadoop-
2.6.0/hadoop-2.6.0-src.tar.gz
# tar xzf hadoop-2.6.0-src.tar.gz
# mv hadoop-2.6.0/* hadoop/
# exit
Installing Hadoop
在任何必需的模式下安装 Hadoop。这里,我们正在以伪分布式模式演示 HBase 的功能,因此请以伪分布式模式安装 Hadoop。
Install Hadoop in any of the required modes. Here, we are demonstrating HBase functionalities in pseudo-distributed mode, therefore install Hadoop in pseudo-distributed mode.
按照下方给出的步骤将 Hadoop 2.4.1 安装在您的系统上。
Follow the steps given below to install Hadoop 2.4.1 on your system.
Step 1: Setting up Hadoop
您可以通过将以下命令追加到 ~/.bashrc 文件来设置 Hadoop 环境变量。
You can set Hadoop environment variables by appending the following commands to ~/.bashrc file.
export HADOOP_HOME=/usr/local/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin
export HADOOP_INSTALL=$HADOOP_HOME
现在,将所有更改应用于当前运行的系统。
Now, apply all changes into the currently running system.
$ source ~/.bashrc
Step 2: Hadoop Configuration
您可以在以下位置找到所有 Hadoop 配置文件:“$HADOOP_HOME/etc/hadoop”。根据 Hadoop 基础结构,需要对这些配置文件进行更改。
You can find all the Hadoop configuration files at the location “$HADOOP_HOME/etc/hadoop”. It is required to make changes in those configuration files according to your Hadoop infrastructure.
$ cd $HADOOP_HOME/etc/hadoop
为了在 Java 中开发 Hadoop 程序,您需要通过使用系统中 Java 的位置替换 JAVA_HOME 值在 hadoop-env.sh 文件中重置 Java 环境变量。
In order to develop Hadoop programs in Java, you need to reset the Java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of Java in your system.
export JAVA_HOME=/usr/local/jdk1.7.0_71
以下是您必须编辑以配置 Hadoop 的文件列表。
Given below are the list of files which you have to edit to configure Hadoop.
core-site.xml
core-site.xml
core-site.xml 文件包含诸如 Hadoop 实例使用的端口号、分配给文件系统、数据存储内存限制和读/写缓冲区大小等信息。
The core-site.xml file contains information such as the port number used for Hadoop instance, memory allocated for file system, memory limit for storing data, and the size of Read/Write buffers.
打开 core-site.xml 并将以下属性添加到 <configuration>、</configuration> 标记之间:
Open core-site.xml and add the following property in between the <configuration>, </configuration> tags:
<configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://localhost:9000</value>
</property>
</configuration>
hdfs-site.xm
hdfs-site.xm
hdfs-site.xml 文件包含有关复制数据的值、名称节点路径和本地文件系统的 DataNode 路径的信息。也就是说,您想将 Hadoop 基础架构存储在什么位置。
The hdfs-site.xml file contains information such as the value of replication data, namenode path, and datanode paths of your local file systems. It means the place where you want to store the Hadoop infrastructure.
让我们假设以下数据:
Let us assume the following data:
dfs.replication (data replication value) = 1
(In the below given path /hadoop/ is the user name.
hadoopinfra/hdfs/namenode is the directory created by hdfs file system.)
namenode path = //home/hadoop/hadoopinfra/hdfs/namenode
(hadoopinfra/hdfs/datanode is the directory created by hdfs file system.)
datanode path = //home/hadoop/hadoopinfra/hdfs/datanode
打开此文件,并在此文件中在 <configuration>、</configuration> 标记之间添加以下属性。
Open this file and add the following properties in between the <configuration>, </configuration> tags in this file.
<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
<property>
<name>dfs.name.dir</name>
<value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value>
</property>
<property>
<name>dfs.data.dir</name>
<value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value>
</property>
</configuration>
Note: 在上述文件中,所有属性值都是用户定义的。您可以根据自己的 Hadoop 基础结构进行更改。
Note: In the above file, all the property values are user defined. You can make changes according to your Hadoop infrastructure.
mapred-site.xml
mapred-site.xml
此文件用于将 yarn 配置到 Hadoop 中。打开 mapred-site.xml 文件,并在此文件的 <configuration>、</configuration> 标记之间添加以下属性。
This file is used to configure yarn into Hadoop. Open mapred-site.xml file and add the following property in between the <configuration>, </configuration> tags in this file.
<configuration>
<property>
<name>yarn.nodemanager.aux-services</name>
<value>mapreduce_shuffle</value>
</property>
</configuration>
mapred-site.xml
mapred-site.xml
此文件用于指定我们正在使用的哪个 MapReduce 框架。默认情况下,Hadoop 包含 mapred-site.xml 的模板。首先,需要使用以下命令将文件从 mapred-site.xml.template 复制到 mapred-site.xml 文件。
This file is used to specify which MapReduce framework we are using. By default, Hadoop contains a template of mapred-site.xml. First of all, it is required to copy the file from mapred-site.xml.template to mapred-site.xml file using the following command.
$ cp mapred-site.xml.template mapred-site.xml
打开 mapred-site.xml 文件,并在此文件中的 <configuration>、</configuration> 标记之间添加以下属性。
Open mapred-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file.
<configuration>
<property>
<name>mapreduce.framework.name</name>
<value>yarn</value>
</property>
</configuration>
Verifying Hadoop Installation
以下步骤用于验证 Hadoop 安装。
The following steps are used to verify the Hadoop installation.
Step 1: Name Node Setup
使用命令 “hdfs namenode -format” 设置名称节点,如下所示:
Set up the namenode using the command “hdfs namenode -format” as follows:
$ cd ~
$ hdfs namenode -format
预期结果如下:
The expected result is as follows:
10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG:
/************************************************************
STARTUP_MSG: Starting NameNode
STARTUP_MSG: host = localhost/192.168.1.11
STARTUP_MSG: args = [-format]
STARTUP_MSG: version = 2.4.1
...
...
10/24/14 21:30:56 INFO common.Storage: Storage directory
/home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted.
10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to retain
1 images with txid >= 0
10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0
10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG:
/************************************************************
SHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11
************************************************************/
Step 2: Verifying Hadoop dfs
以下命令用于启动 dfs。此命令将启动您的 Hadoop 文件系统。
The following command is used to start dfs. This command starts your Hadoop file system.
$ start-dfs.sh
预期的输出如下:
The expected output is as follows:
10/24/14 21:37:56
Starting namenodes on [localhost]
localhost: starting namenode, logging to /home/hadoop/hadoop-
2.4.1/logs/hadoop-hadoop-namenode-localhost.out
localhost: starting datanode, logging to /home/hadoop/hadoop-
2.4.1/logs/hadoop-hadoop-datanode-localhost.out
Starting secondary namenodes [0.0.0.0]
Step 3: Verifying Yarn Script
以下命令用于启动 yarn 脚本。执行此命令将启动您的 yarn 守护程序。
The following command is used to start yarn script. Executing this command will start your yarn demons.
$ start-yarn.sh
预期的输出如下:
The expected output is as follows:
starting yarn daemons
starting resource manager, logging to /home/hadoop/hadoop-2.4.1/logs/yarn-
hadoop-resourcemanager-localhost.out
localhost: starting node manager, logging to /home/hadoop/hadoop-
2.4.1/logs/yarn-hadoop-nodemanager-localhost.out
Downloading Mahout
可以在网站 Mahout 中找到 Mahout。从网站中提供的链接下载 Mahout。以下是网站的屏幕截图。
Mahout is available in the website Mahout. Download Mahout from the link provided in the website. Here is the screenshot of the website.

Step 1
使用以下命令从链接 https://mahout.apache.org/general/downloads 下载 Apache mahout。
Download Apache mahout from the link https://mahout.apache.org/general/downloads using the following command.
[Hadoop@localhost ~]$ wget
http://mirror.nexcess.net/apache/mahout/0.9/mahout-distribution-0.9.tar.gz
然后 mahout-distribution-0.9.tar.gz 将在您的系统中下载。
Then mahout-distribution-0.9.tar.gz will be downloaded in your system.
Maven Repository
以下是使用 Eclipse 构建 Apache Mahout 的 pom.xml。
Given below is the pom.xml to build Apache Mahout using Eclipse.
<dependency>
<groupId>org.apache.mahout</groupId>
<artifactId>mahout-core</artifactId>
<version>0.9</version>
</dependency>
<dependency>
<groupId>org.apache.mahout</groupId>
<artifactId>mahout-math</artifactId>
<version>${mahout.version}</version>
</dependency>
<dependency>
<groupId>org.apache.mahout</groupId>
<artifactId>mahout-integration</artifactId>
<version>${mahout.version}</version>
</dependency>
Mahout - Recommendation
本章涵盖了流行的机器学习技术 recommendation, 、其机制,以及如何编写实现 Mahout 推荐的应用程序。
This chapter covers the popular machine learning technique called recommendation, its mechanisms, and how to write an application implementing Mahout recommendation.
Recommendation
您是否曾想过亚马逊如何想出推荐的一系列商品,以此吸引您注意您可能感兴趣的特定产品!
Ever wondered how Amazon comes up with a list of recommended items to draw your attention to a particular product that you might be interested in!
假设您想从亚马逊购买“Mahout in Action”这本书:
Suppose you want to purchase the book “Mahout in Action” from Amazon:

除了所选产品,亚马逊还显示了一系列相关推荐商品,如下所示。
Along with the selected product, Amazon also displays a list of related recommended items, as shown below.

此类推荐列表借助于 recommender engines 生成。Mahout 提供了几种类型的推荐引擎,例如:
Such recommendation lists are produced with the help of recommender engines. Mahout provides recommender engines of several types such as:
-
user-based recommenders,
-
item-based recommenders, and
-
several other algorithms.
Mahout Recommender Engine
Mahout 拥有一个非分布式、非基于 Hadoop 的推荐引擎。您应该传递一个包含用户对商品首选项的文本文档。此引擎的输出将是特定用户对其他商品的估计首选项。
Mahout has a non-distributed, non-Hadoop-based recommender engine. You should pass a text document having user preferences for items. And the output of this engine would be the estimated preferences of a particular user for other items.
Example
考虑一个销售消费商品(例如手机、小工具及其配件)的网站。如果我们希望在这样一个网站中实现 Mahout 的功能,那么我们可以构建一个推荐引擎。此引擎会分析过去用户的购买数据,然后基于其推荐新产品。
Consider a website that sells consumer goods such as mobiles, gadgets, and their accessories. If we want to implement the features of Mahout in such a site, then we can build a recommender engine. This engine analyzes past purchase data of the users and recommends new products based on that.
Mahout 提供的构建推荐引擎的组件如下:
The components provided by Mahout to build a recommender engine are as follows:
-
DataModel
-
UserSimilarity
-
ItemSimilarity
-
UserNeighborhood
-
Recommender
从数据存储,准备数据模型并将其作为输入传递给推荐引擎。推荐引擎为特定用户生成推荐。以下是推荐引擎的架构。
From the data store, the data model is prepared and is passed as an input to the recommender engine. The Recommender engine generates the recommendations for a particular user. Given below is the architecture of recommender engine.
Building a Recommender using Mahout
以下是开发一个简单推荐引擎的步骤:
Here are the steps to develop a simple recommender:
Step1: Create DataModel Object
PearsonCorrelationSimilarity 类的构造函数需要一个数据模型对象,该对象包含一个文件,其中包含产品的用户、商品和首选项详细信息。以下为数据模型文件示例:
The constructor of PearsonCorrelationSimilarity class requires a data model object, which holds a file that contains the Users, Items, and Preferences details of a product. Here is the sample data model file:
1,00,1.0
1,01,2.0
1,02,5.0
1,03,5.0
1,04,5.0
2,00,1.0
2,01,2.0
2,05,5.0
2,06,4.5
2,02,5.0
3,01,2.5
3,02,5.0
3,03,4.0
3,04,3.0
4,00,5.0
4,01,5.0
4,02,5.0
4,03,0.0
DataModel 对象需要文件对象,其中包含输入文件的路径。如下所示,创建 DataModel 对象。
The DataModel object requires the file object, which contains the path of the input file. Create the DataModel object as shown below.
DataModel datamodel = new FileDataModel(new File("input file"));
Step2: Create UserSimilarity Object
使用 PearsonCorrelationSimilarity 如下所示创建 UserSimilarity 对象:
Create UserSimilarity object using PearsonCorrelationSimilarity class as shown below:
UserSimilarity similarity = new PearsonCorrelationSimilarity(datamodel);
Step3: Create UserNeighborhood object
此对象计算用户相对于给定用户的“邻域”。有两种类型的邻域:
This object computes a "neighborhood" of users like a given user. There are two types of neighborhoods:
-
NearestNUserNeighborhood - This class computes a neighborhood consisting of the nearest n users to a given user. "Nearest" is defined by the given UserSimilarity.
-
ThresholdUserNeighborhood - This class computes a neighborhood consisting of all the users whose similarity to the given user meets or exceeds a certain threshold. Similarity is defined by the given UserSimilarity.
这里我们使用 ThresholdUserNeighborhood 并将偏好限制设置为 3.0。
Here we are using ThresholdUserNeighborhood and set the limit of preference to 3.0.
UserNeighborhood neighborhood = new ThresholdUserNeighborhood(3.0, similarity, model);
Step4: Create Recommender Object
创建 UserbasedRecomender 对象。将上述创建的所有对象传递给它的构造函数,如下所示。
Create UserbasedRecomender object. Pass all the above created objects to its constructor as shown below.
UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);
Step5: Recommend Items to a User
使用 Recommender 界面的 recommend() 方法向用户推荐产品。该方法需要两个参数。第一个表示要向其发送推荐的用户 ID,第二个表示要发送的推荐数。以下是 recommender() 方法的使用方法:
Recommend products to a user using the recommend() method of Recommender interface. This method requires two parameters. The first represents the user id of the user to whom we need to send the recommendations, and the second represents the number of recommendations to be sent. Here is the usage of recommender() method:
List<RecommendedItem> recommendations = recommender.recommend(2, 3);
for (RecommendedItem recommendation : recommendations) {
System.out.println(recommendation);
}
Example Program
Example Program
下面是一个设置推荐的示例程序。为用户 ID 为 2 的用户准备推荐。
Given below is an example program to set recommendation. Prepare the recommendations for the user with user id 2.
import java.io.File;
import java.util.List;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.UserBasedRecommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
public class Recommender {
public static void main(String args[]){
try{
//Creating data model
DataModel datamodel = new FileDataModel(new File("data")); //data
//Creating UserSimilarity object.
UserSimilarity usersimilarity = new PearsonCorrelationSimilarity(datamodel);
//Creating UserNeighbourHHood object.
UserNeighborhood userneighborhood = new ThresholdUserNeighborhood(3.0, usersimilarity, datamodel);
//Create UserRecomender
UserBasedRecommender recommender = new GenericUserBasedRecommender(datamodel, userneighborhood, usersimilarity);
List<RecommendedItem> recommendations = recommender.recommend(2, 3);
for (RecommendedItem recommendation : recommendations) {
System.out.println(recommendation);
}
}catch(Exception e){}
}
}
使用以下命令编译程序:
Compile the program using the following commands:
javac Recommender.java
java Recommender
它应生成以下输出:
It should produce the following output:
RecommendedItem [item:3, value:4.5]
RecommendedItem [item:4, value:4.0]
Mahout - Clustering
聚类是对给定集合的元素或项目按项目之间的相似度组织到组中的过程。例如,与在线新闻发布相关的应用程序使用聚类对新闻文章进行分组。
Clustering is the procedure to organize elements or items of a given collection into groups based on the similarity between the items. For example, the applications related to online news publishing group their news articles using clustering.
Applications of Clustering
-
Clustering is broadly used in many applications such as market research, pattern recognition, data analysis, and image processing.
-
Clustering can help marketers discover distinct groups in their customer basis. And they can characterize their customer groups based on purchasing patterns.
-
In the field of biology, it can be used to derive plant and animal taxonomies, categorize genes with similar functionality and gain insight into structures inherent in populations.
-
Clustering helps in identification of areas of similar land use in an earth observation database.
-
Clustering also helps in classifying documents on the web for information discovery.
-
Clustering is used in outlier detection applications such as detection of credit card fraud.
-
As a data mining function, Cluster Analysis serves as a tool to gain insight into the distribution of data to observe characteristics of each cluster.
使用 Mahout,我们可以对给定的数据集进行聚类。所需步骤如下:
Using Mahout, we can cluster a given set of data. The steps required are as follows:
-
Algorithm You need to select a suitable clustering algorithm to group the elements of a cluster.
-
Similarity and Dissimilarity You need to have a rule in place to verify the similarity between the newly encountered elements and the elements in the groups.
-
Stopping Condition A stopping condition is required to define the point where no clustering is required.
Procedure of Clustering
若要对给定数据进行聚类,您需要 -
To cluster the given data you need to -
-
Start the Hadoop server. Create required directories for storing files in Hadoop File System. (Create directories for input file, sequence file, and clustered output in case of canopy).
-
Copy the input file to the Hadoop File system from Unix file system.
-
Prepare the sequence file from the input data.
-
Run any of the available clustering algorithms.
-
Get the clustered data.
Starting Hadoop
Mahout 与 Hadoop 配合工作,因此请确保 Hadoop 服务器已经启动并正在运行。
Mahout works with Hadoop, hence make sure that the Hadoop server is up and running.
$ cd HADOOP_HOME/bin
$ start-all.sh
Preparing Input File Directories
使用以下命令在 Hadoop 文件系统中创建目录,以存储输入文件、序列文件和聚类数据:
Create directories in the Hadoop file system to store the input file, sequence files, and clustered data using the following command:
$ hadoop fs -p mkdir /mahout_data
$ hadoop fs -p mkdir /clustered_data
$ hadoop fs -p mkdir /mahout_seq
您可以在以下 URL 中使用hadoop web 界面验证目录是否已被创建 - http://localhost:50070/
You can verify whether the directory is created using the hadoop web interface in the following URL - http://localhost:50070/
它会向您提供如下所示的输出:
It gives you the output as shown below:

Copying Input File to HDFS
现在,将输入数据文件从 Linux 文件系统复制到 Hadoop 文件系统中 的 mahout_data 目录,如下所示。假设您的输入文件是 mydata.txt,并且它位于 /home/Hadoop/data/ 目录中。
Now, copy the input data file from the Linux file system to mahout_data directory in the Hadoop File System as shown below. Assume your input file is mydata.txt and it is in the /home/Hadoop/data/ directory.
$ hadoop fs -put /home/Hadoop/data/mydata.txt /mahout_data/
Preparing the Sequence File
Mahout 为您提供了一个实用程序,用于将给定的输入文件转换成序列文件格式。此实用程序需要两个参数。
Mahout provides you a utility to convert the given input file in to a sequence file format. This utility requires two parameters.
-
The input file directory where the original data resides.
-
The output file directory where the clustered data is to be stored.
下面给出了 mahout seqdirectory 实用程序的帮助提示。
Given below is the help prompt of mahout seqdirectory utility.
Step 1: 浏览至 Mahout 主目录。您可以如下所示获得该实用程序的帮助:
Step 1: Browse to the Mahout home directory. You can get help of the utility as shown below:
[Hadoop@localhost bin]$ ./mahout seqdirectory --help
Job-Specific Options:
--input (-i) input Path to job input directory.
--output (-o) output The directory pathname for output.
--overwrite (-ow) If present, overwrite the output directory
使用以下语法使用该实用程序生成序列文件:
Generate the sequence file using the utility using the following syntax:
mahout seqdirectory -i <input file path> -o <output directory>
Example
mahout seqdirectory
-i hdfs://localhost:9000/mahout_seq/
-o hdfs://localhost:9000/clustered_data/
Clustering Algorithms
Mahout 支持两种用于聚类的主要算法,即:
Mahout supports two main algorithms for clustering namely:
-
Canopy clustering
-
K-means clustering
Canopy Clustering
树冠聚类是一种简单快速的算法,Mahout 用于聚类目的。对象将被视为平面空间中的点。该算法经常用作其他聚类算法(如 k 均值聚类)中的初始步骤。您可以使用下列语法运行树冠作业:
Canopy clustering is a simple and fast technique used by Mahout for clustering purpose. The objects will be treated as points in a plain space. This technique is often used as an initial step in other clustering techniques such as k-means clustering. You can run a Canopy job using the following syntax:
mahout canopy -i <input vectors directory>
-o <output directory>
-t1 <threshold value 1>
-t2 <threshold value 2>
树冠作业需要一个包含序列文件的输入文件目录,以及一个将聚类数据存储在其中的输出目录。
Canopy job requires an input file directory with the sequence file and an output directory where the clustered data is to be stored.
Example
mahout canopy -i hdfs://localhost:9000/mahout_seq/mydata.seq
-o hdfs://localhost:9000/clustered_data
-t1 20
-t2 30
您可以在给定的输出目录中获取所生成的集群数据。
You will get the clustered data generated in the given output directory.
K-means Clustering
K-means 聚类是一种重要的聚类算法。K-means 聚类算法中的 k 表示将数据划分为的簇的数目。例如,为该算法指定 k 值为 3 时,该算法将把数据划分为 3 个簇。
K-means clustering is an important clustering algorithm. The k in k-means clustering algorithm represents the number of clusters the data is to be divided into. For example, the k value specified to this algorithm is selected as 3, the algorithm is going to divide the data into 3 clusters.
每个对象将在空间中表示为向量。最初将由算法随机选择 k 个点并将其视为中心,最接近每个中心的每个对象会被聚类。有几种算法用于距离测量,用户应选择所需的一种。
Each object will be represented as vector in space. Initially k points will be chosen by the algorithm randomly and treated as centers, every object closest to each center are clustered. There are several algorithms for the distance measure and the user should choose the required one.
Creating Vector Files
Creating Vector Files
-
Unlike Canopy algorithm, the k-means algorithm requires vector files as input, therefore you have to create vector files.
-
To generate vector files from sequence file format, Mahout provides the seq2parse utility.
下面列出了 seq2parse 实用程序的一些选项。使用这些选项创建向量文件。
Given below are some of the options of seq2parse utility. Create vector files using these options.
$MAHOUT_HOME/bin/mahout seq2sparse
--analyzerName (-a) analyzerName The class name of the analyzer
--chunkSize (-chunk) chunkSize The chunkSize in MegaBytes.
--output (-o) output The directory pathname for o/p
--input (-i) input Path to job input directory.
创建向量后,使用 k-means 算法。运行 k-means 作业的语法如下:
After creating vectors, proceed with k-means algorithm. The syntax to run k-means job is as follows:
mahout kmeans -i <input vectors directory>
-c <input clusters directory>
-o <output working directory>
-dm <Distance Measure technique>
-x <maximum number of iterations>
-k <number of initial clusters>
K-means 聚类作业需要输入向量目录、输出簇目录、距离度量、要执行的最大迭代数和表示将输入数据划分为的簇数目的整数值。
K-means clustering job requires input vector directory, output clusters directory, distance measure, maximum number of iterations to be carried out, and an integer value representing the number of clusters the input data is to be divided into.
Mahout - Classification
What is Classification?
分类是一种机器学习技术,它使用已知数据来确定如何将新数据归类到一组现有类别中。例如,
Classification is a machine learning technique that uses known data to determine how the new data should be classified into a set of existing categories. For example,
-
iTunes application uses classification to prepare playlists.
-
Mail service providers such as Yahoo! and Gmail use this technique to decide whether a new mail should be classified as a spam. The categorization algorithm trains itself by analyzing user habits of marking certain mails as spams. Based on that, the classifier decides whether a future mail should be deposited in your inbox or in the spams folder.
How Classification Works
在对给定一组数据进行分类时,分类器系统执行以下操作:
While classifying a given set of data, the classifier system performs the following actions:
-
Initially a new data model is prepared using any of the learning algorithms.
-
Then the prepared data model is tested.
-
Thereafter, this data model is used to evaluate the new data and to determine its class.

Applications of Classification
-
Credit card fraud detection - The Classification mechanism is used to predict credit card frauds. Using historical information of previous frauds, the classifier can predict which future transactions may turn into frauds.
-
Spam e-mails - Depending on the characteristics of previous spam mails, the classifier determines whether a newly encountered e-mail should be sent to the spam folder.
Naive Bayes Classifier
Mahout 使用朴素贝叶斯分类器算法。它使用两种实现:
Mahout uses the Naive Bayes classifier algorithm. It uses two implementations:
-
Distributed Naive Bayes classification
-
Complementary Naive Bayes classification
朴素贝叶斯是一种构建分类器的简单技术。它不是训练此类分类器的单个算法,而是一系列算法。贝叶斯分类器构建模型以分类问题实例。这些分类是使用可用数据进行的。
Naive Bayes is a simple technique for constructing classifiers. It is not a single algorithm for training such classifiers, but a family of algorithms. A Bayes classifier constructs models to classify problem instances. These classifications are made using the available data.
朴素贝叶斯的一个优点是它只需要少量训练数据来估算分类所需的特征。
An advantage of naive Bayes is that it only requires a small amount of training data to estimate the parameters necessary for classification.
对于某些类型的概率模型,朴素贝叶斯分类器能在受监督的学习设置中非常有效地进行训练。
For some types of probability models, naive Bayes classifiers can be trained very efficiently in a supervised learning setting.
尽管其假设过于简化,但朴素贝叶斯分类器在许多复杂的实际情况中运行良好。
Despite its oversimplified assumptions, naive Bayes classifiers have worked quite well in many complex real-world situations.
Procedure of Classification
以下步骤用于实现分类:
The following steps are to be followed to implement Classification:
-
Generate example data
-
Create sequence files from data
-
Convert sequence files to vectors
-
Train the vectors
-
Test the vectors
Step1: Generate Example Data
生成或下载要分类的数据。例如,您可以从以下链接获取 20 newsgroups 示例数据: http://people.csail.mit.edu/jrennie/20Newsgroups/20news-bydate.tar.gz
Generate or download the data to be classified. For example, you can get the 20 newsgroups example data from the following link: http://people.csail.mit.edu/jrennie/20Newsgroups/20news-bydate.tar.gz
创建一个目录来存储输入数据。按照如下所示下载示例。
Create a directory for storing input data. Download the example as shown below.
$ mkdir classification_example
$ cd classification_example
$tar xzvf 20news-bydate.tar.gz
wget http://people.csail.mit.edu/jrennie/20Newsgroups/20news-bydate.tar.gz
Step 2: Create Sequence Files
使用 seqdirectory 实用工具从示例创建序列文件。生成序列的语法如下:
Create sequence file from the example using seqdirectory utility. The syntax to generate sequence is given below:
mahout seqdirectory -i <input file path> -o <output directory>
Step 3: Convert Sequence Files to Vectors
使用 seq2parse 实用工具从序列文件创建向量文件。 seq2parse 实用工具的选项如下:
Create vector files from sequence files using seq2parse utility. The options of seq2parse utility are given below:
$MAHOUT_HOME/bin/mahout seq2sparse
--analyzerName (-a) analyzerName The class name of the analyzer
--chunkSize (-chunk) chunkSize The chunkSize in MegaBytes.
--output (-o) output The directory pathname for o/p
--input (-i) input Path to job input directory.