数据清洗:函数依赖及其发现算法(附Python代码)

1 函数依赖

  一个函数依赖(Functional Dependency) X → A X\rightarrow A XA是对关系模式 R R R的一个声明,其中 X ⊆ R X\subseteq R XR A ∈ R A\in R AR。所有元组 t 1 , t 2 ∈ R t_{1},t_{2}\in R t1,t2R,满足一下条件:如果 t 1 [ X ] = t 2 [ X ] t_{1}[X]=t_{2}[X] t1[X]=t2[X],则 t 1 [ A ] = t 2 [ A ] t_{1}[A]=t_{2}[A] t1[A]=t2[A],那么这个函数依赖在关系 R R R的实例 r r r上是成立的。 X X X成为FD的左部, A A A为FD的右部。

  • 非平凡函数依赖 X → A X\rightarrow A XA:如果 X → A X\rightarrow A XA成立且属性 A A A不属于 X X X,即 A ∉ X A\notin X A/X,则称函数依赖 X → A X\rightarrow A XA是非平凡的;
  • 最小函数依赖 X → A X\rightarrow A XA:如果 X → A X\rightarrow A XA成立且 X X X的任意一个真子集 Y Y Y都不能决定属性 A A A,即 Y → A Y\rightarrow A YA均不成立,则 X → A X\rightarrow A XA为最小函数依赖;

  函数依赖具有以下三个重要的性质:

  • 如果 Y Y Y X X X的子集,即 Y ⊆ X Y\subseteq X YX,则 X → Y X \rightarrow Y XY;
  • 如果 X → Y X\rightarrow Y XY,则 X Z → Y XZ\rightarrow Y XZY
  • 如果 X → Z X\rightarrow Z XZ Z → W Z\rightarrow W ZW,则 X → W X\rightarrow W XW;

2 Python实现

  最经典的函数依赖发现算法为TANE算法,其具体原理及Python代码可以查看参考文献1、2、3。关于这个算法我也有些内容没有完全弄懂。关于下述函数依赖发现代码,以下几点需要先说明:

  • 这个方法采用的是暴力穷举的策略,当数据集的属性较多时,不建议使用此方法。
  • 示例代码中使用的数据集为abalone,这个数据集可以自行从网络上下载。
  • 在abalone数据集上,使用参数文献3中的代码发现了119个FD,但下述代码共生成了137个FD(另一篇文献中也是生成了137个)。

具体代码如下:

import pandas as pd
import warnings
warnings.filterwarnings('ignore')
from itertools import combinations

data=pd.read_csv(r'abalone.data',sep=',',header=None)
data.columns=list('ABCDEFGHI')

def compute_entropy(LHS,RHS):
    tmp=data.groupby(LHS)[RHS].nunique()
    entropy=(tmp>1).sum()
    return entropy

FD_list=[]
for r in range(2,data.shape[1]+1):
    for comb in combinations(data.columns, r):
        for RHS in comb:
            LHS=[col for col in comb if col!=RHS]
            cond_1=[r_t==RHS and len(set(LHS).intersection(set(l_t)))==len(l_t) for l_t,r_t in FD_list]
            cond_2=[set(l_t+r_t).intersection(set(LHS))==set(l_t+r_t) for l_t,r_t in FD_list]
            if sum(cond_1)==0 and sum(cond_2)==0:
                entropy=compute_entropy(LHS, RHS)
                if entropy==0:
                    FD_list.append([''.join(LHS),RHS])

参考文献

  1. TANE: An Efficient Algorithm for Discovering Functional and Approximate Dependencies
  2. https://blog.csdn.net/He_r_o/article/details/118419121
  3. https://blog.csdn.net/He_r_o/article/details/119359688

猜你喜欢

转载自blog.csdn.net/yeshang_lady/article/details/127282318