當前位置:首頁 » 操作系統 » apriori演算法c

apriori演算法c

發布時間: 2023-01-07 07:18:29

㈠ 設c是apriori演算法產生的ck中的一個候選項集.在剪枝步,需要檢查多少個長度為

2 FAA演算法思想
2.1 鏈表數組定義及生成演算法。鏈表數組定義:數組為n個指針的一維數組P[n],對應資料庫中的頻繁項I1,I2,…,In,對應數組長度n為資料庫中頻繁項的數量。結點為事務結點,分為事務域、計數域和指針域。事務域是以頻繁項為後綴的事務編碼。計數域是該事務編碼的數量,指針域是指向下一結點的指針。
編碼方法:設資料庫中有n個頻繁項I1,I2,…,In。事務t的編碼就是長度為n的0、1位串。在t中出現的項,其相應位置用1表示,否則填0。例如,有四個頻繁項a,b,c,d。那麼,一個包含a和c的事務就被映射為1010。
鏈表數組的構造過程如下:(1)掃描事務資料庫,產生所有頻繁1-項集及支持度計數,依據支持度計數降序排列,生成FI-List。(2)再次掃描資料庫,將每條記錄中不滿足最小支持度計數的項刪除,並將剩餘項按照FI-List重新排序。設形成的新序列為{m1,m2,…,mn},依次取出序列中的前k(1≤k≤n)項組成子序列{m1,m2,…,mk},對每個子序列進行編碼並建立一個與之對應的事務結點,並按照子序列中最後一項追加到P[n]中相應鏈上。

㈡ 怎麼用java實現apriori演算法

作者:何史提
鏈接:https://www.hu.com/question/22590018/answer/26646688
來源:知乎
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請註明出處。

Apriori演算法的理念其實很簡單,可是實現起上來卻復雜無比,因為當中無可避免用Set和Hash Table等高階的數據結構,而且有很多loop用以讀取數據。
我不建議用Java,應改用Python或Scala一類的語言。如果用Python,代碼大概50行左右,但可以想像用Java便看起來復雜得多。看如下:

from operator import and_
from itertools import combinations

class AprioriAssociationRule:
def __init__(self, inputfile):
self.transactions = []
self.itemSet = set([])
inf = open(inputfile, 'rb')
for line in inf.readlines():
elements = set(filter(lambda entry: len(entry)>0, line.strip().split(',')))
if len(elements)>0:
self.transactions.append(elements)
for element in elements:
self.itemSet.add(element)
inf.close()
self.toRetItems = {}
self.associationRules = []

def getSupport(self, itemcomb):
if type(itemcomb) != frozenset:
itemcomb = frozenset([itemcomb])
within_transaction = lambda transaction: rece(and_, [(item in transaction) for item in itemcomb])
count = len(filter(within_transaction, self.transactions))
return float(count)/float(len(self.transactions))

def runApriori(self, minSupport=0.15, minConfidence=0.6):
itemCombSupports = filter(lambda freqpair: freqpair[1]>=minSupport,
map(lambda item: (frozenset([item]), self.getSupport(item)), self.itemSet))
currentLset = set(map(lambda freqpair: freqpair[0], itemCombSupports))
k = 2
while len(currentLset)>0:
currentCset = set([i.union(j) for i in currentLset for j in currentLset if len(i.union(j))==k])
currentItemCombSupports = filter(lambda freqpair: freqpair[1]>=minSupport,
map(lambda item: (item, self.getSupport(item)), currentCset))
currentLset = set(map(lambda freqpair: freqpair[0], currentItemCombSupports))
itemCombSupports.extend(currentItemCombSupports)
k += 1
for key, supportVal in itemCombSupports:
self.toRetItems[key] = supportVal
self.calculateAssociationRules(minConfidence=minConfidence)

def calculateAssociationRules(self, minConfidence=0.6):
for key in self.toRetItems:
subsets = [frozenset(item) for k in range(1, len(key)) for item in combinations(key, k)]
for subset in subsets:
confidence = self.toRetItems[key] / self.toRetItems[subset]
if confidence > minConfidence:
self.associationRules.append([subset, key-subset, confidence])

㈢ 計算機大神請進啊!這個Apriori演算法這個題,由L2到底怎麼產生候選C3的怎麼連接啊,完

自連接不是與自身連接
你說的只有頻繁2項集{A,B}{C,D},那{A,C},{A,D}呢?找到前幾項相同的,最後一項不同的連接,那麼必然產生K+1項集

㈣ 急需C++實現的Apriori演算法代碼

用C++ 實現的 可以 到http://download.csdn.net/down/188143/chanjuanzz下載 不過要注冊扣積分的

演算法實現

(一)核心類

Apriori演算法的核心實現類為AprioriAlgorithm,實現的Java代碼如下所示:

package org.shirdrn.datamining.association;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
* <B>關聯規則挖掘:Apriori演算法</B>
*
* <P>該演算法基本上按照Apriori演算法的基本思想來實現的。
*
* @author shirdrn
* @date 2009/07/22 22:56:23
* @msn shirdrn#hotmail.com(#→@)
* @qq 187071722
*/
public class AprioriAlgorithm {

private Map<Integer, Set<String>> txDatabase; // 事務資料庫
private Float minSup; // 最小支持度
private Float minConf; // 最小置信度
private Integer txDatabaseCount; // 事務資料庫中的事務數

private Map<Integer, Set<Set<String>>> freqItemSet; // 頻繁項集集合
private Map<Set<String>, Set<Set<String>>> assiciationRules; // 頻繁關聯規則集合

public AprioriAlgorithm(
Map<Integer, Set<String>> txDatabase,
Float minSup,
Float minConf) {
this.txDatabase = txDatabase;
this.minSup = minSup;
this.minConf = minConf;
this.txDatabaseCount = this.txDatabase.size();
freqItemSet = new TreeMap<Integer, Set<Set<String>>>();
assiciationRules = new HashMap<Set<String>, Set<Set<String>>>();
}

/**
* 掃描事務資料庫,計算頻繁1-項集
* @return
*/
public Map<Set<String>, Float> getFreq1ItemSet() {
Map<Set<String>, Float> freq1ItemSetMap = new HashMap<Set<String>, Float>();
Map<Set<String>, Integer> candFreq1ItemSet = this.getCandFreq1ItemSet();
Iterator<Map.Entry<Set<String>, Integer>> it = candFreq1ItemSet.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Set<String>, Integer> entry = it.next();
// 計算支持度
Float supported = new Float(entry.getValue().toString())/new Float(txDatabaseCount);
if(supported>=minSup) {
freq1ItemSetMap.put(entry.getKey(), supported);
}
}
return freq1ItemSetMap;
}

/**
* 計算候選頻繁1-項集
* @return
*/
public Map<Set<String>, Integer> getCandFreq1ItemSet() {
Map<Set<String>, Integer> candFreq1ItemSetMap = new HashMap<Set<String>, Integer>();
Iterator<Map.Entry<Integer, Set<String>>> it = txDatabase.entrySet().iterator();
// 統計支持數,生成候選頻繁1-項集
while(it.hasNext()) {
Map.Entry<Integer, Set<String>> entry = it.next();
Set<String> itemSet = entry.getValue();
for(String item : itemSet) {
Set<String> key = new HashSet<String>();
key.add(item.trim());
if(!candFreq1ItemSetMap.containsKey(key)) {
Integer value = 1;
candFreq1ItemSetMap.put(key, value);
}
else {
Integer value = 1+candFreq1ItemSetMap.get(key);
candFreq1ItemSetMap.put(key, value);
}
}
}
return candFreq1ItemSetMap;
}

