R中的归一化累积折扣收益公式

问题描述 投票:0回答:1

我想用R在函数中编写下一个公式:

normalized cumulative discount gain

应该位于R软件包中,但是一旦安装,该软件包就不存在了...

# original source: 
https://www.rdocumentation.org/packages/rrecsys/versions/0.9.5.4/topics/nDCG
#Alternative source:
https://en.wikipedia.org/wiki/Discounted_cumulative_gain

该功能的使用是将两个向量作为输入。

# example
v1=c(1,2,3,4)
v2=c(1,3,2,4)
nDGC(v1,v2)

任何人都可以帮助我以有效的方式对其进行编码吗?

DGC的python版本是:

rel = zip(range(1,7),[3,2,3,0,1,2])
dcg6 = rel[0][1] + sum(map(lambda (a,b):b/math.log(a,2),rel[1:]))
print dcg6
r function recommender-systems
1个回答
1
投票

这是Wikipedia中方程式的直接R实现,其中包括一些错误检查:


第一等式

enter image description here

DCG_pos <- function(rel, p)
{
  if(missing(p)) p <- length(rel)
  stopifnot(p <= length(rel))

  sum(rel[seq(p)]/log(seq(p) + 1, 2))
}

第二等式

enter image description here


IDCG_pos <- function(rel, p)
{
  if(missing(p)) p <- length(rel)
  stopifnot(p <= length(rel))

  sum((2^(rel[seq(p)]) - 1)/log(seq(p) + 1, 2))
}

第三等式

enter image description here

nDGC_pos <- function(rel, p)
{
  if(missing(p)) p <- length(rel)
  stopifnot(p <= length(rel))

  DCG_pos(rel, p) / IDCG_pos(rel, p)
}

您可以这样使用它们:

DCG_pos(1:5, 5)
#> [1] 7.41883
IDCG_pos(1:5, 5)
#> [1] 24.84537
nDGC_pos(1:5, 5)
#> [1] 0.2986

reprex package(v0.3.0)在2020-03-10创建

© www.soinside.com 2019 - 2024. All rights reserved.