2017-01-08 14 views
1

當我試圖在相同的正則和稀疏矩陣上應用log函數時,獲得的結果是不同的。在應用這些功能時,我應該記住什麼?以下是一個可重複的例子。當對數函數應用於相同的正則矩陣和稀疏矩陣時,爲什麼結果會不同?

TestMatrix = matrix(c(3,1,0,0,0,4,0,1,0,0,2,1,1,2,0,6,1,0,1,0,1,0,0,0,0),5,byrow = TRUE) 
TestSparseMatrix = Matrix(TestMatrix,sparse = TRUE) 
# Logarithmic function when applied to regular matrix 
-log(TestMatrix/rowSums(TestMatrix), 2) 


#Output 
#   [,1]  [,2]  [,3]  [,4] [,5] 
#[1,] 0.4150375 2.000000  Inf  Inf Inf 
#[2,] 0.3219281  Inf 2.321928  Inf Inf 
#[3,] 1.5849625 2.584963 2.584963 1.584963 Inf 
#[4,] 0.4150375 3.000000  Inf 3.000000 Inf 
#[5,] 0.0000000  Inf  Inf  Inf Inf 


# Logarithmic function when applied to Sparse matrix 
-log(TestSparseMatrix/rowSums(TestSparseMatrix), 2) 


# Output 
#   [,1]  [,2]  [,3]  [,4] [,5] 
#[1,] 0.2876821 1.386294  Inf  Inf Inf 
#[2,] 0.2231436  Inf 1.609438  Inf Inf 
#[3,] 1.0986123 1.791759 1.791759 1.098612 Inf 
#[4,] 0.2876821 2.079442  Inf 2.079442 Inf 
#[5,] 0.0000000  Inf  Inf  Inf Inf 

回答

4

log()爲稀疏矩陣(一個 「S4」 對象)忽略base。使用log2消除了問題:

-log2(TestSparseMatrix/rowSums(TestSparseMatrix)) 

對 「S4方法」 的?log一部分讀。我相信這不是衆所周知的。

Note that this means that the S4 generic for ‘log’ has a signature 
with only one argument, ‘x’, but that ‘base’ can be passed to 
methods (but will not be used for method selection). On the other 
hand, if you only set a method for the ‘Math’ group generic then 
‘base’ argument of ‘log’ will be ignored for your class. 

如果你不知道,你可以進一步閱讀:

?groupGeneric 
?S4groupGeneric 

或等價(你會被重定向到上述手冊頁):

?base::Math 
?methods::Math 

這是真的與「Math」組的定義有關。從?S4groupGeneric特別引述:

Note that two members of the ‘Math’ group, ‘log’ and ‘trunc’, have 
... as an extra formal argument. Since methods for ‘Math’ will 
have only one formal argument, you must set a specific method for 
these functions in order to call them with the extra argument(s). 

所以,如果你想取對數與任意的,有效的base,說base = 3?用公式:

log(x, base = 3) = log(x)/log(3) 

例如,您TestSparseMatrix,你也可以這樣做:

-log(TestSparseMatrix/rowSums(TestSparseMatrix))/log(2)