顯示具有 programming 標籤的文章。 顯示所有文章
顯示具有 programming 標籤的文章。 顯示所有文章

2017年2月25日 星期六

[Scala] Big Data(5) 雜記,Cloudera Quickstart VM和萬年word count

其實蠻久之前就有用過Spark這個東西了,只是最近再拿出來玩玩發現發現好多東西都忘記,忘得精光那種,筆記這種東西真的好重要啊啊啊啊啊。

Cloudera Quickstart VM


為了練習Spark自己搞一個server雖然很霸氣,但不是所有人都有錢有閒這樣做的,如果只是為了練習,或是用少量資料驗證一下想法可不可行,誠心建議使用Cloudera Quickstart VM就好了。這個東西真的超級佛心的,一包拿來裡面該有的都有(Hadoop, Spark, Hive...),然後設定也算簡單,尤其是對於我這種對Architecture很沒轍的技術廢物(無誤)來說。

題外話,中視《飢餓遊戲》好看!
喔對了,為了平衡報導,其實另外一家叫做Hortonworks提供的Sandbox也不錯,有興趣的人也可以試試看。

然後我選用Docker VM,因為設定超級無敵簡單的就一頁而已,指令也沒幾行,連我都搞得定簡直太棒!不過得先安裝Docker就是了。設定步驟很簡單,以下也不過是把網頁上的Instruction翻成中文而已就醬。

在安裝好Docker之後,就打開terminal,用docker pull指令開始下載Cloudera QuickstartVM。
$ docker pull cloudera/quickstart

整包東西大概4GB左右,要稍微等一下。

然後鍵入指令,裡就會發現有一個image叫做cloudera/quickstart耶!(訝異個屁)
$ docker images
EPOSITORY            TAG                 IMAGE ID            CREATED             SIZE
cloudera/quickstart  latest              4239cd2958c6        10 months ago       6.34 GB

記下對應的IMAGE ID,以上圖為例也就是4239cd2958c6,用來啟動Docker VM囉!
$ docker run \
--hostname=quickstart.cloudera \
--privileged=true \
-t -i -p 8888 \
[IMAGE ID] /usr/bin/docker-quickstart

然後那個[IMAGE ID]記得要換一下。然後基本上經過一段時間的等在就可以成功進入VM的根目錄了,我啟動的時候hue沒有成功,但是在Docker VM開始run之後重複幾次restart神奇的事情就發生了,像這樣:
[root@quickstart /]# service hue restart
Shutting down hue:
Starting hue:                                              [  OK  ]

但如果不是很在意hue的話也可以不理它啦,反正天下事只要牽涉到UI就是神煩(翻白眼)。至於確切原因我也不知到為何,反正它就是好了,很煩(知道原因的拜託留言或是托夢告訴我拜託!)。

看到Hue web UI就是心曠神怡而已

然後注意,如果這時候關掉terminal的話,所有資料都會消失,如果不想資料消失的話,請在剛剛的啟動加上-p選項或者用ctrl+p -> ctrl+q關掉terminal,這樣VM就會繼續運行。如果要重新接上,請用docker ps找到對應的conatiner id
$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED    
56703ef28dc3        4239cd2958c6        "/usr/bin/docker-q..."   2 hours ago

然後docker attach
$ docker attach [CONTAINER ID]

如果要在執行其他指令的話,可以用docker exec,概念上和ssh差不多
$ sudo docker exec -i -t [CONTAINER ID] /bin/bash

千篇一律的Word count problem


接下來就是用Spark跑跑看最白爛(對,即便就是白爛我還是要跑)的word count,就是計算字數啦。首先得把檔案用docker cp從本機丟過去docker VM的container裡面。
$ docker cp word_count.txt [CONTAINER ID]:/word_count.txt

然後進入docker VM,把這個剛剛丟過來的檔案推到HDFS上。
[root@quickstart /]# hdfs dfs -mkdir temp
[root@quickstart /]# hdfs dfs -put word_count.txt temp/word_count.txt

之後進入Spark shell
[root@quickstart /]# spark-shell

之後就開始跑罐頭程式
scala> val file = sc.textFile("temp/word_count.txt")
file: org.apache.spark.rdd.RDD[String] = temp/word_count.txt MapPartitionsRDD[1] at textFile at :27

scala> val counts = file.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey(_ + _)
counts: org.apache.spark.rdd.RDD[(String, Int)] = ShuffledRDD[4] at reduceByKey at :29

scala> counts.collect().foreach(println)
(Groovy..,1)
(found,1)
(Check,1)...

scala> counts.saveAsTextFile("temp/output")

寫資料路徑的時候要稍微小心一點,其實不一定像網路上的demo一樣寫完整的路徑,像這樣。

scala> val file = sc.textFile("hdfs://quickstart.cloudera:8020/user/root/temp/word_count.txt")

然後看一下HDFS看看有沒有存成功
[root@quickstart /]# hdfs dfs -ls temp/output
Found 3 items
-rw-r--r--   1 root supergroup          0 2017-02-25 19:56 temp/output/_SUCCESS
-rw-r--r--   1 root supergroup         93 2017-02-25 19:56 temp/output/part-00000
-rw-r--r--   1 root supergroup        127 2017-02-25 19:56 temp/output/part-00001


2014年10月10日 星期五

[JAVA] Big Data(4) Hadoop Multiple Input

Multiple Input

在map-reduce時,若不同的資料來源要塞給不同的mapper,最後再一起塞進reducer運算,就需要使用Multiple Input 的功能。如下圖,有三個不同的資料來源,先分別進入不同的mapper,然後最後要進到同一個reducer。



