Strong Root

뿌리튼튼 CS/Data Mining +2

난이도 ★★★☆ (쉽진 않지만 apriori 보다는 쉽다)


목표

information gain을 사용하여 decision tree를 만들고, 그것을 이용하여 test set을 분류하라.


요구사항

 실행파일 이름 : dt.exe


 실행프로그램 인자 : training file name, test file name




 훈련파일 형식




 테스트파일 형식



 기타 주의사항

1. Attribute 선택은 information gain값으로 한다.

2. 정확도가 높을 수록 높은 점수를 받는다.


 결과 테스트용 입력 파일

1. Training file

dt_train.txt


2. Test file

dt_test.txt


 결과 테스트용 출력 파일

dt_result.txt


 소스 코드

1. 직접 다운

dt.cpp


2. 소스 보기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#include <stdio.h>
#include <math.h>    // log2
 
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
 
#pragma warning(disable:4996)
 
#define DEBUG_MODE false    // if true, print logs
 
using namespace std;
 
typedef struct {
    vector<string> attributeNames;
    vector<vector<string>> records;
    int classLabelIndex;
} Table;
 
typedef struct Node {
    int attributeIndex;
    vector<struct Child> children;
} Node;
 
typedef struct Child {
    string value;    // attribute value
    struct Node* pNode;
    string classValue;    // only for leaves
} Child;
 
typedef struct {
    string classValue;
    int count;
} ClassValueCountPair;
 
// only for building tree
typedef struct {
    vector<vector<string>*> remainingRecords;
    vector<ClassValueCountPair> classValueCountPairs;    // for majarity voting. If size() == 1, it means that all records for the remaining records belong to the same class.
} ChildData;
 
// only for getting gains
typedef struct {
    string attributeValue;
    vector<ClassValueCountPair> classValueCountPairs;
} AttributeData;
 
// I(pi[])
double getInfo(const vector<int>* pi) {
    double sum = 0.0;
    for (int i = 0; i < pi->size(); i++) {
            sum += pi->at(i);
    }
 
    double ret = 0.0;
    for (int i = 0; i < pi->size(); i++) {
        if (pi->at(i) == 0) {
            continue;
        }
 
        ret += (-1 * pi->at(i) / sum) * log2(pi->at(i) / sum);
    }
 
    return ret;
}
 
// Gain(attribute)
double getGain(const int attributeIndex, const int classLableIndex, const vector<vector<string>*>* remainingRecords) {
    vector<ClassValueCountPair> classValueTotalCountPairs;    // for infoD
    vector<AttributeData> attributeData;    // for infoAD
 
    for (int i = 0; i < remainingRecords->size(); i++) {
        const string classValue = remainingRecords->at(i)->at(classLableIndex);
        const string attributeValue = remainingRecords->at(i)->at(attributeIndex);
 
        // make attributeData
        bool attributeValueFound = false;
        for (int j = 0; j < attributeData.size(); j++) {
            if (attributeData[j].attributeValue.compare(attributeValue) == 0) {
                bool found = false;
                for (int k = 0; k < attributeData[j].classValueCountPairs.size(); k++) {
                    if (attributeData[j].classValueCountPairs[k].classValue.compare(classValue) == 0) {
                        attributeData[j].classValueCountPairs[k].count++;
                        found = true;
                        break;
                    }
                }
 
                if (!found) {
                    ClassValueCountPair classValueCountPair;
 
                    classValueCountPair.classValue = classValue;
                    classValueCountPair.count = 1;
 
                    attributeData[j].classValueCountPairs.push_back(classValueCountPair);
                }
 
                attributeValueFound = true;
                break;
            }
        }
 
        if (!attributeValueFound) {
            AttributeData attributeDatum;
            attributeDatum.attributeValue = attributeValue;
 
            ClassValueCountPair classValueCountPair;
            classValueCountPair.classValue = classValue;
            classValueCountPair.count = 1;
            attributeDatum.classValueCountPairs.push_back(classValueCountPair);
 
            attributeData.push_back(attributeDatum);
        }
 
        // make classValueTotalCountPairs
        bool found = false;
        for (int j = 0; j < classValueTotalCountPairs.size(); j++) {
            if (classValueTotalCountPairs[j].classValue.compare(classValue) == 0) {
                classValueTotalCountPairs[j].count++;
                found = true;
                break;
            }
        }
 
        if (!found) {
            ClassValueCountPair classValueCountPair;
 
            classValueCountPair.classValue = classValue;
            classValueCountPair.count = 1;
 
            classValueTotalCountPairs.push_back(classValueCountPair);
        }
    }
 
    // get infoD
    double infoD;
    {
        vector<int> pi;
        for (int i = 0; i < classValueTotalCountPairs.size(); i++) {
            pi.push_back(classValueTotalCountPairs[i].count);
        }
        infoD = getInfo(&pi);
    }
 
    // get infoAD's sum
    double infoADSum = 0.0;
    for (int i = 0; i < attributeData.size(); i++) {
        vector<int> pi;
        double sum = 0.0;
        for (int j = 0; j < attributeData[i].classValueCountPairs.size(); j++) {
            pi.push_back(attributeData[i].classValueCountPairs[j].count);
            sum += attributeData[i].classValueCountPairs[j].count;
        }
        infoADSum += (sum / remainingRecords->size()) * getInfo(&pi);
    }
 
    if (DEBUG_MODE) {
        printf("[rec_size=%2d, att_id=%d, att_size=%d] infoD=%.3f, infoADSum=%.3f, gain=%.3f\n", remainingRecords->size(), attributeIndex, attributeData.size(), infoD, infoADSum, infoD - infoADSum);
    }
 
    return infoD - infoADSum;
}
 
