Tuesday, September 25, 2012

[Python] package mlpy and matplotlib

import numpy as np # scientific computing package
import mlpy
import matplotlib.pyplot as plt # required for plotting'
iris = np.loadtxt('iris.csv', delimiter=',')  # http://mlpy.sourceforge.net/docs/3.5/_downloads/iris.csv
x, y = iris[:, :4], iris[:, 4].astype(np.int)
x.shape, y.shape

# Principal Component Analysis
pca = mlpy.PCA() # new PCA instance
pca.learn(x) # learn from data
z = pca.transform(x, k=2) # choose 2 principal components

#plot the principal components
plt.set_cmap(plt.cm.Paired)
fig1 = plt.figure(1)
title = plt.title("PCA on iris dataset")
plot = plt.scatter(z[:, 0], z[:, 1], c=y)
labx = plt.xlabel("First component")
laby = plt.ylabel("Second component")
plt.show()

Thursday, September 13, 2012

[Python] Topic Model: Latent Semantic Indexing

 Latent semantic indexing (LSI) is an indexing and retrieval method that uses a mathematical technique called Singular value decomposition (SVD) to identify patterns in the relationships between the terms and concepts contained in an unstructured collection of text. LSI is based on the principle that words that are used in the same contexts tend to have similar meanings. A key feature of LSI is its ability to extract the conceptual content of a body of text by establishing associations between those terms that occur in similar contexts.

from gensim import corpora, models, similarities
documents = ["Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response time",
"The EPS user interface management system",
"System and human system engineering testing of EPS",
"Relation of user perceived response time to error measurement",
"The generation of random binary unordered trees",
"The intersection graph of paths in trees",
"Graph minors IV Widths of trees and well quasi ordering",
"Graph minors A survey"]
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist] for document in documents]
all_tokens = sum(texts, [])
tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1)
texts=[[word for word in text if word not in tokens_once] for text in texts]

dictionary = corpora.Dictionary(texts)
dictionary.save('/tmp/deerwester.dict')
print dictionary.token2id

new_doc = "Human computer interaction"
new_vec = dictionary.doc2bow(new_doc.lower().split())  #The function doc2bow() simply counts the number of occurences of each distinct word, converts the word to its integer word id and returns the result as a sparse vector.
print new_vec

corpus = [dictionary.doc2bow(text) for text in texts]
corpora.MmCorpus.serialize('/tmp/deerwester.mm', corpus)  # store to disk, for later use
print corpus

#Corpus Streaming – One Document at a Time
class MyCorpus(object):
 def __iter__(self):
  for line in open('mycorpus.txt'):
   # assume there's one document per line, tokens separated by whitespace
   yield dictionary.doc2bow(line.lower().split())

#the corpus is now much more memory friendly, because at most one vector resides in RAM at a time
corpus_memory_friendly = MyCorpus() # doesn't load the corpus into memory!
for vector in corpus_memory_friendly: # load one vector into memory at a time
 print vector


# topics and transformations
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

tfidf = models.TfidfModel(corpus) # step 1: initialize a model
corpus_tfidf = tfidf[corpus]
for doc in corpus_tfidf:
 print doc

lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2) # initialize an LSI transformation
corpus_lsi = lsi[corpus_tfidf] # create a double wrapper over the original corpus: bow->tfidf->fold-in-lsi
lsi.print_topics(2)   # the number of topics are self-chosen
for doc in corpus_lsi: # both bow->tfidf and tfidf->lsi transformations are actually executed here, on the fly
 print doc

lsi.save('/tmp/model.lsi') # same for tfidf, lda, ...
lsi = models.LsiModel.load('/tmp/model.lsi')

#available transformations
model = tfidfmodel.TfidfModel(bow_corpus, normalize=True)   #tf-idf
model = lsimodel.LsiModel(tfidf_corpus, id2word=dictionary, num_topics=300)  #LSI
model = rpmodel.RpModel(tfidf_corpus, num_topics=500)  #Random Projection
model = ldamodel.LdaModel(bow_corpus, id2word=dictionary, num_topics=100)    #LDA
model = hdpmodel.HdpModel(bow_corpus, id2word=dictionary)   #Hierarchical Dirichlet Process, HDP