首先要先import需要的的類別
org.apache.hadoop.mapreduce.lib.input.MultipleInputs

然後在主程式(main)中寫入下面這一行,告訴電腦你要把哪一筆資料送進哪一個Mapper class的map函數

MultipleInputs.addInputPath(Job名稱, 輸入資料的位址, 格式Mapper class的名字);

接下來看一個簡單到近乎無腦的例子
假設手上有三筆資料,都包含學號、科目和成績,但是長相就是不太一樣,現在我們要計算各科的平均分數

第一筆
$HADOOP/hadoop fs -cat input_1 | head -3
WUJ-360100;math;56
WPY-802007;math;98
FKT-670008;science;67
第二筆
$HADOOP/hadoop fs -cat input_2 | head -3
{Number:FJB-004150, Subject:math, Score:96}
{Number:QDG-300700, Subject:chinese, Score:90}
{Number:JVY-030140, Subject:chinese, Score:71}
第三筆
$HADOOP/hadoop fs -cat input_3 | head -3
[Number=>ITM-501806; Subject=>science; Score=>82]
[Number=>QBE-003981; Subject=>math; Score=>85]
[Number=>EUJ-017009; Subject=>chinese; Score=>63]
以上三種長相的資料要分別送給三種不同的Mapper中處理,產生(subject, score)的pair然後統一送進一個Reducer做平均數的計算,所以要準備三種Mapper
public static class Map1 extends Mapper
{
      public void map(LongWritable key, Text value, Context con) 
        throws IOException, InterruptedException
      {
              // get the student number
              String stNum = value.toString().split(";")[1];

              // get score
              int score = Integer.parseInt(value.toString().split(";")[2]);
              con.write(new Text(stNum), new IntWritable(score));
      }
}
public static class Map2 extends Mapper
{
      public void map(LongWritable key, Text value, Context con) 
        throws IOException, InterruptedException
      {       
              // "shave" the input value
              String line = value.toString().replaceAll("}", "");

              if(line.contains(",")){
                      // get the student number
                      String stNum = line.split(",")[1].split(":")[1];

                      // get score
                      int score = Integer.parseInt(line.split(",")[2].split(":")[1]);
                      con.write(new Text(stNum), new IntWritable(score));
              }
      }
}
public static class Map3 extends Mapper
{
      public void map(LongWritable key, Text value, Context con) 
        throws IOException, InterruptedException
      {
              // "shave" the input value
              String line=value.toString().replaceAll("[]\\[]", "");


              if(line.contains(";")){
                // get the student number
                String stNum = line.split(";")[1].split("=>")[1];

                // get score
                int score = Integer.parseInt(line.split(";")[2].split("=>")[1]);
                con.write(new Text(stNum), new IntWritable(score));
              }
      }
}
Reducer其實就只需要一個就可以了
public static class Red extends Reducer
{
     public void reduce(Text stNum, Iterable scores, Context con)
      throws IOException , InterruptedException
      {
              int numerator = 0;
              int denominator = 0;
              for (IntWritable v : scores){
                  numerator += v.get();
                  denominator ++;
              }
              int avg = numerator/denominator;
              con.write(stNum, new IntWritable(avg));
      }
}
然後是比較麻煩的主程式
public static void main(String[] args) throws Exception
{
      Configuration conf=new Configuration();
      String[] files=new GenericOptionsParser(conf,args).getRemainingArgs();
      Path inPath1=new Path(files[0]);
      Path inPath2=new Path(files[1]);
      Path inPath3=new Path(files[2]);
      Path outPath=new Path(files[3]);
      FileSystem hdfs = outPath.getFileSystem(conf);
      if (hdfs.exists(outPath)){
        hdfs.delete(outPath, true);
      };

      Job exampleJob = new Job(conf,"example");
      exampleJob.setJarByClass(MpInputExp.class);
      exampleJob.setMapperClass(Map1.class);
      exampleJob.setMapperClass(Map2.class);
      exampleJob.setMapperClass(Map3.class);
      exampleJob.setReducerClass(Red.class);
      exampleJob.setOutputKeyClass(Text.class);
      exampleJob.setOutputValueClass(IntWritable.class);

      MultipleInputs.addInputPath(exampleJob, inPath1, TextInputFormat.class, Map1.class);
      MultipleInputs.addInputPath(exampleJob, inPath2, TextInputFormat.class, Map2.class);
      MultipleInputs.addInputPath(exampleJob, inPath3, TextInputFormat.class, Map3.class);
      
      FileOutputFormat.setOutputPath(exampleJob, outPath);
      System.exit(exampleJob.waitForCompletion(true) ? 0:1);
}
要注意MultipleInputs.addInputPath有沒有把Input和Mapper配對好

最後來看結果(打包部分省略,可以參考這裡)
$HADOOP/hadoop fs -getmerge output_exp output_exp
cat output_exp