/**
* 根據頻繁(k-1)-項集計算候選頻繁k-項集
*
* @param m 其中m=k-1
* @param freqMItemSet 頻繁(k-1)-項集
* @return
*/
public Set<Set<String>> aprioriGen(int m, Set<Set<String>> freqMItemSet) {
Set<Set<String>> candFreqKItemSet = new HashSet<Set<String>>();
Iterator<Set<String>> it = freqMItemSet.iterator();
Set<String> originalItemSet = null;
while(it.hasNext()) {
originalItemSet = it.next();
Iterator<Set<String>> itr = this.getIterator(originalItemSet, freqMItemSet);
while(itr.hasNext()) {
Set<String> identicalSet = new HashSet<String>(); // 兩個項集相同元素的集合(集合的交運算)
identicalSet.addAll(originalItemSet);
Set<String> set = itr.next();
identicalSet.retainAll(set); // identicalSet中剩下的元素是identicalSet與set集合中公有的元素
if(identicalSet.size() == m-1) { // (k-1)-項集中k-2個相同
Set<String> differentSet = new HashSet<String>(); // 兩個項集不同元素的集合(集合的差運算)
differentSet.addAll(originalItemSet);
differentSet.removeAll(set); // 因為有k-2個相同,則differentSet中一定剩下一個元素,即differentSet大小為1
differentSet.addAll(set); // 構造候選k-項集的一個元素(set大小為k-1,differentSet大小為k)
candFreqKItemSet.add(differentSet); // 加入候選k-項集集合
}
}
}
return candFreqKItemSet;
}

/**
* 根據一個頻繁k-項集的元素(集合),獲取到頻繁k-項集的從該元素開始的迭代器實例
* @param itemSet
* @param freqKItemSet 頻繁k-項集
* @return
*/
private Iterator<Set<String>> getIterator(Set<String> itemSet, Set<Set<String>> freqKItemSet) {
Iterator<Set<String>> it = freqKItemSet.iterator();
while(it.hasNext()) {
if(itemSet.equals(it.next())) {
break;
}
}
return it;
}

/**
* 根據頻繁(k-1)-項集,調用aprioriGen方法,計算頻繁k-項集
*
* @param k
* @param freqMItemSet 頻繁(k-1)-項集
* @return
*/
public Map<Set<String>, Float> getFreqKItemSet(int k, Set<Set<String>> freqMItemSet) {
Map<Set<String>, Integer> candFreqKItemSetMap = new HashMap<Set<String>, Integer>();
// 調用aprioriGen方法,得到候選頻繁k-項集
Set<Set<String>> candFreqKItemSet = this.aprioriGen(k-1, freqMItemSet);

// 掃描事務資料庫
Iterator<Map.Entry<Integer, Set<String>>> it = txDatabase.entrySet().iterator();
// 統計支持數
while(it.hasNext()) {
Map.Entry<Integer, Set<String>> entry = it.next();
Iterator<Set<String>> kit = candFreqKItemSet.iterator();
while(kit.hasNext()) {
Set<String> kSet = kit.next();
Set<String> set = new HashSet<String>();
set.addAll(kSet);
set.removeAll(entry.getValue()); // 候選頻繁k-項集與事務資料庫中元素做差元算
if(set.isEmpty()) { // 如果拷貝set為空,支持數加1
if(candFreqKItemSetMap.get(kSet) == null) {
Integer value = 1;
candFreqKItemSetMap.put(kSet, value);
}
else {
Integer value = 1+candFreqKItemSetMap.get(kSet);
candFreqKItemSetMap.put(kSet, value);
}
}
}
}
// 計算支持度,生成頻繁k-項集,並返回
return support(candFreqKItemSetMap);
}

/**
* 根據候選頻繁k-項集,得到頻繁k-項集
*
* @param candFreqKItemSetMap 候選k項集(包含支持計數)
*/
public Map<Set<String>, Float> support(Map<Set<String>, Integer> candFreqKItemSetMap) {
Map<Set<String>, Float> freqKItemSetMap = new HashMap<Set<String>, Float>();
Iterator<Map.Entry<Set<String>, Integer>> it = candFreqKItemSetMap.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Set<String>, Integer> entry = it.next();
// 計算支持度
Float supportRate = new Float(entry.getValue().toString())/new Float(txDatabaseCount);
if(supportRate<minSup) { // 如果不滿足最小支持度,刪除
it.remove();
}
else {
freqKItemSetMap.put(entry.getKey(), supportRate);
}
}
return freqKItemSetMap;
}

/**
* 挖掘全部頻繁項集
*/
public void mineFreqItemSet() {
// 計算頻繁1-項集
Set<Set<String>> freqKItemSet = this.getFreq1ItemSet().keySet();
freqItemSet.put(1, freqKItemSet);
// 計算頻繁k-項集(k>1)
int k = 2;
while(true) {
Map<Set<String>, Float> freqKItemSetMap = this.getFreqKItemSet(k, freqKItemSet);
if(!freqKItemSetMap.isEmpty()) {
this.freqItemSet.put(k, freqKItemSetMap.keySet());
freqKItemSet = freqKItemSetMap.keySet();
}
else {
break;
}
k++;
}
}

/**
* <P>挖掘頻繁關聯規則
* <P>首先挖掘出全部的頻繁項集,在此基礎上挖掘頻繁關聯規則
*/
public void mineAssociationRules() {
freqItemSet.remove(1); // 刪除頻繁1-項集
Iterator<Map.Entry<Integer, Set<Set<String>>>> it = freqItemSet.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Integer, Set<Set<String>>> entry = it.next();
for(Set<String> itemSet : entry.getValue()) {
// 對每個頻繁項集進行關聯規則的挖掘
mine(itemSet);
}
}
}

/**
* 對從頻繁項集集合freqItemSet中每迭代出一個頻繁項集元素,執行一次關聯規則的挖掘
* @param itemSet 頻繁項集集合freqItemSet中的一個頻繁項集元素
*/
public void mine(Set<String> itemSet) {
int n = itemSet.size()/2; // 根據集合的對稱性,只需要得到一半的真子集
for(int i=1; i<=n; i++) {
// 得到頻繁項集元素itemSet的作為條件的真子集集合
Set<Set<String>> properSubset = ProperSubsetCombination.getProperSubset(i, itemSet);
// 對條件的真子集集合中的每個條件項集,獲取到對應的結論項集,從而進一步挖掘頻繁關聯規則
for(Set<String> conditionSet : properSubset) {
Set<String> conclusionSet = new HashSet<String>();
conclusionSet.addAll(itemSet);
conclusionSet.removeAll(conditionSet); // 刪除條件中存在的頻繁項
confide(conditionSet, conclusionSet); // 調用計算置信度的方法,並且挖掘出頻繁關聯規則
}
}
}

