Я пытаюсь реализовать следующий код, написанный с помощью pandas, в более общую версию, используя только Numpy. Код также находится здесь :
attribute = 'Taste'
target_variables = df.Eat.unique() #This gives all 'Yes' and 'No'
variables = df[attribute].unique() #This gives different features in that attribute (like 'Sweet')
entropy_attribute = 0
for variable in variables:
entropy_each_feature = 0
for target_variable in target_variables:
num = len(df[attribute][df[attribute]==variable][df.Eat ==target_variable]) #numerator
den = len(df[attribute][df[attribute]==variable]) #denominator
fraction = num/(den+eps) #pi
entropy_each_feature += -fraction*log(fraction+eps) #This calculates entropy for one feature like 'Sweet'
fraction2 = den/len(df)
entropy_attribute += -fraction2*entropy_each_feature #Sums up all the entropy ETaste
Вот моя попытка:
def entropy_by_attribute(dataset, feature):
attribute = dataset[,:feature]
target_variables = numpy.unique(dataset[:,-1])
variables = numpy.unique(attribute)
entropy_attribute = 0
for variable in variables:
entropy_each_feature = 0
for target_variable in target_variables:
num =
den =
fraction = num / (den + eps)
entropy_each_feature = entropy_each_feature + (-fraction*log(fraction+eps))
fraction2 = den/len(dataset)
entropy_attribute = entropy_attribute + (-fraction2*entropy_each_feature)
return abs(entropy_attribute)
Что меня смущает, так это как конвертировать числитель и знаменатель. Я не понимаю, что делает len(df[attribute][df[attribute]==variable][df.Eat ==target_variable])
.
Для справки, вот набор данных, который использует пример панд:
dataset = {'Taste':['Salty','Spicy','Spicy','Spicy','Spicy','Sweet','Salty','Sweet','Spicy','Salty'],
'Temperature':['Hot','Hot','Hot','Cold','Hot','Cold','Cold','Hot','Cold','Hot'],
'Texture':['Soft','Soft','Hard','Hard','Hard','Soft','Soft','Soft','Soft','Hard'],
'Eat':['No','No','Yes','No','Yes','Yes','No','Yes','Yes','Yes']}
Может ли кто-нибудь помочь мне понять объявления num
и den
, чтобы я мог продолжить это преобразование? Я не понимаю, что они представляют в данном случае или что такое eps
.
Спасибо