// get decision tree by recursion
Node* getTree(const vector<vector<string>*> remainingRecords, vector<int> remainingAttributeIndexes, const int classLableIndex) {
    // select an attribute which has max gain
    if (DEBUG_MODE) {
        printf("** getGain **\n");
    }
    int selected = 0;
    double maxGain = getGain(remainingAttributeIndexes[selected], classLableIndex, &remainingRecords);
    for (int i = 1; i < remainingAttributeIndexes.size(); i++) {
        double gain = getGain(remainingAttributeIndexes[i], classLableIndex, &remainingRecords);
        if (gain > maxGain) {
            maxGain = gain;
            selected = i;
        }
    }
    const int selectedAttributeIndex = remainingAttributeIndexes[selected];
    if (DEBUG_MODE) {
        printf("\n\n");
    }
 
    // get new remainingAttributeIndexes which excludes the selectedAttributeIndex
    remainingAttributeIndexes.erase(remainingAttributeIndexes.begin() + selected);
 
    // make node (1) : node allocation and set node.attributeIndex
    Node* node = new Node;
    node->attributeIndex = selectedAttributeIndex;
 
    // make node (2) : make children and childData
    vector<ChildData> childData;
    for (int i = 0; i < remainingRecords.size(); i++) {
        string childValue = remainingRecords[i]->at(selectedAttributeIndex);
        string classValue = remainingRecords[i]->at(classLableIndex);
 
        bool childValueFound = false;
        for (int j = 0; j < node->children.size(); j++) {
            // found : already exists
            if (node->children[j].value.compare(childValue) == 0) {
                childData[j].remainingRecords.push_back(remainingRecords[i]);
 
                // renew classValueCountPairs
                bool classValueFound = false;
                for (int k = 0; k < childData[j].classValueCountPairs.size(); k++) {
                    if (childData[j].classValueCountPairs[k].classValue.compare(classValue) == 0) {
                        childData[j].classValueCountPairs[k].count++;
                        classValueFound = true;
                        break;
                    }
                }
                if (!classValueFound) {
                    ClassValueCountPair classValueCountPair;
 
                    classValueCountPair.classValue = classValue;
                    classValueCountPair.count = 1;
 
                    childData[j].classValueCountPairs.push_back(classValueCountPair);
                }
 
                childValueFound = true;
                break;
            }
        }
 
        // not found : create new child and new childDatum
        if (!childValueFound) {
            // create new child which will be a part of tree
            Child child;
            child.value = childValue;
            node->children.push_back(child);
 
            // create new childDatum which will be used as a parameter when building tree
            ChildData childDatum;
            childDatum.remainingRecords.push_back(remainingRecords[i]);
 
            ClassValueCountPair classValueCountPair;
            classValueCountPair.classValue = classValue;
            classValueCountPair.count = 1;
            childDatum.classValueCountPairs.push_back(classValueCountPair);
 
            childData.push_back(childDatum);
        }
    }
 
    // make node (3) : get children's nodes by recursion
    for (int i = 0; i < node->children.size(); i++) {
        // if all records for a given node belong to the same class
        if (childData[i].classValueCountPairs.size() == 1) {
            node->children[i].classValue = childData[i].classValueCountPairs[0].classValue;
            node->children[i].pNode = NULL;
        }
 
        // if there are no remaining attributes for further partitioning, majority voting is employed for classifying the leaf
        else if (remainingAttributeIndexes.empty()) {
            int maxClassValueIndex = 0;
            for (int j = 1; j < childData[i].classValueCountPairs.size(); j++) {
                if (childData[i].classValueCountPairs[j].count > childData[i].classValueCountPairs[maxClassValueIndex].count) {
                    maxClassValueIndex = j;
                }
            }
 
            node->children[i].classValue = childData[i].classValueCountPairs[maxClassValueIndex].classValue;
            node->children[i].pNode = NULL;
        }
 
        // if normal case
        else {
            node->children[i].pNode = getTree(childData[i].remainingRecords, remainingAttributeIndexes, classLableIndex);
        }
    }
 
    return node;
}
 