/**
* 對得到的一個條件項集和對應的結論項集,計算該關聯規則的支持計數,從而根據置信度判斷是否是頻繁關聯規則
* @param conditionSet 條件頻繁項集
* @param conclusionSet 結論頻繁項集
*/
public void confide(Set<String> conditionSet, Set<String> conclusionSet) {
// 掃描事務資料庫
Iterator<Map.Entry<Integer, Set<String>>> it = txDatabase.entrySet().iterator();
// 統計關聯規則支持計數
int conditionToConclusionCnt = 0; // 關聯規則(條件項集推出結論項集)計數
int conclusionToConditionCnt = 0; // 關聯規則(結論項集推出條件項集)計數
int supCnt = 0; // 關聯規則支持計數
while(it.hasNext()) {
Map.Entry<Integer, Set<String>> entry = it.next();
Set<String> txSet = entry.getValue();
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
set1.addAll(conditionSet);

set1.removeAll(txSet); // 集合差運算:set-txSet
if(set1.isEmpty()) { // 如果set為空,說明事務資料庫中包含條件頻繁項conditionSet
// 計數
conditionToConclusionCnt++;
}
set2.addAll(conclusionSet);
set2.removeAll(txSet); // 集合差運算:set-txSet
if(set2.isEmpty()) { // 如果set為空,說明事務資料庫中包含結論頻繁項conclusionSet
// 計數
conclusionToConditionCnt++;

}
if(set1.isEmpty() && set2.isEmpty()) {
supCnt++;
}
}
// 計算置信度
Float conditionToConclusionConf = new Float(supCnt)/new Float(conditionToConclusionCnt);
if(conditionToConclusionConf>=minConf) {
if(assiciationRules.get(conditionSet) == null) { // 如果不存在以該條件頻繁項集為條件的關聯規則
Set<Set<String>> conclusionSetSet = new HashSet<Set<String>>();
conclusionSetSet.add(conclusionSet);
assiciationRules.put(conditionSet, conclusionSetSet);
}
else {
assiciationRules.get(conditionSet).add(conclusionSet);
}
}
Float conclusionToConditionConf = new Float(supCnt)/new Float(conclusionToConditionCnt);
if(conclusionToConditionConf>=minConf) {
if(assiciationRules.get(conclusionSet) == null) { // 如果不存在以該結論頻繁項集為條件的關聯規則
Set<Set<String>> conclusionSetSet = new HashSet<Set<String>>();
conclusionSetSet.add(conditionSet);
assiciationRules.put(conclusionSet, conclusionSetSet);
}
else {
assiciationRules.get(conclusionSet).add(conditionSet);
}
}
}

/**
* 經過挖掘得到的頻繁項集Map
*
* @return 挖掘得到的頻繁項集集合
*/
public Map<Integer, Set<Set<String>>> getFreqItemSet() {
return freqItemSet;
}

/**
* 獲取挖掘到的全部的頻繁關聯規則的集合
* @return 頻繁關聯規則集合
*/
public Map<Set<String>, Set<Set<String>>> getAssiciationRules() {
return assiciationRules;
}
}

(二)輔助類

ProperSubsetCombination類是一個輔助類,在挖掘頻繁關聯規則的過程中,用於生成一個頻繁項集元素的非空真子集,實現代碼如下:

package org.shirdrn.datamining.association;
import java.util.BitSet;
import java.util.HashSet;
import java.util.Set;

/**
* <B>求頻繁項集元素(集合)的非空真子集集合</B>
* <P>從一個集合(大小為n)中取出m(m屬於2~n/2的閉區間)個元素的組合實現類,獲取非空真子集的集合
*
* @author shirdrn
* @date 2009/07/22 22:56:23
* @msn shirdrn#hotmail.com(#→@)
* @qq 187071722
*/
public class ProperSubsetCombination {

private static String[] array;
private static BitSet startBitSet; // 比特集合起始狀態
private static BitSet endBitSet; // 比特集合終止狀態,用來控制循環
private static Set<Set<String>> properSubset; // 真子集集合

/**
* 計算得到一個集合的非空真子集集合
*
* @param n 真子集的大小
* @param itemSet 一個頻繁項集元素
* @return 非空真子集集合
*/
public static Set<Set<String>> getProperSubset(int n, Set<String> itemSet) {
String[] array = new String[itemSet.size()];
ProperSubsetCombination.array = itemSet.toArray(array);
properSubset = new HashSet<Set<String>>();
startBitSet = new BitSet();
endBitSet = new BitSet();

// 初始化startBitSet,左側占滿1
for (int i=0; i<n; i++) {
startBitSet.set(i, true);
}

// 初始化endBit,右側占滿1
for (int i=array.length-1; i>=array.length-n; i--) {
endBitSet.set(i, true);
}

// 根據起始startBitSet,將一個組合加入到真子集集合中
get(startBitSet);

while(!startBitSet.equals(endBitSet)) {
int zeroCount = 0; // 統計遇到10後,左邊0的個數
int oneCount = 0; // 統計遇到10後,左邊1的個數
int pos = 0; // 記錄當前遇到10的索引位置

// 遍歷startBitSet來確定10出現的位置
for (int i=0; i<array.length; i++) {
if (!startBitSet.get(i)) {
zeroCount++;
}
if (startBitSet.get(i) && !startBitSet.get(i+1)) {
pos = i;
oneCount = i - zeroCount;
// 將10變為01
startBitSet.set(i, false);
startBitSet.set(i+1, true);
break;
}
}
// 將遇到10後,左側的1全部移動到最左側
int counter = Math.min(zeroCount, oneCount);
int startIndex = 0;
int endIndex = 0;
if(pos>1 && counter>0) {
pos--;
endIndex = pos;
for (int i=0; i<counter; i++) {
startBitSet.set(startIndex, true);
startBitSet.set(endIndex, false);
startIndex = i+1;
pos--;
if(pos>0) {
endIndex = pos;
}
}
}
get(startBitSet);
}
return properSubset;
}

/**
* 根據一次移位操作得到的startBitSet,得到一個真子集
* @param bitSet
*/
private static void get(BitSet bitSet) {
Set<String> set = new HashSet<String>();
for(int i=0; i<array.length; i++) {
if(bitSet.get(i)) {
set.add(array[i]);
}
}
properSubset.add(set);
}
}

測試用例

對上述Apriori演算法的實現進行了簡單的測試,測試用例如下所示:

package org.shirdrn.datamining.association;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.shirdrn.datamining.association.AprioriAlgorithm;

import junit.framework.TestCase;

/**
* <B>Apriori演算法測試類</B>
*
* @author shirdrn
* @date 2009/07/22 22:56:23
* @msn shirdrn#hotmail.com(#→@)
* @qq 187071722
*/
public class TestAprioriAlgorithm extends TestCase {

private AprioriAlgorithm apriori;
private Map<Integer, Set<String>> txDatabase;
private Float minSup = new Float("0.50");
private Float minConf = new Float("0.70");

@Override
protected void setUp() throws Exception {
create(); // 構造事務資料庫
apriori = new AprioriAlgorithm(txDatabase, minSup, minConf);
}

/**
* 構造模擬事務資料庫txDatabase
*/
public void create() {
txDatabase = new HashMap<Integer, Set<String>>();
Set<String> set1 = new TreeSet<String>();
set1.add("A");
set1.add("B");
set1.add("C");
set1.add("E");
txDatabase.put(1, set1);
Set<String> set2 = new TreeSet<String>();
set2.add("A");
set2.add("B");
set2.add("C");
txDatabase.put(2, set2);
Set<String> set3 = new TreeSet<String>();
set3.add("C");
set3.add("D");
txDatabase.put(3, set3);
Set<String> set4 = new TreeSet<String>();
set4.add("A");
set4.add("B");
set4.add("E");
txDatabase.put(4, set4);
}

/**
* 測試挖掘頻繁1-項集
*/
public void testFreq1ItemSet() {
System.out.println("挖掘頻繁1-項集 : " + apriori.getFreq1ItemSet());
}

/**
* 測試aprioriGen方法,生成候選頻繁項集
*/
public void testAprioriGen() {
System.out.println(
"候選頻繁2-項集 : " +
this.apriori.aprioriGen(1, this.apriori.getFreq1ItemSet().keySet())
);
}

/**
* 測試挖掘頻繁2-項集
*/
public void testGetFreq2ItemSet() {
System.out.println(
"挖掘頻繁2-項集 :" +
this.apriori.getFreqKItemSet(2, this.apriori.getFreq1ItemSet().keySet())
);
}

/**
* 測試挖掘頻繁3-項集
*/
public void testGetFreq3ItemSet() {
System.out.println(
"挖掘頻繁3-項集 :" +
this.apriori.getFreqKItemSet(
3,
this.apriori.getFreqKItemSet(2, this.apriori.getFreq1ItemSet().keySet()).keySet()
)
);
}

/**
* 測試挖掘全部頻繁項集
*/
public void testGetFreqItemSet() {
this.apriori.mineFreqItemSet(); // 挖掘頻繁項集
System.out.println("挖掘頻繁項集 :" + this.apriori.getFreqItemSet());
}

/**
* 測試挖掘全部頻繁關聯規則
*/
public void testMineAssociationRules() {
this.apriori.mineFreqItemSet(); // 挖掘頻繁項集
this.apriori.mineAssociationRules();
System.out.println("挖掘頻繁關聯規則 :" + this.apriori.getAssiciationRules());
}
}

