2014年10月19日日曜日

Rのsvd(特異値分解)で次元の圧縮

Rではsvdを使って次元の圧縮が可能
svdでは任意の行列を3つの行列に分解します。

> #適当な行列を作る。(2次元の特徴量が3個あるイメージ)
> x=matrix(1:6, nrow=2, ncol=3)
> 
> #中身はこんな感じ
> x
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> 
> #特異値分解
> svd=svd(x)
> 
> #次の3つの行列に分解される。
> A=diag(svd$d)
> U=svd$u
> V=svd$v
> 
> #上記の3つの行列の積は元の行列と一致する。
> U %*% A %*% t(V)
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
次元の圧縮をしたいときはこんな感じ
> #次元圧縮はこんな関数にしておくと便利
> reduce <- function(x,svd,reduced_dimension) {
+     result=t(svd$u[,1:reduced_dimension]) %*% x 
+     return(result)
+ }
> 
> x=matrix(1:6, nrow=2, ncol=3)
> svd=svd(x)
> 
> #2次元だったものを1次元に圧縮
> reduce(x,svd,1)
          [,1]      [,2]      [,3]
[1,] -2.189418 -4.998466 -7.807514


詳しい原理は下記参照
http://en.wikibooks.org/wiki/Data_Mining_Algorithms_In_R/Dimensionality_Reduction/Singular_Value_Decomposition

0 件のコメント:

コメントを投稿