// get class value by recursive tree traversal
void makeDecision(vector<string>* record, const Node* node) {
    const string attributeValue = record->at(node->attributeIndex);
 
    if (DEBUG_MODE) {
        cout << attributeValue << "\t";
    }
 
    for (int i = 0; i < node->children.size(); i++) {
        if (node->children[i].value.compare(attributeValue) == 0) {
            if (node->children[i].pNode == NULL) {
                record->push_back(node->children[i].classValue);
            }
            else {
                makeDecision(record, node->children[i].pNode);
            }
 
            break;
        }
    }
}
 
int main(int argc, char** argv) {
    if (argc != 3) {
        cout << "Error Code: 001" << "\n" << "argc should be 3" << endl;
        return 0;
    }
 
    char* trainingFileName = argv[1];
    char* testFileName = argv[2];
 
    // get training table
    Table trainingTable;
    ifstream trainingFile(trainingFileName);
    if (trainingFile.is_open()) {
        string line;
 
        // get names of attributes
        if (getline(trainingFile, line)) {
            stringstream ss(line);
            string s;
 
            while (ss >> s) {
                trainingTable.attributeNames.push_back(s);
            }
        }
 
        // get records
        while (getline(trainingFile, line)) {
            stringstream ss(line);
            string s;
 
            vector<string> record;
            while (ss >> s) {
                record.push_back(s);
            }
 
            trainingTable.records.push_back(record);
        }
 
        trainingFile.close();
    }
    else {
        cout << "Error Code: 002" << "\n" << "cannot open training file. (name: " << trainingFileName << ")" << endl;
        return 0;
    }
 
    // get Decision Tree (1) : fill remainingRecords with whole records
    vector<vector<string>*> remainingRecords;
    for (int i = 0; i < trainingTable.records.size(); i++) {
        remainingRecords.push_back(&trainingTable.records[i]);
    }
 
    // get Decision Tree (2) : fill remainingAttributeIndexes with whole indexes except class label index
    trainingTable.classLabelIndex = trainingTable.attributeNames.size() - 1;
    vector<int> remainingAttributeIndexes;
    for (int i = 0; i < trainingTable.attributeNames.size(); i++) {
        if (i != trainingTable.classLabelIndex) {
            remainingAttributeIndexes.push_back(i);
        }
    }
 
    // get Decision Tree (3) : get decision tree by calling a recursive function
    Node* root = getTree(remainingRecords, remainingAttributeIndexes, trainingTable.classLabelIndex);
 
    // get test sets
    vector<vector<string>> testRecords;
    ifstream testFile(testFileName);
    if (testFile.is_open()) {
        string line;
 
        // skip names of attributes
        if (getline(testFile, line)) {
            // do nothing
        }
 
        // get records
        while (getline(testFile, line)) {
            stringstream ss(line);
            string s;
 
            vector<string> record;
            while (ss >> s) {
                record.push_back(s);
            }
 
            // get class value and save at the last column
            if (DEBUG_MODE) {
                printf("** makeDecision **\n");
            }
            makeDecision(&record, root);
            if (DEBUG_MODE) {
                printf("\n\n");
            }
 
            // push
            testRecords.push_back(record);
        }
 
        testFile.close();
    }
    else {
        cout << "Error Code: 003" << "\n" << "cannot open test file. (name: " << testFileName << ")" << endl;
        return 0;
    }
 
    // output
    const string OUTPUT_FILE_NAME = "dt_result.txt";
    ofstream outputFile(OUTPUT_FILE_NAME);
    if (outputFile.is_open()) {
        // print attribute names
        for (int i = 0; i < trainingTable.attributeNames.size(); i++) {
            outputFile << trainingTable.attributeNames[i];
            if (i < trainingTable.attributeNames.size() - 1) {
                outputFile << "\t";
            }
            else {
                outputFile << endl;
            }
        }
 
        // print attribute values and class values
        for (int i = 0; i < testRecords.size(); i++) {
            for (int j = 0; j < testRecords[i].size(); j++) {
                outputFile << testRecords[i][j];
                if (j < testRecords[i].size() - 1) {
                    outputFile << "\t";
                }
                else {
                    outputFile << endl;
                }
            }
        }
 
        outputFile.close();
    }
    else {
        cout << "Error Code: 004" << "\n" << "cannot open output file. (name: " << OUTPUT_FILE_NAME << ")" << endl;
        return 0;
    }
 
    return 0;
}
cs


 출처 : 2015년 한양대학교 김상욱 교수님의 데이터마이닝 수업 과제