測試結果:

挖掘頻繁1-項集 : {[E]=0.5, [A]=0.75, [B]=0.75, [C]=0.75}
候選頻繁2-項集 : [[E, C], [A, B], [B, C], [A, C], [E, B], [E, A]]
挖掘頻繁2-項集 :{[A, B]=0.75, [B, C]=0.5, [A, C]=0.5, [E, B]=0.5, [E, A]=0.5}
挖掘頻繁3-項集 :{[E, A, B]=0.5, [A, B, C]=0.5}
挖掘頻繁項集 :{1=[[E], [A], [B], [C]], 2=[[A, B], [B, C], [A, C], [E, B], [E, A]], 3=[[E, A, B], [A, B, C]]}
挖掘頻繁關聯規則 :{[E]=[[A], [B], [A, B]], [A]=[[B]], [B]=[[A]], [B, C]=[[A]], [A, C]=[[B]], [E, B]=[[A]], [E, A]=[[B]]}

從測試結果看到,使用Apriori演算法挖掘得到的全部頻繁項集為:

{1=[[E], [A], [B], [C]], 2=[[A, B], [B, C], [A, C], [E, B], [E, A]], 3=[[E, A, B], [A, B, C]]}

使用Apriori演算法挖掘得到的全部頻繁關聯規則為:

{E}→{A}、{E}→{B}、{E}→{A,B}、{A}→{B}、{B}→{A}、{B,C}→{A}、{A,C}→{B}、{B,E}→{A}、{A,E}→{B}。

㈤ 解釋一段Apriori演算法的意思,越詳細越好偶電腦白痴

這段是經典Ariori演算法產生頻繁項集的偽代碼

㈥ 急求用C實現的Apriori演算法的 代碼

http://www.csc.liv.ac.uk/~frans/Notes/KDD/AssocRuleMine/apriori.html

.h
====================================
/*----------------------------------------------------------------------
File : apriori.h
Contents: apriori algorithm for finding frequent item sets
(specialized version for FIMI 2003 workshop)
Author : Christian Borgelt
History : 15.08.2003 file created from normal apriori.c
16.08.2003 parameter for transaction filtering added
18.08.2003 dynamic filtering decision based on times added
21.08.2003 transaction sort changed to heapsort
20.09.2003 output file made optional
----------------------------------------------------------------------*/
/*
Modified by : Frédéric Flouvat
Modifications : store the positive and negative border into an
an input trie for ABS
process stastical informations on dataset to stop
the apriori classical iterations
Author : Frédéric Flouvat
----------------------------------------------------------------------*/
#ifndef APRIRORI_H
#define APRIRORI_H

#include <iostream>
using namespace std;
#define MAXIMAL

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <assert.h>

#include "tract.h"
#include "istree.h"
#include "Application.h"

/*----------------------------------------------------------------------
Preprocessor Definitions
----------------------------------------------------------------------*/
#define PRGNAME "fim/apriori"
#define DESCRIPTION "frequent item sets miner for FIMI 2003"
#define VERSION "version 1.7 (2003.12.02) " \
"(c) 2003 Christian Borgelt"

/* --- error codes --- */
#define E_OPTION (-5) /* unknown option */
#define E_OPTARG (-6) /* missing option argument */
#define E_ARGCNT (-7) /* too few/many arguments */
#define E_SUPP (-8) /* invalid minimum support */
#define E_NOTAS (-9) /* no items or transactions */
#define E_UNKNOWN (-18) /* unknown error */

#ifndef QUIET /* if not quiet version */
#define MSG(x) x /* print messages */
#else /* if quiet version */
#define MSG(x) /* suppress messages */
#endif

#define SEC_SINCE(t) ((clock()-(t)) /(double)CLOCKS_PER_SEC)
#define RECCNT(s) (tfs_reccnt(is_tfscan(s)) \
+ ((tfs_delim(is_tfscan(s)) == TFS_REC) ? 0 : 1))
#define BUFFER(s) tfs_buf(is_tfscan(s))

/*----------------------------------------------------------------------
Constants
----------------------------------------------------------------------*/
#ifndef QUIET /* if not quiet version */

/* --- error messages --- */
static const char *errmsgs[] = {
/* E_NONE 0 */ "no error\n",
/* E_NOMEM -1 */ "not enough memory\n",
/* E_FOPEN -2 */ "cannot open file %s\n",
/* E_FREAD -3 */ "read error on file %s\n",
/* E_FWRITE -4 */ "write error on file %s\n",
/* E_OPTION -5 */ "unknown option -%c\n",
/* E_OPTARG -6 */ "missing option argument\n",
/* E_ARGCNT -7 */ "wrong number of arguments\n",
/* E_SUPP -8 */ "invalid minimal support %d\n",
/* E_NOTAS -9 */ "no items or transactions to work on\n",
/* -10 to -15 */ NULL, NULL, NULL, NULL, NULL, NULL,
/* E_ITEMEXP -16 */ "file %s, record %d: item expected\n",
/* E_DUPITEM -17 */ "file %s, record %d: plicate item %s\n",
/* E_UNKNOWN -18 */ "unknown error\n"
};
#endif

/*----------------------------------------------------------------------
Global Variables
----------------------------------------------------------------------*/
#ifndef QUIET
static char *prgname; /* program name for error messages */
#endif
static ITEMSET *itemset = NULL; /* item set */
static TASET *taset = NULL; /* transaction set */
static TATREE *tatree = NULL; /* transaction tree */
static ISTREE *istree = NULL; /* item set tree */
static FILE *in = NULL; /* input file */
static FILE *out = NULL; /* output file */

extern "C" TATREE * apriori( char*fn_in, char*fn_out, int supp, int & level,
Trie * bdPapriori, Trie * bdn, set<Element> * relist, double ratioNfC, double & eps, int ismax,
vector< unsigned int > * stat, int & maxBdP, bool & generatedFk, bool verbose ) ;

#endif