# similarity queries
from gensim import corpora, models, similarities
dictionary = corpora.Dictionary.load('/tmp/deerwester.dict')
corpus = corpora.MmCorpus('/tmp/deerwester.mm')


vec_lsi = lsi[new_vec] # convert the query to LSI space
index = similarities.MatrixSimilarity(lsi[corpus]) # transform corpus to LSI space and index it
index.save('/tmp/deerwester.index')
index = similarities.MatrixSimilarity.load('/tmp/deerwester.index')
sims = index[vec_lsi] # perform a similarity query against the corpus
print list(enumerate(sims)) # print (document_number, document_similarity) 2-tuples
sims = sorted(enumerate(sims), key=lambda item: -item[1])
print sims # print sorted (document number, similarity score) 2-tuples


Monday, August 20, 2012

[R] Merge Data Sets in R

Description:
merge(x, y, by = intersect(names(x), names(y)),
      by.x = by, by.y = by, all = FALSE, all.x = all, all.y = all,
      sort = TRUE, suffixes = c(".x",".y"),
      incomparables = NULL, ...)


Example:
authors <- data.frame(
    surname = I(c("Tukey", "Venables", "Tierney", "Ripley", "McNeil")),
    nationality = c("US", "Australia", "US", "UK", "Australia"),
    deceased = c("yes", rep("no", 4)))
books <- data.frame(
    name = I(c("Tukey", "Venables", "Tierney",
             "Ripley", "Ripley", "McNeil", "R Core")),
    title = c("Exploratory Data Analysis",
              "Modern Applied Statistics ...",
              "LISP-STAT",
              "Spatial Statistics", "Stochastic Simulation",
              "Interactive Data Analysis",
              "An Introduction to R"),
    other.author = c(NA, "Ripley", NA, NA, NA, NA,
                     "Venables & Smith"))
m <- merge(authors, books, by.x = "surname", by.y = "name")

Output:
(1) the data set 'authors':

(2) the data set 'books':

 (3) the data set 'm':












Thursday, August 16, 2012

[Pig] Use of conditional commands



--------------- page views
rawimps = LOAD 'imp' USING TextLoader AS line:chararray;