science 68
chinese 70
math    68
送上所有JAVA code結束這惱人的一切
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MpInputExp
{
  public static class Map1 extends Mapper
  {
        public void map(LongWritable key, Text value, Context con) 
          throws IOException, InterruptedException
        {
                // get the student number
                String stNum = value.toString().split(";")[1];

                // get score
                int score = Integer.parseInt(value.toString().split(";")[2]);
                con.write(new Text(stNum), new IntWritable(score));
        }
  }
  public static class Map2 extends Mapper
  {
        public void map(LongWritable key, Text value, Context con) 
          throws IOException, InterruptedException
        {       
                // "shave" the input value
                String line = value.toString().replaceAll("}", "");

                if(line.contains(",")){
                        // get the student number
                        String stNum = line.split(",")[1].split(":")[1];

                        // get score
                        int score = Integer.parseInt(line.split(",")[2].split(":")[1]);
                        con.write(new Text(stNum), new IntWritable(score));
                }
        }
  }
  public static class Map3 extends Mapper
  {
        public void map(LongWritable key, Text value, Context con) 
          throws IOException, InterruptedException
        {
                // "shave" the input value
                String line=value.toString().replaceAll("[]\\[]", "");


                if(line.contains(";")){
                  // get the student number
                  String stNum = line.split(";")[1].split("=>")[1];

                  // get score
                  int score = Integer.parseInt(line.split(";")[2].split("=>")[1]);
                  con.write(new Text(stNum), new IntWritable(score));
                }
        }
  }
  public static class Red extends Reducer
  {
       public void reduce(Text stNum, Iterable scores, Context con)
        throws IOException , InterruptedException
        {
                int numerator = 0;
                int denominator = 0;
                for (IntWritable v : scores){
                    numerator += v.get();
                    denominator ++;
                }
                int avg = numerator/denominator;
                con.write(stNum, new IntWritable(avg));
        }
   }
  public static void main(String[] args) throws Exception
  {
        Configuration conf=new Configuration();
        String[] files=new GenericOptionsParser(conf,args).getRemainingArgs();
        Path inPath1=new Path(files[0]);
        Path inPath2=new Path(files[1]);
        Path inPath3=new Path(files[2]);
        Path outPath=new Path(files[3]);
        FileSystem hdfs = outPath.getFileSystem(conf);
        if (hdfs.exists(outPath)){
          hdfs.delete(outPath, true);
        };

        Job exampleJob = new Job(conf,"example");
        exampleJob.setJarByClass(MpInputExp.class);
        exampleJob.setMapperClass(Map1.class);
        exampleJob.setMapperClass(Map2.class);
        exampleJob.setMapperClass(Map3.class);
        exampleJob.setReducerClass(Red.class);
        exampleJob.setOutputKeyClass(Text.class);
        exampleJob.setOutputValueClass(IntWritable.class);

        MultipleInputs.addInputPath(exampleJob, inPath1, TextInputFormat.class, Map1.class);
        MultipleInputs.addInputPath(exampleJob, inPath2, TextInputFormat.class, Map2.class);
        MultipleInputs.addInputPath(exampleJob, inPath3, TextInputFormat.class, Map2.class);
        
        FileOutputFormat.setOutputPath(exampleJob, outPath);
        System.exit(exampleJob.waitForCompletion(true) ? 0:1);
  }
}

2014年2月16日 星期日

[JAVA] JDBC 連接 SQL database

JDBC是一個蠻好用的Package,可以從這裡下載

這裡記錄一些最近摸索的基本的用法,以MS-SQL為例

在使用前記得要(搖一搖?)

import java.sql.*;

0. Connection

String conUrl = "jdbc:sqlserver://portNumber:XX;serverName=XX;databaseName=XX;user=XX;password=*****;";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(conUrl);

1. Create , table, truncate table