.c
============================================
/*----------------------------------------------------------------------
File : apriori.c
Contents: apriori algorithm for finding frequent item sets
(specialized version for FIMI 2003 workshop)
Author : Christian Borgelt
History : 15.08.2003 file created from normal apriori.c
16.08.2003 parameter for transaction filtering added
18.08.2003 dynamic filtering decision based on times added
21.08.2003 transaction sort changed to heapsort
20.09.2003 output file made optional
----------------------------------------------------------------------*/
/*
Modified by : Frédéric Flouvat
Modifications : store the positive and negative border into an
an input trie for ABS
process stastical informations on dataset to stop
the apriori classical iterations
Author : Frédéric Flouvat
----------------------------------------------------------------------*/

#include "apriori.h"

/*----------------------------------------------------------------------
Main Functions
----------------------------------------------------------------------*/

static void error (int code, ...)
{ /* --- print an error message */
#ifndef QUIET /* if not quiet version */
va_list args; /* list of variable arguments */
const char *msg; /* error message */

assert(prgname); /* check the program name */
if (code < E_UNKNOWN) code = E_UNKNOWN;
if (code < 0) { /* if to report an error, */
msg = errmsgs[-code]; /* get the error message */
if (!msg) msg = errmsgs[-E_UNKNOWN];
fprintf(stderr, "\n%s: ", prgname);
va_start(args, code); /* get variable arguments */
vfprintf(stderr, msg, args);/* print error message */
va_end(args); /* end argument evaluation */
}
#endif
#ifndef NDEBUG /* if debug version */
if (istree) ist_delete(istree);
if (tatree) tat_delete(tatree);
if (taset) tas_delete(taset, 0);
if (itemset) is_delete(itemset);
if (in) fclose(in); /* clean up memory */
if (out) fclose(out); /* and close files */
#endif
exit(code); /* abort the program */
} /* error() */

/*--------------------------------------------------------------------*/

TATREE * apriori( char*fn_in, char*fn_out, int supp, int & level, Trie * bdPapriori,
Trie * bdn , set<Element> * relist , double ratioNfC, double & eps,int ismax,
vector< unsigned int > * stat, int & maxBdP, bool & generatedFk, bool verbose )
{
int i, k, n; /* loop variables, counters */
int tacnt = 0; /* number of transactions */
int max = 0; /* maximum transaction size */
int empty = 1; /* number of empty item sets */
int *map, *set; /* identifier map, item set */
char *usage; /* flag vector for item usage */
clock_t t, tt, tc, x; /* timer for measurements */

double actNfC = 1 ;
double avgNfC = 0 ;
int nbgen = 0 ;
int nbfreq = 0 ;
level = 1 ;
bool endApriori = false ; // boolean to stop the initial classial apriori approach
int bdnsize = 0 ; // number of itemsets found infrequent

/* --- create item set and transaction set --- */
itemset = is_create(); /* create an item set and */
if (!itemset) error(E_NOMEM); /* set the special characters */
taset = tas_create(itemset); /* create a transaction set */
if (!taset) error(E_NOMEM); /* to store the transactions */
if( verbose ) MSG(fprintf(stderr, "\n")); /* terminate the startup message */

/* --- read transactions --- */
if( verbose )MSG(fprintf(stderr, "reading %s ... ", fn_in));
t = clock(); /* start the timer and */
in = fopen(fn_in, "r"); /* open the input file */
if (!in) error(E_FOPEN, fn_in);
for (tacnt = 0; 1; tacnt++) { /* transaction read loop */
k = is_read(itemset, in); /* read the next transaction */
if (k < 0) error(k, fn_in, RECCNT(itemset), BUFFER(itemset));
if (k > 0) break; /* check for error and end of file */
k = is_tsize(itemset); /* update the maximal */
if (k > max) max = k; /* transaction size */
if (taset && (tas_add(taset, NULL, 0) != 0))
error(E_NOMEM); /* add the loaded transaction */
} /* to the transaction set */
fclose(in); in = NULL; /* close the input file */
n = is_cnt(itemset); /* get the number of items */
if( verbose ) MSG(fprintf(stderr, "[%d item(s),", n));
if( verbose ) MSG(fprintf(stderr, " %d transaction(s)] done ", tacnt));
if( verbose ) MSG(fprintf(stderr, "[%.2fs].\n", SEC_SINCE(t)));

/* --- sort and recode items --- */
if( verbose ) MSG(fprintf(stderr, "sorting and recoding items ... "));
t = clock(); /* start the timer */
map = (int*)malloc(is_cnt(itemset) *sizeof(int));
if (!map) error(E_NOMEM); /* create an item identifier map */
n = is_recode(itemset, supp, 2, map); /* 2: sorting mode */
tas_recode(taset, map, n); /* recode the loaded transactions */
max = tas_max(taset); /* get the new maximal t.a. size */

// use in the other part of the implementation to have the corresponding
// identifiant to an internal id
stat->reserve( n+2 ) ;
stat->push_back( 0 ) ;
for(int j= 0; j< n ; j++ )
{
stat->push_back( 0 ) ;
relist->insert( Element( atoi( is_name( itemset, j ) ) ,j) );
}

if( verbose ) MSG(fprintf(stderr, "[%d item(s)] ", n));
if( verbose ) MSG(fprintf(stderr, "done [%.2fs].\n", SEC_SINCE(t)));

/* --- create a transaction tree --- */
if( verbose ) MSG(fprintf(stderr, "creating transaction tree ... "));
t = clock(); /* start the timer */
tatree = tat_create(taset,1); /* create a transaction tree */
if (!tatree) error(E_NOMEM); /* (compactify transactions) */
tt = clock() -t; /* note the construction time */
if( verbose ) MSG(fprintf(stderr, "done [%.2fs].\n", SEC_SINCE(t)));

/* --- create an item set tree --- */
if( verbose ) MSG(fprintf(stderr, "checking subsets of size 1"));
t = clock(); tc = 0; /* start the timer and */
istree = ist_create(n, supp); /* create an item set tree */
if (!istree) error(E_NOMEM);
for (k = n; --k >= 0; ) /* set single item frequencies */
ist_setcnt(istree, k, is_getfrq(itemset, k));
ist_settac(istree, tacnt); /* set the number of transactions */
usage = (char*)malloc(n *sizeof(char));
if (!usage) error(E_NOMEM); /* create a item usage vector */

/* --- check item subsets --- */
while (ist_height(istree) < max && ( ( ismax == -1 && endApriori == false )
|| ist_height(istree) < ismax )
)
{
nbgen = 0 ;
nbfreq = 0 ;

level ++ ;

i = ist_check(istree,usage);/* check current item usage */

if (i < max) max = i; /* update the maximum set size */
if (ist_height(istree) >= i) break;

k = ist_addlvl(istree, nbgen); /* while max. height is not reached, */

if (k < 0) error(E_NOMEM); /* add a level to the item set tree */
if (k != 0) break; /* if no level was added, abort */
if( verbose ) MSG(fprintf(stderr, " %d", ist_height(istree)));
if ((i < n) /* check item usage on current level */
&& (i *(double)tt < 0.1 *n *tc)) {
n = i; x = clock(); /* if items were removed and */
tas_filter(taset, usage); /* the counting time is long enough, */
tat_delete(tatree); /* remove unnecessary items */
tatree = tat_create(taset, 1);
if (!tatree) error(E_NOMEM);
tt = clock() -x; /* rebuild the transaction tree and */
} /* note the new construction time */
x = clock(); /* start the timer */

ist_countx(istree, tatree, nbfreq, istree->supp ); /* count the transaction tree */

tc = clock() -x; /* in the item set tree */

actNfC = 1-double(nbfreq)/double(nbgen) ;
avgNfC = avgNfC + actNfC ;

if( verbose )
{
cout<<" \t Fk : "<<nbfreq<<" Ck : "<<nbgen<<" NFk/Ck "<<actNfC<<" avg NFk/Ck "<<avgNfC/(level-1)<<endl;
}

bdnsize += nbgen - nbfreq ;

if( level >=4 && ( bdnsize / nbgen < 1.5 ) && ( bdnsize > 100 ) )
{
if( actNfC < ratioNfC )
{
eps = 0 ;
endApriori = true ;
}
else if( actNfC > 0.25 )
endApriori = true ;

}

} /* and note the new counting time */
if( verbose ) MSG(fprintf(stderr, " done [%.2fs].\n", SEC_SINCE(t)));

/* --- filter item sets --- */
t = clock(); /* start the timer */
#ifdef MAXIMAL /* filter maximal item sets */
if( verbose ) MSG(fprintf(stderr, "filtering maximal item sets ... "));

if( ratioNfC == 0 || nbgen < k+1 || ist_height(istree)>= max )
ist_filter2(istree, IST_MAXFRQ, 0);
else
ist_filter2(istree, IST_MAXFRQ, bdn);

if( verbose ) MSG(fprintf(stderr, " done [%.2fs].\n", SEC_SINCE(t)));
empty = (n <= 0) ? 1 : 0; /* check whether the empty item set */
#endif /* is maximal */
#ifdef CLOSED /* filter closed item sets */
if( verbose ) MSG(fprintf(stderr, "filtering closed item sets ... "));
ist_filter(istree, IST_CLOSED);
if( verbose ) MSG(fprintf(stderr, " done [%.2fs].\n", SEC_SINCE(t)));
for (k = n; --k >= 0; ) /* check for an item in all t.a. */
if (is_getfrq(itemset, k) == tacnt) break;
empty = (k <= 0) ? 1 : 0; /* check whether the empty item set */
#endif /* is closed */

/* --- print item sets --- */
for (i = ist_height(istree); --i >= 0; )
map[i] = 0; /* clear the item set counters */
if( verbose ) MSG(fprintf(stderr, "writing %s ... ", (fn_out) ? fn_out : "<none>"));
t = clock(); /* start the timer and */
if (fn_out) { /* if an output file is given, */
out = fopen(fn_out, "w"); /* open the output file */
if (!out) error(E_FOPEN, fn_out);
if (empty) fprintf(out, " (%d)\n", tacnt);
} /* report empty item set */
ist_init(istree); /* init. the item set extraction */
set = is_tract(itemset); /* get the transaction buffer */
for (n = empty; 1; n++) { /* extract item sets from the tree */

k = ist_set(istree, set, &supp);

if (k <= 0) break; /* get the next frequent item set */
map[k-1]++; /* count the item set */
if (fn_out) { /* if an output file is given */
for (i = 0; i < k; i++) { /* traverse the items */
fputs(is_name(itemset, set[i]), out);
fputc(' ', out); /* print the name of the next item */
} /* followed by a separator */
fprintf(out, "(%d)\n", supp);
} /* print the item set's support */
else
{
short unsigned * is = new short unsigned[k] ;

for (i = 0; i < k; i++) /* traverse the items */
{
is[i] = set[i] ;
}
if( k < level || nbgen < k+1 || ist_height(istree)>= max )
{
bdPapriori->insert(is, k ,supp ) ;

(*stat)[ 0 ] ++;
(*stat)[ k+1 ]++;

if( maxBdP < k )
maxBdP = k ;

}
else
{
generatedFk = true ;

}

delete[] is;

}
}
if (fn_out) { /* if an output file is given */
if (fflush(out) != 0) error(E_FWRITE, fn_out);
if (out != stdout) fclose(out);
out = NULL; /* close the output file */
}
if( verbose ) MSG(fprintf(stderr, "[%d set(s)] done ", n));
if( verbose ) MSG(fprintf(stderr, "[%.2fs].\n", SEC_SINCE(t)));

/* --- print item set statistics --- */
k = ist_height(istree); /* find last nonzero counter */
if ((k > 0) && (map[k-1] <= 0)) k--;
if( verbose ){
printf("%d\n", empty); /* print the numbers of item sets */
for (i = 0; i < k; i++) printf("%d\n", map[i]);
}

/* --- clean up --- */
#ifndef NDEBUG /* if this is a debug version */
free(usage); /* delete the item usage vector */
free(map); /* and the identifier map */
ist_delete(istree); /* delete the item set tree, */

if (taset) tas_delete(taset, 0); /* the transaction set, */
is_delete(itemset); /* and the item set */
#endif

return tatree ;

}

㈦ 數據挖掘中的apriori演算法的具體步驟是什麼

演算法:Apriori
輸入:D - 事務資料庫;min_sup - 最小支持度計數閾值
輸出:L - D中的頻繁項集
方法:
L1=find_frequent_1-itemsets(D); // 找出所有頻繁1項集
For(k=2;Lk-1!=null;k++){
Ck=apriori_gen(Lk-1); // 產生候選,並剪枝
For each 事務t in D{ // 掃描D進行候選計數
Ct =subset(Ck,t); // 得到t的子集
For each 候選c 屬於 Ct
c.count++;
}
Lk={c屬於Ck | c.count>=min_sup}
}
Return L=所有的頻繁集;

Procere apriori_gen(Lk-1:frequent(k-1)-itemsets)
For each項集l1屬於Lk-1
For each項集 l2屬於Lk-1
If((l1[1]=l2[1])&&( l1[2]=l2[2])&&……..
&& (l1[k-2]=l2[k-2])&&(l1[k-1]<l2[k-1])) then{
c=l1連接l2 //連接步:產生候選
if has_infrequent_subset(c,Lk-1) then
delete c; //剪枝步:刪除非頻繁候選
else add c to Ck;
}
Return Ck;

Procere has_infrequent_sub(c:candidate k-itemset; Lk-1:frequent(k-1)-itemsets)
For each(k-1)-subset s of c
If s不屬於Lk-1 then
Return true;
Return false;

㈧ apriori演算法 怎麼處理連續值

Apriori演算法流程
1. 掃描資料庫,生成候選1項集和頻繁1項集。
2. 從2項集開始循環,由頻繁k-1項集生成頻繁頻繁k項集。
2.1 頻繁k-1項集生成2項子集,這里的2項指的生成的子集中有兩個k-1項集。使如有3個2項頻繁集{a, b}{b, c}{c, f},則它所有的2項子集為{{a, b}{b, c}}{{a, b}{e, f}}{{b, c}{c, f}}
2.2 對由2.1生成的2項子集中的兩個項集根據上面所述的定理 i 進行連接,生成k項集。
2.3 對k項集中的每個項集根據如上所述的定理 ii 進行計算,舍棄掉子集不是頻繁項集即不在頻繁k-1項集中的項集。
2.4 掃描資料庫,計算2.3步中過濾後的k項集的支持度,舍棄掉支持度小於閾值的項集,生成頻繁k項集。
3. 當當前生成的頻繁k項集中只有一個項集時循環結束。

㈨ 用Matlab實現apriori演算法關聯規則的挖掘程序,完整有詳細註解

下面這段是apriori演算法中由2頻繁項集找k頻繁項集的程序,程序中有兩個問題:
1、似乎while循環的K永遠都是固定的,也就是都是頻繁2項集的個數。得到頻繁3項集後K的個數不是要變嗎?如何體現呢?
2、程序中有兩個for的大循環,但是發現結果是只要找到一個頻繁3項集第二個for循環就會結束,但是其實還應該有其它的頻繁3項集。for循環不是應該無條件執行到參數k結束嗎?當時k值是15,可是程序結束的時候i=2,j=3,然後j就不執行4以及一直到k的部分了。是什麼原因呢?麻煩高手指點一下。急啊……
while( k>0)
le=length(candidate{1});
num=2;
nl=0;
for i=1:k-1
for j=i+1:k
x1=candidate{i}; %candidate初始值為頻繁2項集,這個表示頻繁項集的第i項
x2=candidate{j};
c = intersect(x1, x2);
M=0;
r=1;
nn=0;
l1=0;
if (length(c)==le-1) & (sum(c==x1(1:le-1))==le-1)
houxuan=union(x1(1:le),x2(le));
%樹剪枝,若一個候選項的某個K-1項子集為非頻繁,則剪枝掉
sub_set=subset(houxuan);
%生成該候選項的所有K-1項子集
NN=length(sub_set);
%判斷這些K-1項自己是否都為頻繁的
while(r & M<NN)
M=M+1;
r=in(sub_set{M},candidate);
end
if M==NN
nl=nl+1;
%候選k項集
cand{nl}=houxuan;
%記錄每個候選k項集出現的次數
le=length(cand{1});
for i=1:m
s=cand{nl};
x=X(i,:);
if sum(x(s))==le
nn=nn+1;
end
end
end
end
%從候選集中找頻繁項集
if nn>=th
ll=ll+1;
candmid{nl}=cand{nl};
pfxj(nl).element=cand{nl};
pfxj(nl).time=nn;
disp('得到的頻繁項集為:')
result=(candmid{nl});
disp(result);
end

end
end
end

㈩ 數據挖掘十大演算法-

整理里一晚上的數據挖掘演算法,其中主要引自wiki和一些論壇。發布到上作為知識共享,但是發現Latex的公式轉碼到網頁的時候出現了丟失,暫時沒找到解決方法,有空再回來填坑了。

——編者按

一、 C4.5

C4.5演算法是由Ross Quinlan開發的用於產生決策樹的演算法[1],該演算法是對Ross Quinlan之前開發的ID3演算法的一個擴展。C4.5演算法主要應用於統計分類中,主要是通過分析數據的信息熵建立和修剪決策樹。

1.1 決策樹的建立規則

在樹的每個節點處,C4.5選擇最有效地方式對樣本集進行分裂,分裂規則是分析所有屬性的歸一化的信息增益率,選擇其中增益率最高的屬性作為分裂依據,然後在各個分裂出的子集上進行遞歸操作。

依據屬性A對數據集D進行分類的信息熵可以定義如下:

劃分前後的信息增益可以表示為:

那麼,歸一化的信息增益率可以表示為:

1.2 決策樹的修剪方法

C4.5採用的剪枝方法是悲觀剪枝法(Pessimistic Error Pruning,PEP),根據樣本集計運算元樹與葉子的經驗錯誤率,在滿足替換標准時,使用葉子節點替換子樹。

不妨用K表示訓練數據集D中分類到某一個葉子節點的樣本數,其中其中錯誤分類的個數為J,由於用估計該節點的樣本錯誤率存在一定的樣本誤差,因此用表示修正後的樣本錯誤率。那麼,對於決策樹的一個子樹S而言,設其葉子數目為L(S),則子樹S的錯誤分類數為:

設數據集的樣本總數為Num,則標准錯誤可以表示為:

那麼,用表示新葉子的錯誤分類數,則選擇使用新葉子節點替換子樹S的判據可以表示為:

二、KNN

最近鄰域演算法(k-nearest neighbor classification, KNN)[2]是一種用於分類和回歸的非參數統計方法。KNN演算法採用向量空間模型來分類,主要思路是相同類別的案例彼此之間的相似度高,從而可以藉由計算未知樣本與已知類別案例之間的相似度,來實現分類目標。KNN是一種基於局部近似和的實例的學習方法,是目前最簡單的機器學習演算法之一。

在分類問題中,KNN的輸出是一個分類族群,它的對象的分類是由其鄰居的「多數表決」確定的,k個最近鄰居(k為正整數,通常較小)中最常見的分類決定了賦予該對象的類別。若k = 1,則該對象的類別直接由最近的一個節點賦予。在回歸問題中,KNN的輸出是其周圍k個鄰居的平均值。無論是分類還是回歸,衡量鄰居的權重都非常重要,目標是要使較近鄰居的權重比較遠鄰居的權重大,例如,一種常見的加權方案是給每個鄰居權重賦值為1/d,其中d是到鄰居的距離。這也就自然地導致了KNN演算法對於數據的局部結構過於敏感。

三、Naive Bayes

在機器學習的眾多分類模型中,應用最為廣泛的兩種分類模型是決策樹模型(Decision Tree Model)和樸素貝葉斯模型(Naive Bayesian Model,NBC)[3]。樸素貝葉斯模型發源於古典數學理論,有著堅實的數學基礎,以及穩定的分類效率。同時,NBC模型所需估計的參數很少,對缺失數據不太敏感,演算法也比較簡單。

在假設各個屬性相互獨立的條件下,NBC模型的分類公式可以簡單地表示為:

但是實際上問題模型的屬性之間往往是非獨立的,這給NBC模型的分類准確度帶來了一定影響。在屬性個數比較多或者屬性之間相關性較大時,NBC模型的分類效率比不上決策樹模型;而在屬性相關性較小時,NBC模型的性能最為良好。

四、CART

CART演算法(Classification And Regression Tree)[4]是一種二分遞歸的決策樹,把當前樣本劃分為兩個子樣本,使得生成的每個非葉子結點都有兩個分支,因此CART演算法生成的決策樹是結構簡潔的二叉樹。由於CART演算法構成的是一個二叉樹,它在每一步的決策時只能是「是」或者「否」,即使一個feature有多個取值,也是把數據分為兩部分。在CART演算法中主要分為兩個步驟:將樣本遞歸劃分進行建樹過程;用驗證數據進行剪枝。

五、K-means

k-平均演算法(k-means clustering)[5]是源於信號處理中的一種向量量化方法,現在則更多地作為一種聚類分析方法流行於數據挖掘領域。k-means的聚類目標是:把n個點(可以是樣本的一次觀察或一個實例)劃分到k個聚類中,使得每個點都屬於離他最近的均值(此即聚類中心)對應的聚類。

5.1 k-means的初始化方法

通常使用的初始化方法有Forgy和隨機劃分(Random Partition)方法。Forgy方法隨機地從數據集中選擇k個觀測作為初始的均值點;而隨機劃分方法則隨機地為每一觀測指定聚類,然後執行「更新」步驟,即計算隨機分配的各聚類的圖心,作為初始的均值點。Forgy方法易於使得初始均值點散開,隨機劃分方法則把均值點都放到靠近數據集中心的地方;隨機劃分方法一般更適用於k-調和均值和模糊k-均值演算法。對於期望-最大化(EM)演算法和標准k-means演算法,Forgy方法作為初始化方法的表現會更好一些。

5.2 k-means的標准演算法

k-means的標准演算法主要包括分配(Assignment)和更新(Update),在初始化得出k個均值點後,演算法將會在這兩個步驟中交替執行。

分配(Assignment):將每個觀測分配到聚類中,使得組內平方和達到最小。

更新(Update):對於上一步得到的每一個聚類,以聚類中觀測值的圖心,作為新的均值點。

