In [7]:
import math
import numpy as np
def entropy(ss = 'gargleblaster'):
ssit = {i for i in ss}
n = len(ss)*1.
entropy = 0
for c in ssit:
p_x = ss.count(c)*1./n
if p_x > 0:
entropy += -(p_x)*math.log(p_x,2)
# print("{} {} {}".format(c,ss.count(c),p_x))
# print(ssit)
return entropy
In [8]:
# 丟銅板為例
print(entropy("111111"))
print(entropy("111001"))
In [9]:
# 也可以計算任何字串
print(entropy("lkejrlejrlewjrlewr"))
In [10]:
Y = np.array([1,1,0,0,1])
A = np.array([0.8, 0.7, 0.2, 0.1, 0.9])
A2 = np.array([0.6, 0.6, 0.2, 0.1, 0.3])
In [12]:
import numpy as np
def cross_entropy(Y, A):
m = len(A)
cost = -(1.0 / m) * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
return cost
In [14]:
print(cross_entropy(Y,A))
print(cross_entropy(Y,A2))
In [ ]: