從RDD

2017-03-28 34 views
1

創建2D矩陣我有類型的以下RDD((用戶ID,MovieID),1):從RDD

val data_wo_header=dropheader(data).map(_.split(",")).map(x=>((x(0).toInt,x(1).toInt),1)) 

欲該數據結構轉換成一個二維數組,使得所有元素(用戶ID電影ID)有一個1 else 0

我認爲我們必須映射用戶ID爲0-N,如果N是不同用戶的數量並將電影ID映射到0-M如果不是不同電影的數量。

編輯:如你提到的例子

 Movie ID-> 

Userid 1 2 3 4 5 6 7 

1  0 1 1 0 0 1 0 
2  0 1 0 1 0 0 0 
3  0 1 1 0 0 0 1 
4  1 1 0 0 1 0 0 
5  0 1 1 0 0 0 1 
6  1 1 1 1 1 0 0 
7  0 1 1 0 0 0 0 
8  0 1 1 1 0 0 1 
9  0 1 1 0 0 1 0 

The RDD will be of the sort 
(userID, movID,rating) 
101,1002,3.5 
101,1003,2.5 
101,1006,3 
102,1002,3.5 
102,1004,4.0 
103,1002,1.0 
103,1003,1.0 
103,1007,5.0 
…. 
+0

你可以分享預期的輸出格式? – BDR

+0

您可以將輸出視爲每個用戶ID帶有1和0值的2D矩陣,您可以給我一個格式的電影ID對 –

+0

。無法直觀地看到您正在查找的內容 – BDR

回答

0

HI我管理使用下面的函數來生成的2D矩陣。這需要在格式

((userID, movID),rating) 
101,1002,3.5 
101,1003,2.5 
101,1006,3 
102,1002,3.5 
102,1004,4.0 
103,1002,1.0 
103,1003,1.0 
103,1007,5.0 

的RDD並返回特徵矩陣:

def generate_characteristic_matrix(data_wo_header:RDD[((Int, Int), Int)]):Array[Array[Int]]={ 
    val distinct_user_IDs=data_wo_header.sortByKey().map(x=>x._1._1).distinct().collect().sorted 
    val distinct_movie_IDs=data_wo_header.sortByKey().map(x=>x._1._2).distinct().collect().sorted 

    var movie_count=distinct_movie_IDs.size 
    var user_count=distinct_user_IDs.size 

    var a =0 
    var map_movie = new ArrayBuffer[(Int, Int)]() 
    var map_user = new ArrayBuffer[(Int, Int)]() 
    //map movie ID's from (0,movie_count) 
    for(a <- 0 to movie_count-1){ 
     map_movie+=((distinct_movie_IDs(a),a)) 
    } 
    //map user ID's from (0,user_count) 
    for(a <- 0 to user_count-1){ 
     map_user+=((distinct_user_IDs(a),a)) 
    } 
    //size of char matrix is user_countxmovie_count 
    var char_matrix = Array.ofDim[Int](user_count,movie_count) 
    data_wo_header.collect().foreach(x => { 
     var user =x._1._1 
     var movie=x._1._2 
     var movie_mappedid=map_movie.filter(x=>x._1==movie).map(x=>x._2).toArray 
     var user_mappedid=map_user.filter(x=>x._1==user).map(x=>x._2).toArray 
     char_matrix(user_mappedid(0))(movie_mappedid(0))=1 
    }) 
    return char_matrix 
    } 
0
val baseRDD = sc.parallelize(Seq((101, 1002, 3.5), (101, 1003, 2.5), (101, 1006, 3), (102, 1002, 3.5), (102, 1004, 4.0), (103, 1002, 1.0), (103, 1003, 1.0), (103, 1007, 5.0)))  
     baseRDD.map(x => (x._1, x._2)).groupByKey().foreach(println) 

(用戶ID,movID,等級)格式

結果:

(101,CompactBuffer(1002,1003,1006 ))

(102,CompactBuffer(1002,1004))

(103,CompactBuffer(1002,1003,1007))

+0

但是我們如何生成/打印0 1 0矩陣? –

+0

你的意思是說,你還希望用戶給出的評分?類似於tis(101(1002,4.0),(1003,3.5),(1006,4.0))?? – BDR

+0

我剛剛修改了這個問題。我想以編輯中顯示的格式打印矩陣。矩陣具有元素0 1 1 0 0 1 0,用戶ID 101由矩陣的行1表示。由Matrix的第1列表示的電影ID 1001。同樣的電影ID 1002由第2列代表等等 –