六、Apriori

Apriori演算法[6]是一種最有影響的挖掘布爾關聯規則頻繁項集的演算法,其核心是基於兩階段頻集思想的遞推演算法。該關聯規則在分類上屬於單維、單層、布爾關聯規則。Apriori採用自底向上的處理方法,每次只擴展一個對象加入候選集,並且使用數據集對候選集進行檢驗,當不再產生匹配條件的擴展對象時,演算法終止。

Apriori的缺點在於生成候選集的過程中,演算法總是嘗試掃描整個數據集並盡可能多地添加擴展對象,導致計算效率較低;其本質上採用的是寬度優先的遍歷方式,理論上需要遍歷次才可以確定任意的最大子集S。

七、SVM

支持向量機(Support Vector Machine, SVM)[7]是在分類與回歸分析中分析數據的監督式學習模型與相關的學習演算法。給定一組訓練實例,每個訓練實例被標記為屬於兩個類別中的一個或另一個,SVM訓練演算法創建一個將新的實例分配給兩個類別之一的模型,使其成為非概率二元線性分類器。SVM模型是將實例表示為空間中的點,這樣映射就使得單獨類別的實例被盡可能寬的明顯的間隔分開。然後,將新的實例映射到同一空間,並基於它們落在間隔的哪一側來預測所屬類別。

除了進行線性分類之外,SVM還可以使用所謂的核技巧有效地進行非線性分類,將其輸入隱式映射到高維特徵空間中,即支持向量機在高維或無限維空間中構造超平面或超平面集合,用於分類、回歸或其他任務。直觀來說,分類邊界距離最近的訓練數據點越遠越好,因為這樣可以縮小分類器的泛化誤差。

八、EM

最大期望演算法(Expectation–Maximization Algorithm, EM)[7]是從概率模型中尋找參數最大似然估計的一種演算法。其中概率模型依賴於無法觀測的隱性變數。最大期望演算法經常用在機器學習和計算機視覺的數據聚類(Data Clustering)領域。最大期望演算法經過兩個步驟交替進行計算,第一步是計算期望(E),利用對隱藏變數的現有估計值,計算其最大似然估計值;第二步是最大化(M),最大化在E步上求得的最大似然值來計算參數的值。M步上找到的參數估計值被用於下一個E步計算中,這個過程不斷交替進行。

九、PageRank

PageRank演算法設計初衷是根據網站的外部鏈接和內部鏈接的數量和質量對網站的價值進行衡量。PageRank將每個到網頁的鏈接作為對該頁面的一次投票,被鏈接的越多,就意味著被其他網站投票越多。

演算法假設上網者將會不斷點網頁上的鏈接,當遇到了一個沒有任何鏈接出頁面的網頁,這時候上網者會隨機轉到另外的網頁開始瀏覽。設置在任意時刻,用戶到達某頁面後並繼續向後瀏覽的概率,該數值是根據上網者使用瀏覽器書簽的平均頻率估算而得。PageRank值可以表示為:

其中,是被研究的頁面集合,N表示頁面總數,是鏈接入頁面的集合,是從頁面鏈接處的集合。

PageRank演算法的主要缺點是的主要缺點是舊的頁面等級會比新頁面高。因為即使是非常好的新頁面也不會有很多外鏈,除非它是某個站點的子站點。

十、AdaBoost

AdaBoost方法[10]是一種迭代演算法,在每一輪中加入一個新的弱分類器,直到達到某個預定的足夠小的錯誤率。每一個訓練樣本都被賦予一個權重,表明它被某個分類器選入訓練集的概率。如果某個樣本點已經被准確地分類,那麼在構造下一個訓練集中,它被選中的概率就被降低;相反,如果某個樣本點沒有被准確地分類,那麼它的權重就得到提高。通過這樣的方式,AdaBoost方法能「聚焦於」那些較難分的樣本上。在具體實現上,最初令每個樣本的權重都相等,對於第k次迭代操作,我們就根據這些權重來選取樣本點,進而訓練分類器Ck。然後就根據這個分類器,來提高被它分錯的的樣本的權重,並降低被正確分類的樣本權重。然後,權重更新過的樣本集被用於訓練下一個分類器Ck[,並且如此迭代地進行下去。

AdaBoost方法的自適應在於:前一個分類器分錯的樣本會被用來訓練下一個分類器。AdaBoost方法對於雜訊數據和異常數據很敏感。但在一些問題中,AdaBoost方法相對於大多數其它學習演算法而言,不會很容易出現過擬合現象。AdaBoost方法中使用的分類器可能很弱(比如出現很大錯誤率),但只要它的分類效果比隨機好一點(比如兩類問題分類錯誤率略小於0.5),就能夠改善最終得到的模型。而錯誤率高於隨機分類器的弱分類器也是有用的,因為在最終得到的多個分類器的線性組合中,可以給它們賦予負系數,同樣也能提升分類效果。

引用

[1] Quinlan, J. R. C4.5: Programs for Machine Learning. Morgan Kaufmann Publishers, 1993.

[2] Altman, N. S. An introction to kernel and nearest-neighbor nonparametric regression. The American Statistician. 1992, 46 (3): 175–185. doi:10.1080/00031305.1992.10475879

[3] Webb, G. I.; Boughton, J.; Wang, Z. Not So Naive Bayes: Aggregating One-Dependence Estimators. Machine Learning (Springer). 2005, 58 (1): 5–24. doi:10.1007/s10994-005-4258-6

[4] decisiontrees.net Interactive Tutorial

[5] Hamerly, G. and Elkan, C. Alternatives to the k-means algorithm that find better clusterings (PDF). Proceedings of the eleventh international conference on Information and knowledge management (CIKM). 2002

[6] Rakesh Agrawal and Ramakrishnan Srikant. Fast algorithms for mining association rules in large databases. Proceedings of the 20th International Conference on Very Large Data Bases, VLDB, pages 487-499, Santiago, Chile, September 1994.

[7] Cortes, C.; Vapnik, V. Support-vector networks. Machine Learning. 1995, 20 (3): 273–297. doi:10.1007/BF00994018

[8] Arthur Dempster, Nan Laird, and Donald Rubin. "Maximum likelihood from incomplete data via the EM algorithm". Journal of the Royal Statistical Society, Series B, 39 (1):1–38, 1977

[9] Susan Moskwa. PageRank Distribution Removed From WMT. [October 16, 2009]

[10] Freund, Yoav; Schapire, Robert E. A Decision-Theoretic Generalization of on-Line Learning and an Application to Boosting. 1995. CiteSeerX: 10.1.1.56.9855

熱點內容
python文件刪除一行 發布:2025-05-14 08:06:58 瀏覽:720
如何下載奧特曼高級化3安卓版 發布:2025-05-14 07:47:31 瀏覽:346
qml文件修改後編譯未生效 發布:2025-05-14 07:31:00 瀏覽:331
內到內演算法 發布:2025-05-14 07:29:11 瀏覽:34
文件夾名字不顯示 發布:2025-05-14 07:27:47 瀏覽:775
oracle的資料庫驅動jar 發布:2025-05-14 07:23:20 瀏覽:556
我的世界電腦版伺服器手機版能進嗎 發布:2025-05-14 07:22:01 瀏覽:679
達內培訓php多少錢 發布:2025-05-14 07:19:10 瀏覽:27
python位元組轉字元串 發布:2025-05-14 07:06:35 瀏覽:423
subplotpython 發布:2025-05-14 06:53:51 瀏覽:662