f = tanh这样的函数可以写成df = f *(delta(i,j)-f)。当g是矢量或列矩阵时,可以使用循环,转置和应用来编程df,编程如下。
set.seed(5)
g1<-matrix(rnorm(3),ncol=1)
f1<-tanh(g1)
df1a = matrix(NA,nrow=nrow(f1),ncol=nrow(f1))
df1b = matrix(NA,nrow=nrow(f1),ncol=nrow(f1))
for (i in seq(1,nrow(f1))) {
for (j in seq(1,nrow(f1))) {
df1a[i,j] = -f1[j]*f1[i]
df1b[i,j] = -f1[j]*f1[i]
}
df1b[i,i] = df1b[i,i]+f1[i]
}
df2a <- -f1 %*% t(f1)
df2b <- diag(as.list(f1))+df2a
df3a <- (-1)*apply(f1,1,'*',f1)
df3b <- diag(as.list(f1))+df3a
does_m1_m2_match = all.equal(df1b, df2b, tolerance = 1e-5)
does_m1_m3_match = all.equal(df1b, df3b, tolerance = 1e-5)
does_m1_m2_match
does_m1_m3_match
当g是矩阵时如何扩展它,并且应该被视为列向量的集合。这是循环实现。如何进行申请实施?
ddf2a = array(NA,c(nrow(f2),nrow(f2),ncol(f2)))
ddf2b = array(NA,c(nrow(f2),nrow(f2),ncol(f2)))
for (k in seq(1,ncol(f2))) {
for (i in seq(1,nrow(f2))) {
for (j in seq(1,nrow(f2))) {
ddf2a[i,j,k] = -f2[j]*f2[i]
ddf2b[i,j,k] = -f2[j,k]*f2[i,k]
}
ddf2b[i,i,k] = ddf2b[i,i,k]+f2[i,k]
}
}
for (k in seq(1,ncol(f2))) {
does_m1_md_match = all.equal(df1b, ddf2b[,,k], tolerance = 1e-5)
print(paste('k',k,does_m1_md_match))
}