Showing posts with label Hadoop. Show all posts
Showing posts with label Hadoop. Show all posts

Thursday, July 18, 2013

Hadoop Streaming with Python



--install python
yinst install ypython27 –nosudo

chmod +x wc_map.py

./hello.py

-- Part I: Map/Reduce on Local Machine
cat wc_map.py
#!/usr/local/bin/python
import os, sys, string

what = sys.argv[1]
for ln in sys.stdin:
        ww = ln.rstrip().split("\t")
        ct = reduce (lambda x,y: x+y, [what == w and 1 or 0 for w in ww])
        if ct:
                print "%s\t%d" % (what, ct)

cat wc_reduce.py
#!/usr/local/bin/python
import os, sys, string

ct_ttl=0
for ln in sys.stdin:
        ww = ln.strip().split("\t")
        ct_ln = int(ww[1])
        ct_ttl += ct_ln

print ct_ttl

cat data1 | python wc_map.py dog

cat data1 | python wc_map.py dog > intermediate

cat intermediate | python wc_reduce.py

cat data1 | python wc_map.py dog | python wc_reduce.py

Part II: Map/Reduce on Hadoop Cluster
hadoop jar $HADOOP_PREFIX/share/hadoop/tools/lib/hadoop-streaming.jar \
-Dmapred.job.queue.name=unfunded \
-mapper "python wc_map.py dog  "  \
-reducer "python wc_reduce.py"  \
-input data1  \
-output whatever  \
-file wc_map.py  \
-file wc_reduce.py  \
-jobconf mapred.map.tasks=2  \
-jobconf mapred.reduce.tasks=1 


For example, cat mapper.py
import sys

# input comes from STDIN (standard input)
#f=open("linux.words", "r")
for line in sys.stdin:
#for line in f:
    # remove leading and trailing whitespace
    line = line.strip()
    # split the line into words
    words = line.split()
    # increase counters
    for word in words:
        # write the results to STDOUT (standard output);
        # what we output here will be the input for the
        # Reduce step, i.e. the input for reducer.py
        #
        # tab-delimited; the trivial word count is 1
        print '%s\t%s' % (word, 1)
# testing echo "foo foo quux labs foo bar quux" | python mapper.py


For example, cat reducer.py
#!/usr/bin/env python

from operator import itemgetter
import sys

current_word = None
current_count = 0
word = None

# input comes from STDIN
for line in sys.stdin:
    # remove leading and trailing whitespace
    line = line.strip()

    # parse the input we got from mapper.py
    word, count = line.split('\t', 1)

    # convert count (currently a string) to int
    try:
        count = int(count)
    except ValueError:
        # count was not a number, so silently
        # ignore/discard this line
        continue

    # this IF-switch only works because Hadoop sorts map output
    # by key (here: word) before it is passed to the reducer
    if current_word == word:
        current_count += count
    else:
        if current_word:
            # write result to STDOUT
            print '%s\t%s' % (current_word, current_count)
        current_count = count
        current_word = word

# do not forget to output the last word if needed!
if current_word == word:
    print '%s\t%s' % (current_word, current_count)
   

#echo "foo foo quux labs foo bar quux" | python mapper.py | sort -k1,1 | /python reducer.py

Friday, June 7, 2013

Try Out Hadoop Streaming with Shell awk

--- Remove the whole directory
hadoop fs -rmr /user/*****/tempoutput


-- Run the script in the allocated cluster. The results (output files) are written to the dfs directory tempoutput.

hadoop jar $HADOOP/hadoop-streaming.jar -Dmapred.job.queue.name=unfunded -mapper "awk '{if(length(\$0) > 50){print \$0}}'" -reducer NONE -input linux.words -output tempoutput



-- Wrap with shell script: mapper

$ cat mymapper1.sh

#!/bin/sh
awk '{if(length($0) > 50){print $0}}'
yarn jar $HADOOP/hadoop-streaming.jar \
-Dmapred.job.queue.name=unfunded \
-mapper mymapper1.sh \
-reducer NONE \
-input linux.words \
-output tempoutput \
-file mymapper1.sh