try{
        String query="XXX";//可以是create, drop或是truncate table的sql語句
 
        Statement stmt = con.createStatement();
        stmt.executeUpdate(query);
        stmt.close();
        con.close();

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

2. Insert data

如果只是要插入一筆資料的話,可以把上面的
String query="XXX";
換成
String query="insert into xxx...";
也可以參考prepare statement的寫法,好處是可以不用重複寫sql語句,只要把問號(?)的地方取代成想要插入的值
try{
        String sql="INSERT INTO XXX (column1,column2) VALUES (?,?)";//prepare statement
 
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, "插入值1");//第一個?要插入的值
        pstmt.setString(2, "插入值2");//第二個?要插入的值
        pstmt.executeUpdate();
        
        pstmt.close();
        con.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
如果要insert的資料有很多筆,其實一筆一筆塞是有點沒效率的,所以如果要塞入很多筆資料的話,可以先寫入Batch再一次執行
try{
        String sql="INSERT INTO XXX (column1,column2) VALUES (?,?)";//prepare statement
 
        PreparedStatement pstmt = con.prepareStatement(sql);

        for(String s : Data){
            pstmt.setString(1, "要插入的資料");//第一個?要插入的值
            pstmt.setString(2, "要插入的資料");//第二個?要插入的值
            pstmt.addBatch();//寫入Batch
        }

        pstmt.executeBatch();//執行Batch

        pstmt.close();
        con.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

3. 讀料取資

讀取SQL database的資料算是蠻常用的
try{
        String sql="SELECT XXX ...";//Query語句
     Statement stmt = con.createStatement();
 
     ResultSet rs = stmt.executeQuery(sql);//Query結果存在這裡
        ResultSetMetaData rsmd = rs.getMetaData(); //取得Query資料

        int numColumns = rsmd.getColumnCount();

        while (rs.next()){//while loop 一筆一筆iterate
           for(int i = 1; i < numColumns+1; i ++){
           System.out.println(rs.getString(rsmd.getColumnName(i)));//印出資料
        }
        }

        stmt.close();
        con.close();
        
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
以上是用print當作示範,當然也可以把資料讀下來做其搭更複雜的計算,比如說塞進array裡面bla bla bla..

2014年1月13日 星期一

[Python] 小用法備忘

最近很少跟他打交道,有些小東西雖然基本,但是久不用就會忘記阿阿阿阿阿

lambda

有別於function的寫法,lamda用過即丟,用來建立簡單的function
>>> test = lambda x,y,z: x*y*z
>>> test(1,2,3)
6

filter

用filter函數把不符條件的element濾掉
>>> a = [31,545,21,2,0,231,56]
>>> func = lambda x: x>2
>>> filter(func,a)
[31, 545, 21, 231, 56]

map

用map函數計算每個member的結果
>>> a = [31,545,21,2,0,231,56]
>>> func = lambda x: x+2
>>> map(func, a)
[33, 547, 23, 4, 2, 233, 58]

reduce

用reduce計算$f(f...f(f(x_{0},x_{1}),x_{2})..,x_{n})$
>>> a = [1,2,3,4,5]
>>> func = lambda x,y: x*y
>>> reduce(func, a)
120

range & xrange

用range 函數來產生數列
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

xrange函數用在迴圈中加強效能
>>> for i in xrange(10):
 print(i)

 
0
1
2
3
4
5
6
7
8
9

iterate寫法

iterate寫法是python特有的解決方案,和for loop類似
[i*5 for i in xrange(4)]
[0, 5, 10, 15]

2013年10月10日 星期四

[R] OOP(1) class的寫法

OOP就是 object-oriented programming的縮寫

中文比較常見的翻譯是「物件導向」

我其實還蠻討厭把「物件導向」不斷掛在嘴上的人,因為我覺得這四個字非常難以顧名思義

尤有甚者,一大堆屬性啦、方法啦之類完全莫名其妙的名詞就是要嚇退那些剛剛接觸程式設計的人阿!

好啦曾經的我就是被嚇得很慘的人之一(愧)




言歸正傳,說到OOP,R裡語言中當然也是有class寫法的

R語言裡主要有兩種形態的class:S3和S4

S3 Class

在R中最原始的class就是S3 class

我們可以把任何東西指定一個S3 class,比如說一個list開始

假設我今天把a這個list指定給一個叫做BodyIndex的類別
> a<- list(name="John", weight=65, height=166)
> class(a)<- "BodyIndex"
> a
$name
[1] "John"

$weight
[1] 65

$height
[1] 166

attr(,"class")
[1] "BodyIndex"

我們現在就可以幫這個特定的class寫一個他的print
print.BodyIndex<- function(l){
    BMI<- l$weight/((l$height/100)^2)
    cat(l$name,"\n")    
    cat("BMI is ", BMI)
}

當我們再請系統把它print出來的時候
> a
John 
BMI is  23.58833

S3 class當然是可以繼承的
> b<- list(name="Tom", weight=75, height=172, sex="Male")
> class(b)<- c("profile","BodyIndex")
> b
Tom 
BMI is  25.35154

隨著需求,你可以改寫更多某個類別專屬的內建函數(generic function)

S4 Class

R語言裡也提供比較安全的S4類別,但是寫法就比較複雜了

首先要用setClass()定義class

然後用new()把特定的東西指向class
> setClass("BodyIndex",
+     representation(
+         name = "character",
+         weight = "numeric",
+         height = "numeric"
+     )
+ )
> a<- new("BodyIndex",name="John", weight=65, height=166)

在S4 class裡的member我們都叫做slot

我們可以用@把他們叫出來
> a@name
[1] "John"
> a@weight
[1] 65
> a@height
[1] 166

然後不同於S3 class,S4 class是用show()讓我們看到它裡面的slot
> show(a)
An object of class "BodyIndex"
Slot "name":
[1] "John"

Slot "weight":
[1] 65

Slot "height":
[1] 166

當然我們也可以修改它,只是要用setMethod()
> setMethod("show", "BodyIndex",
+     function(obj){
+         BMI<- obj@weight/((obj@height/100)^2)
+         cat(obj@name,"\n")    
+         cat("BMI is ", BMI)
+     }
+ )

> a
John 
BMI is  23.58833

S4 class的架構下可以用setGeneric()設定自己的generic function
> setGeneric("Warnning",
+     function(obj){
+         BMI<- obj@weight/((obj@height/100)^2)
+         if(BMI>35){
+             cat("You are over-weight")
+         }else{cat("You are normal")}
+     } 
+ )

> Warnning(a)
You are normal

當然也可以用setMethod()客制化

> setMethod("Warnning", "BodyIndex",
+     function(obj){
+         BMI<- obj@weight/((obj@height/100)^2)
+         if(BMI>35){
+             cat("You are over-weight")
+         }else{cat("Good for you~~")}
+     } 
+ )

> Warnning(a)
Good for you~~

2013年9月11日 星期三

[R] 效能(3) hash套件

hash table其實就是一種key-value的資料格式
像是Java的HashMap、Python裡的Dictionary等等

在R裡的list也是一種key-value資料格式,個人覺得蠻好用的,想塞甚麼就塞甚麼
但是如果要塞進list的東西很多,就會遇到麻煩的效能問題,就是速度會拖慢啦

hash套件提供一種key-value的資料格式就叫hash
在執行速度上比list要來得快頗多


1. 使用.set(hash, key = value,...) 函數給定key-value值

> library(hash)
>
> test<- hash()
>
> .set( test,
+   name = "AirQuality",
+   May = datasets::airquality[which(datasets::airquality$Mon==5),],
+   Jun = datasets::airquality[which(datasets::airquality$Mon==5),],
+   Jul = datasets::airquality[which(datasets::airquality$Mon==5),],
+   Aug = datasets::airquality[which(datasets::airquality$Mon==5),]
+  )
> 

然後就可以像list一樣輸入key值叫出value了!

> head(test[["May"]])
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6
>
> head(test$May)
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6
>

或是直接insert key-value也可以

> test$"Sep"<- datasets::airquality[which(datasets::airquality$Mon==5),]
> 
> head(test[["Sep"]])
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6


2. 用 has.key(key,hash) 和 keys(hash) 函數檢查hash裡有哪些key

> has.key(c("May","Jun"),test)
 May  Jun
TRUE TRUE
> keys(test)
[1] "Aug"  "Jul"  "Jun"  "May"  "name" "Sep"

3. 用copy(hash)函數複製hash

官方文件裡建議不要直接用<- assign給某物件,所以在assign的時候最好用copy(hash)函數把hash直接複製給物件

> test2<- copy(test)


4. 用clear(hash)函數清理hash

如果直接用rm(hash)的話,hash所佔據記憶體容量並不會釋放,得先用clear(hash)把hash清空然後再刪掉

> clear(test)
> is.empty(test)
[1] TRUE
> rm(test)

5. 效能比較

最後來做一個無聊實驗,比較把資料塞進進list和塞進hash裡在效能上究竟熟優熟劣

> test1<- hash()
> test2<- list()
> system.time(
+  for (i in 1:10000){
+   test1[[as.character(i)]]<- 1:i
+  }
+ )
   user  system elapsed
  1.082   0.059   1.139
> system.time(
+  for (i in 1:10000){
+   test2[[as.character(i)]]<- 1:i
+  }
+ )
   user  system elapsed
  1.770   0.199   2.057

速度大概是兩倍左右,完畢!



2013年9月9日 星期一

[Python] 超級基本的網頁抓取

這篇是完全沒有基礎的我最近的小小心得

厲害的爬蟲技巧在這裡完全都沒有喔~~~

沒辦法誰叫我實在是嫩了!




抓取步驟(EX: 中央氣象局台北市氣溫預報)

第一步:

先到想去的網頁,記下網址(廢話)

http://www.cwb.gov.tw/V7/forecast/taiwan/Taipei_City.htmimport urllib2

到想抓的東西上反藍後「檢查元素」



找到他的標籤

像我要找的這個東西的標簽就是「td」!!




然後把python打開

把該import的套件import(他們都是python內建的,算是非常仁慈)

然後繼承SGMLParser寫成一個叫做WeatherList的類別

『is_td』是SGMLParser內建的,因為我們要抓的東西是被「td」標簽的,所使在這裡是使用is_td,如果有不同需求也有is_a之類的可以使用。之後定義start_td和end_td函數,最後定義handle_data函數把被td標簽包住的東西全寫進name裡面。

import urllib2
from sgmllib import SGMLParser
 
class WeatherList(SGMLParser):
    is_td=""
    name=[]
    def start_td(self, attrs):
        self.is_td = 1
    def end_td(self):
        self.is_td=""
    def handle_data(self, text):  
        if self.is_td:
                self.name.append(text)  

寫完之後就可以開始抓囉!
content = urllib2.urlopen('http://www.cwb.gov.tw/V7/forecast/taiwan/Taipei_City.htm').read()

Tempreature = WeatherList()
Tempreature.feed(content)

for i in Tempreature.name:
    if '\t' not in i:
        print i.decode('utf-8')

首先先用urllib2的工具把目標網頁上的東西抓下來

然後把name裡的東西排除不要的東西(「\t」這種東西就別來亂了)

再把東西印出來,就可以囉~~
26 ~ 30
舒適至悶熱
0 %
26 ~ 34
舒適至易中暑
0 %
26 ~ 30
舒適至悶熱
0 %
31.1
24.8
360.5
05:38
18:05
08:53
20:27
°C
°F

2013年8月30日 星期五

[R] 效能(2) compiler套件

Compiler套件的功能是把寫好的R code變成位元碼(byte code),以加快執行速度。

對於懶得動腦優化程式的人還真是一大福音。

用下面這個蠢到不行的function來做demo,這個function傳回的是一條由1到n取log 的向量:

demo<- function(n){
  test<- 1:n
  for(i in length(test)){
    test[i]=log(test[i])
  }
  return(test)
}

用cmpfun函數把它轉成位元碼

> democmp<- compiler::cmpfun(demo)

先來做個十萬筆來比較看看有沒有變快

> system.time(a<- demo(100000))
   user  system elapsed 
  0.142   0.000   0.140 
> system.time(a<- democmp(100000))
  user  system elapsed 
  0.025   0.000   0.024 


現在我們把處裡的資料從十萬筆慢慢拉大到一百萬試試看!
經過窮極無聊的實驗可以發現,隨著函數處裡的資料量,效率的差別也會越明顯。在做大量資料運算的compile真的會是個好幫手喔!!!

2013年8月29日 星期四

[R] Big Data(1) rmr2套件 多重input

rmr2是一個可以使用R語言在Hadoop上做map-reduce的套件。

尚不知Hadoop和mapreduce為何物的人請參考這篇文章

以往做過的東西和網路上看得到的demo幾乎都是單一dataset利用鍵值(key)打散然後做平行運算。然而最近在處理的問題必須要把不同來源和結構(schema)的資料送到同一個node裡做運算,想說網路上找demo code卻遍尋不著,整個讓我非常頭大。

就在我試了老半天之後,竟然就成功了!!!於是就來寫一篇網誌告訴大家遇到好多個dataset的時候該怎麼辦~~~

用來demo的三組資料A、B、C
我們要做這件事:

資料長這樣(我隨便亂生的)。
> head(A)
  key         A1         A2         A3
1   1 -1.0348640  1.8177439  0.1352576
2   3 -1.3735558 -0.2437948 -0.4509937
3   2 -0.2034888  1.0297576  0.6305115
4   1  0.2270242  0.9087429 -0.4122123
5   3 -0.3290382 -0.4840644 -0.3688641
6   3 -0.1822808 -1.1303439 -0.4175791
> head(B)
  key           B1         B2          B3          B4
1   3  0.363861211  1.5158812 -1.20591630  0.08659873
2   3 -0.001122564  0.1037150  0.25809288  1.60135858
3   2  1.465006010 -0.4572000 -1.89767865 -0.60817508
4   2  1.964748118  0.8320135  0.50937176  0.77755846
5   1 -0.390667063  0.8493213  0.09075889  0.36958850
6   1 -0.768992997  0.7308232 -0.82277576  0.33674132
> head(C)
  key         C1         C2
1   1  0.4192436  0.1554905
2   2 -0.2125050 -1.4696090
3   1  0.3410178  0.3290381
4   2 -2.2716488  1.3529220
5   2 -0.2565037 -0.1575783
6   2 -0.4259541  0.1968482
接下來用函數split,把資料打散成一份一份的存成list格式。
> A_wk<- split(A,A$key)
> head(A_wk)
$`1`
   key         A1         A2          A3
1    1 -1.0348640  1.8177439  0.13525756
4    1  0.2270242  0.9087429 -0.41221232
13   1 -0.3573558 -1.2751938 -0.03458945
14   1 -0.7453312 -1.1503369  1.08577621
16   1  0.8465141  0.2366092  0.91902192
19   1  1.4896751  0.3213586 -0.98961302
23   1 -0.3143099  2.0754432 -1.29391057

$`2`
   key          A1          A2          A3
3    2 -0.20348880  1.02975761  0.63051151
7    2  1.53614888  1.96886642  0.04558348
9    2 -0.07431669 -0.03700706 -1.47200277
10   2  0.66355253  0.07667024 -1.22673427
17   2  1.13416422 -1.69200417 -0.13861365
18   2 -0.99696590  0.24465904  0.54821302
24   2 -0.44196754 -0.28170710 -0.73912548
27   2 -1.34823336 -0.06120274  2.12261003
30   2  1.83861168 -0.02982669  0.14312250

$`3`
   key         A1         A2         A3
2    3 -1.3735558 -0.2437948 -0.4509937
5    3 -0.3290382 -0.4840644 -0.3688641
6    3 -0.1822808 -1.1303439 -0.4175791
8    3  1.2317304 -0.7572487 -0.4401060
11   3 -0.4940248 -0.1259619 -1.1145702
12   3 -1.4488153 -0.9855823 -0.7537385
15   3 -0.6147528  0.6804414 -0.7799006
20   3  0.5340705 -0.2427455 -1.5272875
21   3 -1.2019567 -0.1434495 -0.3046498
22   3  0.1311908 -0.4900816  0.8861471
25   3 -1.1544569 -0.1732862 -2.2312314
26   3 -1.3264688 -0.6784207  1.5171326
28   3  1.1866616 -1.9195358  0.3591871
29   3  0.7476575 -0.3390230 -1.6448516

> B_wk<- split(B,B$key)
> head(B_wk)
$`1`
   key          B1         B2          B3            B4
5    1 -0.39066706  0.8493213  0.09075889  0.3695884990
6    1 -0.76899300  0.7308232 -0.82277576  0.3367413230
8    1 -1.05567857 -0.5663445  0.32075285  1.0807403069
9    1 -0.07174419 -0.6553943 -0.30134811 -1.2155568454
13   1 -0.39760179  0.5973388 -0.43153826 -0.0003626449
14   1  0.38234556 -0.4762401  0.90686094 -3.8579677970
15   1 -0.73177601 -0.6438049 -1.52620752  0.0814186088
20   1  0.07927141 -1.7918052 -1.27799659  0.1533002628

$`2`
   key          B1         B2          B3         B4
3    2  1.46500601 -0.4572000 -1.89767865 -0.6081751
4    2  1.96474812  0.8320135  0.50937176  0.7775585
7    2  0.35856113  0.1048170 -0.76270331 -0.5114040
10   2  1.11808088 -0.5707235 -0.16225111 -1.0749321
12   2 -0.32032713 -0.7167343 -0.03320639  0.2495948
18   2  1.36768551  1.1874533  2.13816520  1.0105115
19   2  0.02825361  0.8781400 -1.44303311  1.2391620

$`3`
   key           B1         B2         B3          B4
1    3  0.363861211  1.5158812 -1.2059163  0.08659873
2    3 -0.001122564  0.1037150  0.2580929  1.60135858
11   3  0.180619368 -0.8830636  0.7562675  1.09992035
16   3  2.644110325 -1.8546195  2.4887309 -0.03694847
17   3  1.131906794  0.9559589 -1.9111856  1.16240718

> C_wk<- split(C,C$key)
> head(C_wk)
$`1`
   key          C1         C2
1    1  0.41924361  0.1554905
3    1  0.34101785  0.3290381
14   1 -1.27793718 -0.2728525
18   1 -0.72084207  0.3307406
20   1  0.05193866 -0.4465938
27   1  1.03553670  1.7562845
29   1  2.35281628 -1.6114928
37   1  0.02295450 -0.9392724

$`2`
   key         C1         C2
2    2 -0.2125050 -1.4696090
4    2 -2.2716488  1.3529220
5    2 -0.2565037 -0.1575783
6    2 -0.4259541  0.1968482
7    2 -1.1866331 -0.3687882
13   2  0.7102612 -1.1221971
15   2  0.1592025  0.2775758
17   2  0.3842816 -0.6379072
22   2  0.1516206 -1.0723437
24   2 -0.4070279 -0.2998299
25   2  0.7779358 -0.2862851
28   2 -0.6860207 -0.9731296
30   2 -0.1319815  1.4057571
31   2  0.2845947 -0.3443439
33   2  0.7927496  0.9126125
34   2  0.4733910 -1.6850074

$`3`
   key          C1           C2
8    3 -0.13961645  0.204808027
9    3  1.49999162 -0.435241747
10   3 -0.94473626  1.768523536
11   3 -1.68380914 -0.172574070
12   3  1.12455947  0.611700128
16   3  0.19875147 -1.356228028
19   3  0.78590745 -0.796733981
21   3 -1.02839096  0.254459297
23   3 -1.00747198  0.593401435
26   3  0.81168025 -1.447740656
32   3  0.74883355 -0.170628912
35   3 -0.82805688 -1.792942718
36   3 -0.68229982  0.001420327
38   3  1.11185787  1.452839232
39   3  0.01296254 -0.676003236
40   3 -0.70681824 -0.027688693

打散之後我們用keyval函數把list的物件名稱(用names函數提取)當作key值(其實就是把打散的資料和key值兜在一起)
> Total<- keyval(c(names(A_wk),names(B_wk),names(C_wk)),c(A_wk,B_wk,C_wk))

之後放進mapreduce裡面! 因為已經用keyval把資料賦予key值,所以這裡我就不需要map了,直接在reduce裡面把資料還原成我要的東西。 先把資料用欄位名稱打散(在這裡不同dataset欄位名稱是不同的,如果有一樣的話請加上其他條件),打散之後再把它們合併成data.frame

> Demo<- mapreduce(
+     input = to.dfs(Total),
+     reduce = function(k,v){
+         test<- split(v,sapply(v,function(x) paste(colnames(x),collapse = "")))
+         test<- lapply(test,function(x) Reduce(rbind,x))
+         keyval(k,list(test[[1]],test[[2]],test[[3]]))
+     }
+ )
然後來看結果
> from.dfs(Demo)
$key
[1] "1" "1" "1" "2" "2" "2" "3" "3" "3"

$val
$val[[1]]
   key         A1         A2          A3
1    1 -1.0348640  1.8177439  0.13525756
4    1  0.2270242  0.9087429 -0.41221232
13   1 -0.3573558 -1.2751938 -0.03458945
14   1 -0.7453312 -1.1503369  1.08577621
16   1  0.8465141  0.2366092  0.91902192
19   1  1.4896751  0.3213586 -0.98961302
23   1 -0.3143099  2.0754432 -1.29391057

$val[[2]]
   key          B1         B2          B3            B4
5    1 -0.39066706  0.8493213  0.09075889  0.3695884990
6    1 -0.76899300  0.7308232 -0.82277576  0.3367413230
8    1 -1.05567857 -0.5663445  0.32075285  1.0807403069
9    1 -0.07174419 -0.6553943 -0.30134811 -1.2155568454
13   1 -0.39760179  0.5973388 -0.43153826 -0.0003626449
14   1  0.38234556 -0.4762401  0.90686094 -3.8579677970
15   1 -0.73177601 -0.6438049 -1.52620752  0.0814186088
20   1  0.07927141 -1.7918052 -1.27799659  0.1533002628

$val[[3]]
   key          C1         C2
1    1  0.41924361  0.1554905
3    1  0.34101785  0.3290381
14   1 -1.27793718 -0.2728525
18   1 -0.72084207  0.3307406
20   1  0.05193866 -0.4465938
27   1  1.03553670  1.7562845
29   1  2.35281628 -1.6114928
37   1  0.02295450 -0.9392724

$val[[4]]
   key          A1          A2          A3
3    2 -0.20348880  1.02975761  0.63051151
7    2  1.53614888  1.96886642  0.04558348
9    2 -0.07431669 -0.03700706 -1.47200277
10   2  0.66355253  0.07667024 -1.22673427
17   2  1.13416422 -1.69200417 -0.13861365
18   2 -0.99696590  0.24465904  0.54821302
24   2 -0.44196754 -0.28170710 -0.73912548
27   2 -1.34823336 -0.06120274  2.12261003
30   2  1.83861168 -0.02982669  0.14312250

$val[[5]]
   key          B1         B2          B3         B4
3    2  1.46500601 -0.4572000 -1.89767865 -0.6081751
4    2  1.96474812  0.8320135  0.50937176  0.7775585
7    2  0.35856113  0.1048170 -0.76270331 -0.5114040
10   2  1.11808088 -0.5707235 -0.16225111 -1.0749321
12   2 -0.32032713 -0.7167343 -0.03320639  0.2495948
18   2  1.36768551  1.1874533  2.13816520  1.0105115
19   2  0.02825361  0.8781400 -1.44303311  1.2391620

$val[[6]]
   key         C1         C2
2    2 -0.2125050 -1.4696090
4    2 -2.2716488  1.3529220
5    2 -0.2565037 -0.1575783
6    2 -0.4259541  0.1968482
7    2 -1.1866331 -0.3687882
13   2  0.7102612 -1.1221971
15   2  0.1592025  0.2775758
17   2  0.3842816 -0.6379072
22   2  0.1516206 -1.0723437
24   2 -0.4070279 -0.2998299
25   2  0.7779358 -0.2862851
28   2 -0.6860207 -0.9731296
30   2 -0.1319815  1.4057571
31   2  0.2845947 -0.3443439
33   2  0.7927496  0.9126125
34   2  0.4733910 -1.6850074

$val[[7]]
   key         A1         A2         A3
2    3 -1.3735558 -0.2437948 -0.4509937
5    3 -0.3290382 -0.4840644 -0.3688641
6    3 -0.1822808 -1.1303439 -0.4175791
8    3  1.2317304 -0.7572487 -0.4401060
11   3 -0.4940248 -0.1259619 -1.1145702
12   3 -1.4488153 -0.9855823 -0.7537385
15   3 -0.6147528  0.6804414 -0.7799006
20   3  0.5340705 -0.2427455 -1.5272875
21   3 -1.2019567 -0.1434495 -0.3046498
22   3  0.1311908 -0.4900816  0.8861471
25   3 -1.1544569 -0.1732862 -2.2312314
26   3 -1.3264688 -0.6784207  1.5171326
28   3  1.1866616 -1.9195358  0.3591871
29   3  0.7476575 -0.3390230 -1.6448516

$val[[8]]
   key           B1         B2         B3          B4
1    3  0.363861211  1.5158812 -1.2059163  0.08659873
2    3 -0.001122564  0.1037150  0.2580929  1.60135858
11   3  0.180619368 -0.8830636  0.7562675  1.09992035
16   3  2.644110325 -1.8546195  2.4887309 -0.03694847
17   3  1.131906794  0.9559589 -1.9111856  1.16240718

$val[[9]]
   key          C1           C2
8    3 -0.13961645  0.204808027
9    3  1.49999162 -0.435241747
10   3 -0.94473626  1.768523536
11   3 -1.68380914 -0.172574070
12   3  1.12455947  0.611700128
16   3  0.19875147 -1.356228028
19   3  0.78590745 -0.796733981
21   3 -1.02839096  0.254459297
23   3 -1.00747198  0.593401435
26   3  0.81168025 -1.447740656
32   3  0.74883355 -0.170628912
35   3 -0.82805688 -1.792942718
36   3 -0.68229982  0.001420327
38   3  1.11185787  1.452839232
39   3  0.01296254 -0.676003236
40   3 -0.70681824 -0.027688693
OK,和我想要的一樣!
前面三組dataset屬於key "1"
中間三組dataset屬於key "2"
後面三組dataset屬於key "3"
大功告成!!!
在reduce裡面可以加上更多的東西,像是資料表之間彼此join之類的運算。

2013年8月28日 星期三

[R] 效能(1) apply和他的快樂朋友們

在R的世界裡,for迴圈是幾乎所以R programmer都要盡量避免的,因為for迴圈真的很容易拖慢速度!

apply系列的函數可以把運算向量化(vectorization),讓程式簡潔快速喔!!!並且可以和還在用for迴圈的新手們炫耀自己的功力。

先來看看Demo的資料,都是R內建的
> library(datasets)
> head(cars)
  speed dist
1     4    2
2     4   10
3     7    4
4     7   22
5     8   16
6     9   10
> head(airquality)
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6

1. apply(資料名稱,計算方向,套用函數)

apply算是基本款的,但是就已經蠻強大的了

其中計算方向比較需要注意:
1 表示逐列
2 表示逐行

EX: 用apply函數來計算demo資料cars中不同欄位的平均數或者檢查資料格式,通通一行搞定!
> apply(cars,2,mean)
speed  dist
15.40 42.98
> apply(cars,2,class)
    speed      dist 
"numeric" "numeric" 

2. tapply(資料$欄位,分層欄位,套用函數)

個人認為tapply還蠻好用的,尤其是要做分層的時候,功能就像是SQL語法的group by

EX: 我們可以用它來計算demo資料airquality中不同月份(Month)的最大風速(Wind)
> tapply(airquality$Wind, airquality$Month,max)
   5    6    7    8    9
20.1 20.7 14.9 15.5 16.6 

3. sapply(列表或向量,套用函數) 

是作用在列表(list)或是向量(vector)上面的

EX: 把向量a通通取絕對值!
> sapply(-4:4,abs)
[1] 4 3 2 1 0 1 2 3 4
> a<- -4:4
> a
[1] -4 -3 -2 -1  0  1  2  3  4

或者把a這個list裡面的東東通通取平均
> a=list(a=c(1,2,3),b=c(2,3,4),c=c(3,4,5))
> a
$a
[1] 1 2 3

$b
[1] 2 3 4

$c
[1] 3 4 5

> sapply(a,mean)
a b c 
2 3 4 

4. mapply(函數,函數引數)

mapply其實就是sapply的多重版,可以放數多個函數引述

EX: 由N(0,1)中做五次抽樣,第一次抽一個樣本,第二次抽兩個樣本,...第五次抽五個樣本

> mapply(rnorm, n=1:7, mean=0, sd=1)
[[1]]
[1] -2.112067
[[2]]
[1]  0.7254029 -1.2384776
[[3]]
[1]  0.8083143 -1.6875636  0.6863660
[[4]]
[1]  2.0391266  0.2182393 -0.6225456  0.4714035
[[5]]
[1] 1.0811637 0.1209754 1.1659376 0.5173664 0.1244459

5. lapply(列表或向量,套用函數)

傳回列表(list)的apply函數

EX: 向量a中每個元素都+1並存在列表(list)裡
> > a <-1:4> a
[1] 1 2 3 4
> lapply(a,function(x) x+1)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

[[4]]
[1] 5

6. rapply(列表或向量,套用函數) 

針對嵌套列表(nested list就是,list中又有list的東東)的apply函數

how選項可以決定要不要針對各list裡的value

EX: 加總(how="unlist")
> a<- list(x1=1:5,x2=2:7)
> b<- list(x1=7:5,x2=0:7)
> rapply(list(a,b),sum,how="unlist")
x1 x2 x1 x2 
15 27 18 28 
EX: 加總(how="list")
> rapply(list(a,b),sum,how="list")
[[1]]
[[1]]$x1
[1] 15

[[1]]$x2
[1] 27


[[2]]
[[2]]$x1
[1] 18

[[2]]$x2
[1] 28