【发布时间】:2017-11-22 12:48:17
【问题描述】:
以下代码运行结果出乎意料,我觉得有点奇怪,先定义featfun():
featfun <- function(yi_1, yi, i) {
all_fea <- list(c(1, 2, 2),
c(1, 2, 3),
c(1, 1, 2),
c(2, 1, 3),
c(2, 1, 2),
c(2, 2, 3),
c( 1, 1),
c( 2, 1),
c( 2, 2),
c( 1, 2),
c( 1, 3),
c( 2, 3))
weights <- c(1,1,0.6,1,1,0.2,1,0.5,0.5,0.8,0.8,0.5)
idx1 <- 0; idx2 <- 0
if (list(c(yi_1, yi, i)) %in% all_fea) {
idx1 <- which(all_fea %in% list(c(yi_1, yi, i)))
}
if (list(c(yi, i)) %in% all_fea) {
idx2 <- which(all_fea %in% list(c(yi, i)))
}
if (idx1 != 0 & idx2 != 0) {
return(list(c(1, weights[idx1]), c(1, weights[idx2])))
} else if (idx1 != 0 & idx2 == 0) {
return(list(c(1, weights[idx1])))
} else if (idx1 == 0 & idx2 != 0) {
return(list(c(1, weights[idx2])))
} else {
return(NA)
}
}
> featfun(1,1,2)
[[1]]
[1] 1.0 0.6
[[2]]
[1] 1.0 0.8
我把featfun()和for循环结合起来:
> for (k in seq(2,3)) {
+ cat("k=",k,"\n")
+ for (i in seq(1, 2)) {
+ cat("i=", i,"\n")
+ print(featfun(1, i, k))
+ }
+ }
k= 2
i= 1
[[1]]
[1] 1.0 0.6
i= 2
[[1]]
[1] 1 1
[[2]]
[1] 1.0 0.5
k= 3
i= 1
[[1]]
[1] 1.0 0.8
i= 2
[[1]]
[1] 1 1
我们可以看到,当k = 2,i = 1时,只返回第一个元素“[1] 1.0 0.6”,而第二个元素缺失,与featfun(1 ,1,2)。
此外,我使用 python 重写了代码。以下是python代码:
def featfun(yi_1, yi, i):
all_fea = [
[1,2,2],
[1,2,3],
[1,1,2],
[2,1,3],
[2,1,2],
[2,2,3],
[ 1,1],
[ 2,1],
[ 2,2],
[ 1,2],
[ 1,3],
[ 2,3]]
weights = [1,1,0.6,1,1,0.2,1,0.5,0.5,0.8,0.8,0.5]
idx1 = 999
idx2 = 999
if [yi_1,yi,i] in all_fea:
idx1 = all_fea.index([yi_1, yi, i])
if [yi, i] in all_fea:
idx2 = all_fea.index([yi, i])
if (idx1!=999)&(idx2!=999):
return [[1,weights[idx1]],[1,weights[idx2]]]
elif (idx1!=999)&(idx2==999):
return [1,weights[idx1]]
elif (idx1==999)&(idx2!=999):
return [1,weights[idx2]]
else:
return None
featfun(1,1,2) 返回 [[1, 0.6], [1, 0.8]]。
然后我再次将 python_based featfun 与 for 循环结合起来:
for k in [2,3]:
for i in [1,2]:
return featfun(1,i,k)
以下是返回结果,正确的结果,和课本上的答案一样。
[[1, 0.6], [1, 0.8]]
[[1, 1], [1, 0.5]]
[1, 0.8]
[[1, 1], [1, 0.5]]
我的 R 代码会发生什么?或者R中似乎有问题? 我希望有一个人可以帮助我!谢谢!
【问题讨论】:
-
您的代码中似乎有很多次
It looks like your post is mostly code, please add some more details。您能否编辑这些 cmets 并添加更多详细信息(如果适用)。 -
这是一个条件随机场模型的简单实现,来自教科书,中文版。对不起..
-
如果您想激励某人回答您,请编辑问题并添加更多关于条件随机字段的背景。例如,为什么要得到预期的结果?现在还不清楚为什么预期的结果比你得到的结果好..
标签: python r function loops for-loop