'뿌리튼튼 CS > Data Mining' 카테고리의 다른 글

Apriori 알고리즘  (0) 2015.04.10

난이도 ★★★ (너무 어렵다)


요구사항

 실행파일 이름 : apriori.exe


 실행프로그램 인자 : minimum support, input file name, output file name




 입력파일 형식




 출력파일 형식


 기타 주의사항

1. 실행시 인자로 넘겨주는 Min Support값과 출력시 Support값은 %값이다.

2. 출력파일에서의 행별 정렬 순서는 중요하지 않다.


 결과 테스트용 입력 파일

input.txt


 결과 테스트용 출력 파일

1. Min Support = 10%

output_10.txt


2. Min Support = 9%

output_9.txt


3. Min Support = 6%

output_6.txt


4. Min Support = 2% (굉장히 오래걸림. 1시간 이상)

output_2.txt


 소스 코드 (답은 맞지만 느립니다. 최적의 코드가 결코 아닙니다)

1. 직접 다운

apriori.cpp


2. 소스 보기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#include <stdio.h>
#include <stdlib.h>
 
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
 
#include <set>
#include <algorithm>
 
#include <iomanip>
 
#define DEBUG_MODE true
 
#pragma warning(disable:4996)
 
using namespace std;
 
typedef struct {
    set<int> itemset;
    int sup;
} Itemset;
 