-- Wrap with shell script: mapper & reducer
$ cat mymapper.sh
#!/bin/sh
awk '{
if(length($0) gt 4 ) {print substr($0, 0, 4)" "$0 } 
if(length($0) gt 5 ) {print substr($0, 0, 5)" "$0} 
if(length($0) gt 6 ) {print substr($0, 0, 6)" "$0}
}'

$ cat myreducer.sh
#!/bin/sh
awk '{
curkey=$1; 
curvalue=$2; 
if(prevkey == curkey){
  count+=1; 
  mylist=mylist","curvalue;

else{
  if(count lt 3) {print prevkey" "mylist; } 
  count = 0; 
  mylist=curkey

  prevkey=curkey
}'

hadoop jar $HADOOP/hadoop-streaming.jar \
-Dmapred.job.queue.name=*********** \
-input linux.words \
-output tempoutput2 \
-mapper mymapper.sh \
-reducer myreducer.sh \
-file mymapper.sh \
-file myreducer.sh
 

Try Out MapReduce

--Check running queue
hadoop queue -showacls
--Run the wordcount program
hadoop jar $HADOOP_HOME/hadoop-examples.jar wordcount Dmapred.job.queue.name=unfunded /data/vespanews/20070128 temp/newsout
 
-- Copy the results from dfs to the gateway directory.
hadoop fs -copyToLocal 'temp/newsout/*' newsout
  
--Checking results
head -10 part-r-00000
  
--Kill the job by using jobid
hadoop job -kill job_201204200957_110493

Try Out Hive

--$PATH

echo $PATH
export PATH=$PATH:/home/y/bin
export HIVE_HOME=/home/y/libexec/hive
tar -xzvf 2008.tar.gz

hive
-- Creates a new database and stores related data at <hdfs-path>.
hive> CREATE DATABASE ling LOCATION '/user/***/hive';
hive> SHOW DATABASES;

-- Use the database the was just created.
hive> USE ***;

-- Prepare a table;
hive> CREATE TABLE test (a string, b string) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' LOCATION '/user/***/mydata/test';

CREATE TABLE flight_data(
year INT,
month INT,
day INT,
day_of_week INT,
dep_time INT,
crs_dep_time INT,
arr_time INT,
crs_arr_time INT,
unique_carrier STRING,
flight_num INT,
tail_num STRING,
actual_elapsed_time INT,
crs_elapsed_time INT,
air_time INT,
arr_delay INT,
dep_delay INT,
origin STRING,
dest STRING,
distance INT,
taxi_in INT,
taxi_out INT,
cancelled INT,
cancellation_code STRING,
diverted INT,
carrier_delay STRING,
weather_delay STRING,
nas_delay STRING,
security_delay STRING,
late_aircraft_delay STRING
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
 

CREATE TABLE airports(
name STRING,
country STRING,
area_code INT,
code STRING)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ',';

-- Load data;
hive> LOAD DATA LOCAL INPATH 'data.00000' INTO TABLE test;
hive> LOAD DATA LOCAL INPATH '2008.csv' OVERWRITE INTO TABLE flight_data;hive> LOAD DATA LOCAL INPATH 'airports.csv' OVERWRITE INTO TABLE airports;

SHOW TABLES;
-- Execute a query to retrieve the data.
hive> SELECT * FROM test;
hive> set mapred.job.queue.name=unfunded;
hive> SELECT avg(arr_delay) FROM flight_data WHERE month=1 AND origin='SFO';hive> SELECT * FROM airports LIMIT 10;
hive> CREATE TABLE results AS SELECT name, AVG(arr_delay)
FROM flight_data f
INNER JOIN airports a
ON (f.origin=a.code)
WHERE month=1
GROUP BY name;

 hive> SELECT * FROM results LIMIT 10;

-- Clean up the table and database.
hive> DROP TABLE test;
hive> DROP DATABASE ling;


hive --hiveconf mapreduce.map.speculative=true --hiveconf mapreduce.reduce.speculative=true --hiveconf mapreduce.job.acl-view-job="*";

set mapred.reduce.tasks = 500;
set mapreduce.job.queuename=adhoc;
set mapreduce.input.fileinputformat.split.minsize = 2048000000;
set mapreduce.input.fileinputformat.split.maxsize = 2048000000;

use ling;
grant all on database ling to user XXX; 



Try Out Pig



--Local machine(local mode)

--creates copy of linux.words in local fs


cp /usr/share/dict/linux.words linux.words

-- places you in Grunt shell (Grunt is Pig's interactive shell)
pig -x local

--enter Pig latin statements from Grunt shell
grunt> A = load 'linux.words' using PigStorage() as (word:chararray);
grunt> B = filter A by SIZE(word) > 19;
grunt> dump B;
grunt> quit;

--place Pig latin statements in script
/* myscript.pig */
A = load 'linux.words' using PigStorage() as (word:chararray);
B = filter A by SIZE(word) > 19;
dump B;

-- runs the script
pig -x local myscript.pig


-- check running queue/cluster should use?
mapred queue -showacls

--Gateway machine(mapreduce mode. Change (myqueue) to (unfunded)
pig -Dmapred.job.queue.name=unfunded myscript.pig
pig -Dmapred.job.queue.name=unfunded myscript2.pig
pig -Dmapred.job.queue.name=unfunded Pig_ABF.pig

Try Out HDFS

Usage: hadoop [--config confdir] COMMAND

where COMMAND is one of:

namenode -format format the DFS filesystem

secondarynamenode run the DFS secondary namenode

namenode run the DFS namenode

datanode run a DFS datanode

dfsadmin run a DFS admin client

fsck run a DFS filesystem checking utility

fs run a generic filesystem user client

balancer run a cluster balancing utility

jobtracker run the MapReduce job Tracker node

pipes run a Pipes job

tasktracker run a MapReduce task Tracker node

job manipulate MapReduce jobs

version print the version

jar <jar> run a jar file

distcp <srcurl> <desturl> copy file or directories recursively

archive -archiveName NAME <src>* <dest> create a hadoop archive

daemonlog get/set the log level for each daemon

or

CLASSNAME run the class named CLASSNAME

Most commands print help when invoked w/o parameters.

-- Check the status of Kerberos tickets
klist

-- invoke kinit to get a ticket
kinit li@COM

-- sudo user login to get a ticket
sudo -s -h -u d_pbp
/usr/kerberos/bin/kinit -k -t /homes/dfsload/dfsload.prod.headless.keytab dfsload@COM

-- Drop a ticket
kdestroy
Hadoop HDFS Commands

--View the hadoop commands
hadoop

--View the version of hadoop
hadoop version

--View FS shell commands
hadoop fs

-- List directory
hadoop fs –ls /user/li

-- List content of HDFS files:
hadoop fs -cat wordcount/output/*
hadoop fs -cat file.bz2 | bunzip2
hadoop fs -cat dir/*.bz2 | bacat | cut -d ^A -f 125,126 | cat -v
hadoop fs -test -e dir/*.bz2 | tail -1

-- Move files or directory
hadoop fs –ls /user/li/target /user/li/dest

--Copy file or directory
hadoop fs –cp file1 file2 file3 /user/li/dest/
hadoop fs -cp /user/li/file1.txt .
hadoop fs -cp /HRBlock/hrblock.data.reduced /HRBlock/ part-r-00000-- Create HDFS directoyr
hadoop fs –mkdir /user/li/input

-- Upload from the gateway host to the HDFS home directory
hadoop fs -copyFromLocal test-data/ch1/file1.txt /user/li
hadoop fs -put test-data/ch1/file1.txt /user/li

-- Download HDFS Files
hadoop fs –get /user/li/myfile .
hadoop fs -copyToLocal hdfs://dilithiumred-nn1.red.ygrid.com:8020/projects/prod/user/20130327/SIDEBID/user/part-00998.bz2 .

-- Delete directory/file, and remove revursively(rm -rf)
hadoop fs -rm /user/li/temp
hadoop fs -rmr /user/li/temp

-- Change permissions by chown, chgrp, chmod
hadoop fs -chgrp -R users /user/li
hadoop fs -chmod 755 /user/li

-- Viewing Data from HDFS
hadoop fs -text /user/li/tmp5/000000_0.deflate | tr '\001' ',' | head -1
hadoop fs -cat path_to_data/*.bz2 | bzcat | cut -d ^A -f 125,126  | cat -v
This selects columns 125 and 126 from Ctrl-A separated data.
To create the ^A, type:  CTRL-v CTRL-a
Inside screen, type:  CTRL-v CTRL-a a

--Transfer data between clusters
hadoop distcp -Dmapred.job.queue.name=adhoc -Ddfs.umaskmode=002 -i -m 40 -update webhdfs://ygrid.yahoo.com/user/li/search_20131211 hdfs://ygrid.yahoo.com/user/li/search_20131211

--Kill a job
mapred job -list |tail -n+3 |awk {'print $1" "$4'} |grep 'li'
mapred job -kill job_1399615563645_524816

--View job logs
mapred job -logs job_1374774840603_3324664
mapred job -logs job_1387925060187_4840299

-- Show available queues
mapred queue -showacls
mapred queue -list
mapred queue -info apg_dailymedium_p5
The meanings are percentages or fractions:
Capacity = % of the grid’s total capacity used by this queue under normal usage. If you add up the capacities for all queues you will get 100%.
MaximumCapacity =Fraction of the grid’s total capacity this queue can use. In this example, the p5 queue normally uses 5%, but it’s allowed to go as high as 40% of the total grid capacity.
CurrentCapacity = Current usage relative to Capacity. In this example, p5 is using 144% of its Capacity, or 7.2% of the total grid capacity.

-- Check running job list/Show number of jobs per queue for each user
mapred job -list
mapred job -list |tail -n+3 |awk {'print $5" "$4'} |sort |uniq –c

-- Another way to list jobs, both running and completed:
mapred queue -info apg_d**_p3 -showJobs

-- Check Gateway Quota
quota -u apoqa

-- Check HDFS Quotas, aka get count of objests
hadoop fs -count -q /projects/DSP
hadoop fs -count -q /user/li

-- Displays aggregate length of files contained in the directory.
hadoop fs –dus /user/li
hadoop fs -du hdfs://.com:8020/projects

-- Check the running processes
jps

-- Check is file / is zero /is dir
hadoop fs -test -e /user/li/
hadoop fs -test -z /user/li/
hadoop fs -test -d /user/li/

-- Check group members
/gridtools/generic/bin/showmembers –n GROUPNAME
/gridtools/gneric/bin/showmembers -n awrgroup
showmembers --netgroup cp_pnp_c_sudoers --type user --format comma

-- Launch R
echo USER=***
export INSTALL_ROOT=/homes/$USER/custom_root
/homes/$USER/custom_root/bin/R

-- Launch Pig
pig -Dmapred.job.queue.name=***  \
-Dmapreduce.reduce.memory.mb=3072 \
-Dmapreduce.map.memory.mb=3072 \
-Dmapreduce.map.java.opts="-Xmx2048M" \
-Dmapreduce.map.speculative=true \
-Dmapreduce.job.acl-view-job=* \
-Dmapreduce.task.timeout=1800000 \
-Dmapreduce.reduce.speculative=true \
-Dmapreduce.output.fileoutputformat.compress=true \
-param PARALLEL_ORDER=512  \
***_MB3.pig

-- Hadoop Streaming

hadoop jar $HADOOP_PREFIX/share/hadoop/tools/lib/hadoop-streaming.jar \
        -input /ngrams \
        -output /output-streaming \
        -mapper mapper.py \
        -combiner reducer.py \
        -reducer reducer.py \
        -jobconf stream.num.map.output.key.fields=3 \
        -jobconf stream.num.reduce.output.key.fields=3 \
        -jobconf mapred.reduce.tasks=10 \
        -file mapper.py \
        -file reducer.py

Wednesday, May 29, 2013

Transform to VW format

import sys
import string

for line in sys.stdin:
    line = line.strip()
    toks = line.split('\t')
    pline =  toks[0].strip() + " | "
    #continuous
#    for i in range(1, sys.argv[3]):
    for i in range(1, 2):
        if len(toks[i].strip()) == 0 :
            continue
        pline = pline + str(i) + ":" + toks[i].strip() + str('\t')
    #categorical
    for i in range(2, len(toks)):
        if len(toks[i].strip()) == 0 :
            continue
        pline = pline + str(i) + "cell" + toks[i].strip() + ":1" + str('\t')
    print pline
 
hadoop  jar hadoop-streaming.jar \
-input $1 \
-output $2 \
-mapper "python csv2vm2.py" \
-reducer NONE \
-file csv2vm2.py \
-jobconf mapred.reduce.tasks=5 \
-jobconf mapred.job.queue.name=***;

./csv2vm.sh /train1/* /vwtrain1/
./csv2vm.sh /test1/* /vwtest1/



Running Mincemeat Example on Windows

Lightweight MapReduce in python: https://github.com/michaelfairley/mincemeatpy.

client

E:\Python27>python example.py

server

E:\Python27>python mincemeat.py -p changeme localhost

Word count example

import glob
import mincemeat

#text_files=glob.glob('hw3data/*')
text_files=glob.glob('hw3data/c0001')
print(text_files)

def file_contents(file_name):
    f=open(file_name,'rb')
    try:
        return f.read()
    finally:
        f.close()

source=dict((file_name,file_contents(file_name))
    for file_name in text_files)

# setup map and reduce functions
def mapfn(key,value):
      for line in value.splitlines():
          for word in line.split():
               yield word.lower(),1

def reducefn(key,value):
       return key,len(value)  
  
# start the server
s =    mincemeat.Server()
s.datasource = source
s.mapfn = mapfn
s.reducefn = reducefn

results = s.run_server(password="changeme")
print results

Tuesday, February 5, 2013

R with Hadoop

1 R + Streaming
 With this approach, you use MapReduce to execute R scripts in the map and reduce phrases.
The R package needs to be installed on each Data-Node, but packages are available on pubicly available Yum repositories for easy installation.

2 RHipe
 Rhipe is an open source priject which allows MapReduce to be closely integrated with R on the client side.An R package that integrates the R environment with Hadoop, the open source implementation of Google’s MapReduce. 
Using Rhipe, it is possible to write MapReduce algorithms in R, launch and monitor MapReduce jobs from R and interact with the HDFS.
R must be installed on each Data-Node, in conjunction with Protocal Buffers, and Rhipe itself. 

3 RHadoop
RHadoop like Rhipe, provides an R wrapper around Map-Reduce so that they can be seamlessly integrated on the client side.
R must be installed on each Data-Node, and RHadoop has dependencies on other R packages. But these packages can be installled with CRAN, and the RHadoop installlation,, while not via CRAN, is straight-forward.

4 RHive
RHive is an R extension facilitating distributed computing via HIVE query. It provides an easy to use HQL like SQL and R objects and functions in HQL. It requires Hadoop core and Hive system.

5 Segue
An R language segue into parallel processing on Amazon’s Web Serives (in the cloud). Not a full map/reduce framework for R. Currently runs on Mac or Linux.







Wednesday, February 8, 2012

LME to estimate Mixed Effect Models in R

In common marketing discussion, a hierarchical model estimates both group level effects and individual differences in effects. Such models are popular in marketing because they provide insight into differences among customers (heterogeneity) and distribution of preference. HLM are exemplified when we estimate the importance of effects for individuals as well as for an overall population. 

Effects that are associated with all observations are known as fixed effects, and those that differ across various grouping levels are known as random effects. 

These models are also known as mixed effect models, because the total effect for each person is composed of the effect for the overall population ( the fixed effect) plus the per-individual (random) effect. 

The difference between estimating hierarchical effects, as opposed to including the grouping variable as a factor in a standard linear model, is that a hierarchical model estimates every specified effect for each individual or group, not only a single adjustment term. 

The formula for a mixed effect model includes a grouping term + (... |group). Common models have a different intercept by group using (1|group) or different intercepts and slopes for predictors within each group using (predictor|group). To estimate an individual level model, the grouping term is typically the respondent identifier. 


Hierarchical model can be used to group observations at other levels than the individual level. For example, we might wish to group by store, advertising campaign, salesperson, or some other factor, if we went o estimate effects that are specific to such a grouping. 


Hierarchical models in marketing are often estimated with Bayesian methods that are able to pool information and produce best estimates of both group and individual effects using potentially sparse data. 

Model coefficients from a hierarchical model are inspected using summaries of the many estimates that are collected in an mcmc object.

library(nlme)
model1<-lme(mathach ~ 1, random = ~ 1 | id, data=hsb)
summary(model1)