0

我正在尝试将以下用 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])在做什么。

作为参考,这里是 pandas 示例使用的数据集:

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']}

有人可以帮助我理解numandden声明,以便我可以继续这种转换吗?我不明白它们在这种情况下代表什么,或者是什么eps

谢谢

4

1 回答 1

0

num计算同时包含 Eat 的目标变量('Yes' 或 'No')和变量 attribute 的行的次数。

den计算变量属性出现的次数。

让我们将“Salty”作为 Taste 属性,将“No”作为 Eat 的目标变量。现在分子是 2,因为我们有两个 ('No', 'Salty') 对,分母是 3,因为 'Salty' 出现了 3 次。

如果您查看您提供的链接,您会发现 eps 的含义。 eps = np.finfo(float).eps

我引用:

这里的“eps”是可表示的最小数字。有时我们会在分母中得到 log(0) 或 0,以避免我们将使用它。

在这种情况下,Eps 用于通过使用可能的最小数字来避免除以零。

计算num而不den使用 pandas 可以这样完成:

attribute = 'Taste'
variables = numpy.unique(dataset[attribute])
target_variables = numpy.unique(dataset["Eat"])
entropy_attribute = 0
for variable in variables:
entropy_each_feature = 0
for target_variable in target_variables:
    num = 0
    den = 0
    for index in range(0,len(dataset[attribute])):
        if dataset[attribute][index] == variable and dataset["Eat"][index] == target_variable:
            num += 1
        if dataset[attribute][index] == variable:
            den += 1

使用 numpy 操作而不是基于索引的比较可能有一种更快/更清洁的方法,但我对它不是很熟悉。

于 2019-03-22T16:43:40.683 回答