void makeC(vector<Itemset> *pC, vector<Itemset> *pLi) {
    pC->clear();
 
    // self-joining L
    for (int i = 0; i < pLi->size() - 1; i++) {
        for (int j = i + 1; j < pLi->size(); j++) {
            // get L(i) - L(j)
            set<int> i_diff_j;
            set_difference(pLi->at(i).itemset.begin(), pLi->at(i).itemset.end(),
                pLi->at(j).itemset.begin(), pLi->at(j).itemset.end(),
                inserter(i_diff_j, i_diff_j.end()));
 
            // if could
            if (i_diff_j.size() == 1) {
                // generate a candidate
                set<int> candidate;
 
                candidate.insert(pLi->at(j).itemset.begin(), pLi->at(j).itemset.end());
                candidate.insert(i_diff_j.begin(), i_diff_j.end());
 
                // redundancy check
                bool found = false;
                for each (Itemset c in *pC) {
                    set<int> result;
                    set_difference(c.itemset.begin(), c.itemset.end(), candidate.begin(), candidate.end(), inserter(result, result.end()));
                    if (result.empty()) {
                        found = true;
                        break;
                    }
                }
 
                // if not found, push
                if (!found) {
                    Itemset item;
 
                    item.itemset = candidate;
                    item.sup = 0;
 
                    pC->push_back(item);
                }
            }
        }
    }
 
    // if don't need to be pruned, return
    if ((pC->size() < 1|| (pC->at(0).itemset.size() < 3)) {
        return;
    }
 
    // pruning
    int i = 0;
    while (true) {
        if (i >= pC->size()) {
            break;
        }
 
        for (int j = 0; j < pC->at(i).itemset.size(); j++) {
            // get subSet which excludes jth number
            set<int> subSet;
 
            set<int>::iterator it = pC->at(i).itemset.begin();
            if (j == 0) {    // first
                std::advance(it, 1);
                subSet.insert(it, pC->at(i).itemset.end());
            }
            else if (j == pC->at(i).itemset.size() - 1) {    // last
                std::advance(it, j);
                subSet.insert(pC->at(i).itemset.begin(), it);
            }
            else {    // else
                std::advance(it, j);
                subSet.insert(pC->at(i).itemset.begin(), it);
 
                std::advance(it, 1);
                subSet.insert(it, pC->at(i).itemset.end());
            }
 
            // check
            bool found = false;
            for each (Itemset l in *pLi) {
                set<int> result;
                set_difference(subSet.begin(), subSet.end(), l.itemset.begin(), l.itemset.end(), inserter(result, result.end()));
                if (result.empty()) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                pC->erase(pC->begin() + i);
                i--;
                break;
            }
        }
 
        i++;
    }
}
 
void makeL(vector<vector<Itemset>> *pL, vector<Itemset> *pC, int minSupport) {
    vector<Itemset> Li;
 
    for each (Itemset c in *pC) {
        if (c.sup >= minSupport) {
            Itemset item;
 
            item.itemset = c.itemset;    // could generate error
            item.sup = c.sup;
 
            Li.push_back(item);
        }
    }
 
    pL->push_back(Li);
 
    if (DEBUG_MODE) {
        printf("\n************************\n");
        int i = pL->size() - 1;
        printf("L[%d] (size = %d, minSup = %d)\n", i, pL->at(i).size(), minSupport);
        for each (Itemset l in pL->at(i)) {
            printf("{ ");
            for each (int num in l.itemset) {
                printf("%d ", num);
            }
            printf(" }, %d\t", l.sup);
        }
        printf("\n*************************\n");
    }
}
 
set<set<int>> findSubsets(set<int> A) {
    if (A.empty()) {
        set<set<int>> ret;
        return ret;
    }
 
    set<int> tmp;
    set<int>::iterator it = A.begin();
    std::advance(it, 1);
    tmp.insert(it, A.end());
 
    set<set<int>> B = findSubsets(tmp);
 
    set<set<int>> C;
 
    int A0 = *A.begin();
    for each (set<int> D in B) {
        set<int> temp;
        temp.insert(A0);
        temp.insert(D.begin(), D.end());
        C.insert(temp);
 
        set<int> temp2;
        temp2.insert(A0);
        C.insert(temp2);
    }
    if (B.empty()) {
        set<int> temp;
 
        temp.insert(A0);
 
        C.insert(temp);
    }
 
    B.insert(C.begin(), C.end());
 
    return B;
}
 
int getSupport(set<int> *itemset, vector<vector<Itemset>> *pL) {
    for each (Itemset l in pL->at(itemset->size() - 1)) {
        set<int> result;
        set_difference(l.itemset.begin(), l.itemset.end(), itemset->begin(), itemset->end(), inserter(result, result.end()));
        if (result.empty()) {
            return l.sup;
        }
    }
 
    return -1;
}
 
int main(int argc, char** argv) {
    if (argc != 4) {
        cout << "Error Code: 001" << "\n" << "argc should be 4" << endl;
        return 0;
    }
 
    int relativeSupport = atoi(argv[1]);
    char* inputFileName = argv[2];
    char* outputFileName = argv[3];
 
    if (DEBUG_MODE) {
        printf("%d %s %s\n", relativeSupport, argv[2], argv[3]);
    }
 
    int sizeOfTransactions = 0;
 
    // scan to increment the count of all candidates in C(1)
    vector<vector<Itemset>> L;    // L(i) : frequent itemset of size i
    vector<Itemset> C;    // C(i) : candidate itemset of size i
    ifstream inputFile(inputFileName);
    if (inputFile.is_open()) {
        string line;
        while (getline(inputFile, line)) {
            sizeOfTransactions++;
 
            // get transaction
            set<int> transaction;
            stringstream ss(line);
            int num;
            while (ss >> num) {
                transaction.insert(num);
 
                // find num in C
                int target = -1;
                for (int i = 0; i < C.size(); i++) {
                    if (C[i].itemset.find(num) != C[i].itemset.end()) {
                        target = i;
                        break;
                    }
                }
 
                // not found
                if (target == -1) {
                    Itemset item;
 
                    item.itemset.insert(num);
                    item.sup = 0;
 
                    C.push_back(item);
                }
 
                // found
                else {
                    C[target].sup++;
                }
            }
 
            // get C's sup
            for each (Itemset c in C) {
                set<int> result;
                set_difference(c.itemset.begin(), c.itemset.end(), transaction.begin(), transaction.end(), inserter(result, result.end()));
                if (result.empty()) {
                    c.sup++;
                }
            }
        }
        inputFile.close();
    }
    else {
        cout << "Error Code: 002" << "\n" << "Cannot open input file. (name: " << inputFileName << ")" << endl;
        return 0;
    }
 
    // get minSupport
    int minSupport = ceil(((double)sizeOfTransactions / 100* relativeSupport);
 
    // get L(1)
    makeL(&L, &C, minSupport);
 
    // get C(i) & L(i) where i > 1
    int i = 0;
    while (true) {
        // get C(i+1)
        makeC(&C, &L[i]);
 
        // if cannot generate C(i+1), break
        if (C.empty()) {
            break;
        }
 
        // scan to increment the count of all candidates in C
        ifstream inputFile(inputFileName);
        if (inputFile.is_open()) {
            string line;
            while (getline(inputFile, line)) {
                // get transaction
                set<int> transaction;
                stringstream ss(line);
                int num;
                while (ss >> num) {
                    transaction.insert(num);
                }
 
                // get C's sup
                for (int j = 0; j < C.size(); j++) {
                    set<int> result;
                    set_difference(C[j].itemset.begin(), C[j].itemset.end(), transaction.begin(), transaction.end(), inserter(result, result.end()));
                    if (result.empty()) {
                        C[j].sup++;
                    }
                }
            }
            inputFile.close();
        }
        else {
            cout << "Error Code: 003(" << i << ")" << "\n" << "Cannot open input file. (name: " << inputFileName << ")" << endl;
            return 0;
        }
 
        // get L(i+1)
        makeL(&L, &C, minSupport);
 
        i++;
    }
    
    // output
    ofstream outputFile(outputFileName);
    if (outputFile.is_open()) {
        printf("\n*** output... ***\n");
        outputFile << fixed << setprecision(2);
        for (int i = 1; i < L.size(); i++) {
            for (int j = 0; j < L.at(i).size(); j++) {    // L.at(i) : {itemset}, {itemset}, {itemset}, ...
                // get all sizes of subset
                set<set<int>> subsets = findSubsets(L.at(i).at(j).itemset);    // L.at(i).at(j) : {itemset}
 
                for each (set<int> subset1 in subsets) {
                    set<int> subset2;
                    set_difference(L.at(i).at(j).itemset.begin(), L.at(i).at(j).itemset.end(), subset1.begin(), subset1.end(), inserter(subset2, subset2.end()));
                    if (subset2.empty()) {
                        continue;
                    }
 
                    // print subset1
                    outputFile << "{";
                    int pos = 0;
                    for each (int item in subset1) {
                        outputFile << item;
                        if (pos < subset1.size() - 1) {
                            outputFile << ",";
                        }
                        else {
                            outputFile << "}\t";
                        }
                        pos++;
                    }
 
                    // print subset2
                    outputFile << "{";
                    pos = 0;
                    for each (int item in subset2) {
                        outputFile << item;
                        if (pos < subset2.size() - 1) {
                            outputFile << ",";
                        }
                        else {
                            outputFile << "}\t";
                        }
                        pos++;
                    }
 
                    // print relative support of original set (subset1 + subset2)
                    outputFile << (L.at(i).at(j).sup / (double)sizeOfTransactions) * 100 << "\t";
 
                    // print confidence (original set's support / subset1's support)
                    outputFile << (L.at(i).at(j).sup / (double)getSupport(&subset1, &L)) * 100 << endl;
                }
            }
        }
 
        outputFile.close();
    }
    else {
        cout << "Error Code: 004" << "\n" << "Cannot open output file. (name: " << outputFileName << ")" << endl;
        return 0;
    }
 
    return 0;
}
cs


 출처 : 2015년 한양대학교 김상욱 교수님의 데이터마이닝 수업 과제


'뿌리튼튼 CS > Data Mining' 카테고리의 다른 글

Decision Tree  (0) 2015.04.23