imp = FOREACH rawimps GENERATE JSON2MAP(line);
imp = FOREACH imp GENERATE JSON2MAP($0#'publisher_descriptor') as publisher, JSON2MAP($0#'user_descriptor') as user;

-- only includes LiveStrong (which has site_id=3)
imp = FILTER imp by publisher#'site_id'=='3';    
imp_user = FOREACH imp GENERATE (chararray) user#'uuid' as user_id;
imp_user = GROUP imp_user BY user_id parallel 5;
pv_user = FOREACH imp_user GENERATE $0 as user_id, COUNT($1) as pv;

--------------- clicks
rawclicks = LOAD 'click' USING TextLoader AS line:chararray;


click = FOREACH rawclicks GENERATE JSON2MAP(line);
click = FOREACH click GENERATE JSON2MAP($0#'publisher_descriptor') as publisher, JSON2MAP($0#'user_descriptor') as user, JSON2MAP($0#'clicked_rad') as clicked_rad;

-- only includes LiveStrong (which has site_id=3)
click_user = FILTER click BY publisher#'site_id'=='3';
click_user = FOREACH click GENERATE (chararray) user#'uuid' as user_id, (float) clicked_rad#'cost' as cost;
click_user = FOREACH click_user GENERATE user_id, cost, (cost==0.0? 'free':null) as free_click, (cost!=0.0? 'paid':null) as paid_click;
click_user = GROUP click_user by user_id parallel 5;

click_user = FOREACH click_user GENERATE $0 as user_id, COUNT($1.free_click) as free_click, COUNT($1.paid_click) as paid_click, SUM($1.cost) as total_cost;

pv_click_user = JOIN pv_user BY user_id LEFT OUTER, click_user BY user_id parallel 5;
pv_click_user = FOREACH pv_click_user GENERATE (chararray) $0 as user_id, (long) pv_user::pv as pv, (long) (click_user::free_click is null?0:click_user::free_click) as free_click, (long) (click_user::paid_click is null?0:click_user::paid_click) as paid_click, (double) (click_user::total_cost is null?0:click_user::total_cost) as total_cost;

user_group = GROUP pv_click_user ALL parallel 5;
user_group = FOREACH user_group GENERATE COUNT($1.user_id) as visitors, SUM($1.pv) as pv, SUM($1.free_click) as free_click, SUM($1.paid_click) as paid_click, SUM($1.total_cost) as revenue;

-- PV distribution
pv_distribution = GROUP pv_user BY pv parallel 5;
pv_distribution = FOREACH pv_distribution GENERATE $0 as pv, COUNT($1) as counts;



Monday, August 13, 2012

[Python] Fibonacci series

# fill in this function
def fib():
    a,b=1,1
    for i in xrange(100):
        yield a
        a,b=b,a+b
    pass #this is a null statement which does nothing when executed, useful as a placeholder.

# testing code
import types
if type(fib()) == types.GeneratorType:
    print "Good, The fib function is a generator."
    counter = 0
    for n in fib():
        print n
        counter += 1
        if counter == 10:
            break



## output: 
Good, The fib function is a generator.
1
1
2
3
5
8
13
21
34
55

Wednesday, July 25, 2012

[Python] sample code

import json

def id_key(val):
    return '{}'.format(val)

def to_key(val):
    return '{}_{}'.format(val[0], val[1])

def from_key(key):
    vals = key.split('_')
    return [ int(vals[0]), int(vals[1])]



def remap_list(l):
    d = {}
    for e in l:
        d[e] = [0, 0]
    return d
       

use_paid = False
domain_to_retain = 'http://www.website.com'
fname = './tracker_output2.txt'

f = open(fname)
out_f = open('output.txt', 'w')

#print 'processing file {}'.format(fname)

num_processed_lines = 0
num_skipped = 0
num_errorline = 0

total_imps = [0]*10
total_clicks = [0]*10


for content in f:
    num_processed_lines = num_processed_lines + 1


    record = json.loads(content)
    scores = record['match_scores']

    url = record['url']

    if ((domain_to_retain) and (not url.startswith(domain_to_retain))):
        num_skipped = num_skipped + 1
        continue


    if num_processed_lines % 1000 == 0:
        print 'num_processed_lines={}'.format(num_processed_lines)

    if use_paid:
        if record['num_paid']>0:
            tuples = record['paid']
 #           print'{}'.format(tuples)
 #           print'{}'.format(scores)
        else:
            continue
    else:
        if record['num_free']>0:
            tuples = record['free']
        else:
            continue


       
    if (isinstance(tuples, list)):
        tuples = remap_list(tuples)
        num_errorline += 1






   
    for key, val in scores.items():
        score_id = id_key(key)
        score_val = id_key(val)
        for key, val in tuples.items():
            val_key = id_key(key)
            val_item = to_key(val)
            val_click_imp = from_key(val_item)
            if score_id == val_key:
 #               print'{},{},{},{}'.format(val_key,val_click_imp[0],val_click_imp[1],score_val)
                score_bucket = int(float(score_val)*10)
                total_clicks[score_bucket] += val_click_imp[0]
                total_imps[score_bucket] += val_click_imp[1]






               
                #print'{},{},{},{}'.format(val_key,val_click_imp[0],val_click_imp[1],score_val)
 #               out_f.write('{},{},{},{}\n'.format(val_key,val_click_imp[0],val_click_imp[1],score_val))
           
ctr = [0]*10
for i in range(0,10):
    if total_imps[i] == 0:
        ctr[i] = 0
    else:
        ctr[i] = float(total_clicks[i])/total_imps[i]


out_f.write('clicks={}\n'.format(total_clicks))
out_f.write('imps={}\n'.format(total_imps))
out_f.write('ctr={}'.format(ctr))
                                                               

Friday, July 13, 2012

[R] Smooth Scatter Plot

## Use smoothed color to represent densities
colors=densCols(x,y)
plot(x,y,col=colors,pch=20)

smoothScatter(x,y)