请让我们考虑一下这段代码
function averageentropy=calculate(f,y)
count1=0;
count0=0;
n=length(f);
n1=0;
n0=0;
entrop1=0;
entrop2=0;
bigp=sum(f)/n;
indf1 = f == 1;
indf0 = ~indf1 ;
indy1 = y == 1;
indy0 = ~indy1 ;
count1 = sum(indf1 & indy1) ;
count0 = sum(indf0 & indy0) ;
n1 = sum(indf1);
n0 = sum(indf0);
smallpplus=count1/n1;
smallpminus=count0/n0;
if smallpplus==0 || (1-smallpplus==0)
entrop1=0;
else
entrop1=-smallpplus*log2(smallpplus)-(1- smallpplus)*log2(1- smallpplus);
end
if smallpminus==0 || (1-smallpminus==0)
entrop2=0;
else
entrop2=-smallpminus*log2(smallpminus)-(1- smallpminus)*log2(1- smallpminus);
end
averageentropy=bigp*entrop1+(1-bigp)*entrop2;
end
我想要关注的事情,首先考虑关注f2和y的数据
f2
0
0
0
1
1
1
0
1
和
y
1
1
1
0
0
0
0
0
我想计算以下步骤
1.计算bigp,其在f2中等于1除以f2的长度,这段代码很好地完成了这部分
2.1我定义了小p加上这个数除以f2中的数字1
3.i想要计算y中1的数字,其中f2 = 0
3.1我定义了小p减去这个数字除以总数f2 = 0
最后我想计算平均熵,公式用代码表示
应该得到的是0.47,但我得到0.4,pl;轻松帮我解决这个问题
已更新 我认为这一行应该是错误
count1 = sum(indf1 & indy1) ;
count0 = sum(indf0 & indy1) ;
更准确地说
count0 = sum(indf0 & indy1)
count0 =
3
有错误,必须有3/8 = 0.375
答案 0 :(得分:1)
既然你说过“我在Excel中完成了这个计算,我知道正确答案是什么”,我决定将上面的代码“转换成excel”(确切地说是VBA)。当我对给定的两个向量进行计算时,得到大约0.4的熵(即0.3936) - 而不是你声称应该得到的0.47。
那么 - “正确”答案是什么,你怎么知道?
我问的原因是:一旦我们在任何语言中使用“工作代码”,如果您遇到翻译,我们可以帮助您。但是当我们不知道你想要做什么时(这可能只是语言障碍),我们无法帮助你。
作为参考,以下是您在VBA中的上述代码:让我们按照您的意图做到这一点,然后我们将翻译。 OK?
Option Explicit
Function calculateEntropy(f, y)
Dim indf1(), indf0(), indy1(), indy0()
Dim count0, count1
Dim n, n0, n1, ii
Dim entrop1, entrop2
Dim bigp, littlep, smallPplus, smallPminus
count1 = 0
count0 = 0
n = UBound(f)
ReDim indf1(1 To n)
ReDim indf0(1 To n)
ReDim indy1(1 To n)
ReDim indy0(1 To n)
n1 = 0
n0 = 0
entrop1 = 0
entrop2 = 0
count1 = 0
count0 = 0
bigp = WorksheetFunction.Sum(f) / n
For ii = 1 To n
If (f(ii) = 1) Then
indf1(ii) = 1
indf0(ii) = 0
Else
indf1(ii) = 0
indf0(ii) = 1
End If
If (y(ii) = 1) Then
indy1(ii) = 1
indy0(ii) = 0
Else
indy1(ii) = 0
indy0(ii) = 1
End If
Next ii
For ii = 1 To n
n1 = n1 + indf1(ii)
n0 = n0 + indf0(ii)
If (indf1(ii) = 1 And indy1(ii) = 1) Then count1 = count1 + 1
If (indf1(ii) = 0 And indy0(ii) = 0) Then count0 = count0 + 1
Next ii
smallPplus = count1 / n1
smallPminus = count0 / n0
If smallPplus = 0 Or (1 - smallPplus) = 0 Then
entrop1 = 0
Else
entrop1 = -smallPplus * Log(smallPplus) - (1 - smallPplus) * Log(1 - smallPplus)
End If
If smallPminus = 0 Or (1 - smallPminus) = 0 Then
entrop2 = 0
Else
entrop2 = -smallPminus * Log(smallPminus) - (1 - smallPminus) * Log(1 - smallPminus)
End If
' note - have to divide whole thing by Log(2) since VBA does not have LOG2() function built in)
calculateEntropy = (bigp * entrop1 + (1 - bigp) * entrop2) / Log(2)
End Function
Sub test()
Dim f()
Dim y()
f = Array(0, 0, 0, 1, 1, 1, 0, 1)
y = Array(1, 1, 1, 0, 0, 0, 0, 0)
MsgBox "entropy is " & calculateEntropy(f, y)
End Sub