PHP实现Apriori算法——计算置信度

来源:互联网 发布:淘宝开个进口食品店 编辑:程序博客网 时间:2024/05/29 07:27

强规则定义
对于一个频繁集L,找到所有的L的非空子集非空子集f,如果f -> L - f,的概率满足最小置信度,则这是一个强规则。
如果{A,B,C,D}是一个频繁集,则它有如下候选规则
ABC -> D, ABD -> C, ACD -> B, BCD -> A, A -> BCD, B -> ACD, C -> ABD, D -> ABC,AB -> CD, AC -> BD, AD -> BC, BC -> AD, BD -> AC, CD -> AB
从中我们可以看出:
如果L的大小|L| = k, 则一共有(2的k次方减2) 个候选关联规则(除去 空集和全集)。
简化计算
根据公式我们可以推导出如下规则:
对于L = {A,B,C,D},它的子集的置信度有如下规则,
c(ABC -> D)>=c(AB -> CD) >= c(A -> BCD)
从而

图中被红圈标注的皆是不满足最小置信度的规则。
算法实现(只计算了满足的强规则,未对算法进行简化)

/**    * 计算一个项集产生的关联规则的所有置信度    * @param $itemset 要计算的某一项集    * @param $lItemset 所有满足支持度的集合    * @param $count 该项集的支持度    * @return $confidence 求出满足最小置信度的关联数组    */    public function confidence($itemset, $lItemset, $count){        $n = sizeof($itemset)-2;        $lkItemset = $lItemset[$n];        $confidence = array();        $this->subset = array();        $this->getAllSubSet(0, $itemset);//获得所有子集        for($i = 0; $i < sizeof($this->subset); $i++){            $n = sizeof($this->subset[$i])-1;            if($n >= 0 && $n < sizeof($itemset)-1){                $dkCountMap = self::$dCountMap[$n]; //根据大小,取出频繁集对应的支持度                //比较取出每个子集对应的支持度,并计算出置信度                for($j = 0; $j < sizeof($lItemset[$n]); $j++){                    if(!array_diff($this->subset[$i], $lItemset[$n][$j])){                        $conf = $count / $dkCountMap[$j] * 1.0;                        if($conf >= self::$MIN_CONF){                            $from = implode(",", $this->subset[$i]);                            $to = implode(",", array_diff($itemset, $this->subset[$i]));                            $confidence["$from ==> $to"] = $conf;                        }                    }                }            }        }        return $confidence;    }    /**    * 递归排列组合,获得一个项集所有子集,包括全集和空集    * @param $pos 记录将要放入子集的位置    * @param $itemset 要计算子集的项集    */    public $p = array(); //记录将要放入子集的位置,每一次递归就有0,1两种选择,最后即可获得所有选择    public $subset = array();    public $subsetCount = 0;    public function getAllSubSet($pos, $itemset){        if($pos == sizeof($itemset)){            $tmp = array();            for($i = 0; $i < sizeof($itemset); $i++){                if($this->p[$i] == 1){                    array_push($tmp, $itemset[$i]);                }            }            $count = $this->subsetCount;            $this->subset[] = $tmp;            $this->subsetCount++;            return;        }        $this->p[$pos] = 0;        $this->getAllSubSet($pos+1, $itemset);        $this->p[$pos] = 1;        $this->getAllSubSet($pos+1, $itemset);    }
0 0
原创粉丝点击