]> git.donarmstrong.com Git - mothur.git/blob - randomforest.cpp
d998de63ee8f31df493cd8546ecb5fb00b83311c
[mothur.git] / randomforest.cpp
1 //
2 //  randomforest.cpp
3 //  Mothur
4 //
5 //  Created by Sarah Westcott on 10/2/12.
6 //  Copyright (c) 2012 Schloss Lab. All rights reserved.
7 //
8
9 #include "randomforest.hpp" 
10
11 /***********************************************************************/
12
13 RandomForest::RandomForest(const vector <vector<int> > dataSet,
14                            const int numDecisionTrees,
15                            const string treeSplitCriterion = "gainratio",
16                            const bool doPruning = false,
17                            const float pruneAggressiveness = 0.9,
18                            const bool discardHighErrorTrees = true,
19                            const float highErrorTreeDiscardThreshold = 0.4,
20                            const string optimumFeatureSubsetSelectionCriteria = "log2",
21                            const float featureStandardDeviationThreshold = 0.0)
22             : Forest(dataSet, numDecisionTrees, treeSplitCriterion, doPruning, pruneAggressiveness, discardHighErrorTrees, highErrorTreeDiscardThreshold, optimumFeatureSubsetSelectionCriteria, featureStandardDeviationThreshold) {
23     m = MothurOut::getInstance();
24 }
25
26 /***********************************************************************/
27 // DONE
28 int RandomForest::calcForrestErrorRate() {
29     try {
30         int numCorrect = 0;
31         for (map<int, vector<int> >::iterator it = globalOutOfBagEstimates.begin(); it != globalOutOfBagEstimates.end(); it++) {
32             
33             if (m->control_pressed) { return 0; }
34             
35             int indexOfSample = it->first;
36             vector<int> predictedOutComes = it->second;
37             vector<int>::iterator maxPredictedOutComeIterator = max_element(predictedOutComes.begin(), predictedOutComes.end());
38             int majorityVotedOutcome = (int)(maxPredictedOutComeIterator - predictedOutComes.begin());
39             int realOutcome = dataSet[indexOfSample][numFeatures];
40                                    
41             if (majorityVotedOutcome == realOutcome) { numCorrect++; }
42         }
43         
44         // TODO: save or return forrestErrorRate for future use;
45         double forrestErrorRate = 1 - ((double)numCorrect / (double)globalOutOfBagEstimates.size());
46         
47         m->mothurOut("numCorrect = " + toString(numCorrect)+ "\n");
48         m->mothurOut("forrestErrorRate = " + toString(forrestErrorRate)+ "\n");
49             
50         return 0;
51     }
52         catch(exception& e) {
53                 m->errorOut(e, "RandomForest", "calcForrestErrorRate");
54                 exit(1);
55         } 
56 }
57 /***********************************************************************/
58
59 int RandomForest::printConfusionMatrix(map<int, string> intToTreatmentMap) {
60     try {
61         int numGroups = intToTreatmentMap.size();
62         vector<vector<int> > cm(numGroups, vector<int>(numGroups, 0));
63         
64         for (map<int, vector<int> >::iterator it = globalOutOfBagEstimates.begin(); it != globalOutOfBagEstimates.end(); it++) {
65             
66             if (m->control_pressed) { return 0; }
67             
68             int indexOfSample = it->first; //key
69             vector<int> predictedOutComes = it->second; //value, vector of all predicted classes
70             vector<int>::iterator maxPredictedOutComeIterator = max_element(predictedOutComes.begin(), predictedOutComes.end());
71             int majorityVotedOutcome = (int)(maxPredictedOutComeIterator - predictedOutComes.begin());
72             int realOutcome = dataSet[indexOfSample][numFeatures];                       
73             cm[realOutcome][majorityVotedOutcome] = cm[realOutcome][majorityVotedOutcome] + 1;
74         }
75         
76         vector<int> fw;
77         for (int w = 0; w <numGroups; w++) {
78             fw.push_back(intToTreatmentMap[w].length());
79         }
80         
81         m->mothurOut("confusion matrix:\n\t\t");
82         for (int k = 0; k < numGroups; k++) {
83             //m->mothurOut(intToTreatmentMap[k] + "\t");
84             cout << setw(fw[k]) << intToTreatmentMap[k] << "\t";
85         }
86         for (int i = 0; i < numGroups; i++) {
87             cout << "\n" << setw(fw[i]) << intToTreatmentMap[i] << "\t";
88             //m->mothurOut("\n" + intToTreatmentMap[i] + "\t");
89             if (m->control_pressed) { return 0; }
90             for (int j = 0; j < numGroups; j++) {
91                 //m->mothurOut(toString(cm[i][j]) + "\t");
92                 cout << setw(fw[i]) << cm[i][j] << "\t";
93             }    
94         }
95         //m->mothurOut("\n");
96         cout << "\n";
97
98         return 0;
99     }
100     
101     catch(exception& e) {
102                 m->errorOut(e, "RandomForest", "printConfusionMatrix");
103                 exit(1);
104         }
105 }
106
107 /***********************************************************************/
108
109 int RandomForest::getMissclassifications(string filename, map<int, string> intToTreatmentMap, vector<string> names) {
110     try {
111         ofstream out;
112         m->openOutputFile(filename, out);
113         out <<"Sample\tRF classification\tActual classification\n";
114         for (map<int, vector<int> >::iterator it = globalOutOfBagEstimates.begin(); it != globalOutOfBagEstimates.end(); it++) {
115             
116             if (m->control_pressed) { return 0; }
117             
118             int indexOfSample = it->first;
119             vector<int> predictedOutComes = it->second;
120             vector<int>::iterator maxPredictedOutComeIterator = max_element(predictedOutComes.begin(), predictedOutComes.end());
121             int majorityVotedOutcome = (int)(maxPredictedOutComeIterator - predictedOutComes.begin());
122             int realOutcome = dataSet[indexOfSample][numFeatures];
123                                    
124             if (majorityVotedOutcome != realOutcome) {             
125                 out << names[indexOfSample] << "\t" << intToTreatmentMap[majorityVotedOutcome] << "\t" << intToTreatmentMap[realOutcome] << endl;
126                                 
127             }
128         }
129         
130         out.close();    
131         return 0;
132     }
133         catch(exception& e) {
134                 m->errorOut(e, "RandomForest", "getMissclassifications");
135                 exit(1);
136         } 
137 }
138
139 /***********************************************************************/
140 int RandomForest::calcForrestVariableImportance(string filename) {
141     try {
142     
143         // follow the link: http://en.wikipedia.org/wiki/Dynamic_cast
144         //if you are going to dynamically cast, aren't you undoing the advantage of abstraction. Why abstract at all?
145         //could cause maintenance issues later if other types of Abstract decison trees are created that cannot be cast as a decision tree.
146         for (int i = 0; i < decisionTrees.size(); i++) {
147             if (m->control_pressed) { return 0; }
148             
149             DecisionTree* decisionTree = dynamic_cast<DecisionTree*>(decisionTrees[i]);
150             
151             for (int j = 0; j < numFeatures; j++) {
152                 globalVariableImportanceList[j] += (double)decisionTree->variableImportanceList[j];
153             }
154         }
155         
156         for (int i = 0;  i < numFeatures; i++) {
157             globalVariableImportanceList[i] /= (double)numDecisionTrees;
158         }
159         
160         vector< pair<int, double> > globalVariableRanks;
161         for (int i = 0; i < globalVariableImportanceList.size(); i++) {
162             //cout << "[" << i << ',' << globalVariableImportanceList[i] << "], ";
163             if (globalVariableImportanceList[i] > 0) {
164                 pair<int, double> globalVariableRank(0, 0.0);
165                 globalVariableRank.first = i;
166                 globalVariableRank.second = globalVariableImportanceList[i];
167                 globalVariableRanks.push_back(globalVariableRank);
168             }
169         }
170         
171 //        for (int i = 0; i < globalVariableRanks.size(); i++) {
172 //            cout << m->currentBinLabels[(int)globalVariableRanks[i][0]] << '\t' << globalVariableImportanceList[globalVariableRanks[i][0]] << endl;
173 //        }
174
175         
176         VariableRankDescendingSorterDouble variableRankDescendingSorter;
177         sort(globalVariableRanks.begin(), globalVariableRanks.end(), variableRankDescendingSorter);
178         
179         ofstream out;
180         m->openOutputFile(filename, out);
181         out <<"OTU\tMean decrease accuracy\n";
182         for (int i = 0; i < globalVariableRanks.size(); i++) {
183             out << m->currentBinLabels[(int)globalVariableRanks[i].first] << '\t' << globalVariableImportanceList[globalVariableRanks[i].first] << endl;
184         }
185         out.close();
186         return 0;
187     }
188         catch(exception& e) {
189                 m->errorOut(e, "RandomForest", "calcForrestVariableImportance");
190                 exit(1);
191         }  
192 }
193 /***********************************************************************/
194 int RandomForest::populateDecisionTrees() {
195     try {
196         
197         vector<double> errorRateImprovements;
198         
199         for (int i = 0; i < numDecisionTrees; i++) {
200           
201             if (m->control_pressed) { return 0; }
202             if (((i+1) % 100) == 0) {  m->mothurOut("Creating " + toString(i+1) + " (th) Decision tree\n");  }
203           
204             // TODO: need to first fix if we are going to use pointer based system or anything else
205             DecisionTree* decisionTree = new DecisionTree(dataSet, globalDiscardedFeatureIndices, OptimumFeatureSubsetSelector(optimumFeatureSubsetSelectionCriteria), treeSplitCriterion, featureStandardDeviationThreshold);
206           
207             if (m->debug && doPruning) {
208                 m->mothurOut("Before pruning\n");
209                 decisionTree->printTree(decisionTree->rootNode, "ROOT");
210             }
211             
212             int numCorrect;
213             double treeErrorRate;
214             
215             decisionTree->calcTreeErrorRate(numCorrect, treeErrorRate);
216             double prePrunedErrorRate = treeErrorRate;
217             
218             if (m->debug) {
219                 m->mothurOut("treeErrorRate: " + toString(treeErrorRate) + " numCorrect: " + toString(numCorrect) + "\n");
220             }
221             
222             if (doPruning) {
223                 decisionTree->pruneTree(pruneAggressiveness);
224                 if (m->debug) {
225                     m->mothurOut("After pruning\n");
226                     decisionTree->printTree(decisionTree->rootNode, "ROOT");
227                 }
228                 decisionTree->calcTreeErrorRate(numCorrect, treeErrorRate);
229             }
230             double postPrunedErrorRate = treeErrorRate;
231             
232           
233             decisionTree->calcTreeVariableImportanceAndError(numCorrect, treeErrorRate);
234             double errorRateImprovement = (prePrunedErrorRate - postPrunedErrorRate) / prePrunedErrorRate;
235
236             if (m->debug) {
237                 m->mothurOut("treeErrorRate: " + toString(treeErrorRate) + " numCorrect: " + toString(numCorrect) + "\n");
238                 if (doPruning) {
239                     m->mothurOut("errorRateImprovement: " + toString(errorRateImprovement) + "\n");
240                 }
241             }
242             
243             
244             if (discardHighErrorTrees) {
245                 if (treeErrorRate < highErrorTreeDiscardThreshold) {
246                     updateGlobalOutOfBagEstimates(decisionTree);
247                     decisionTree->purgeDataSetsFromTree();
248                     decisionTrees.push_back(decisionTree);
249                     if (doPruning) {
250                         errorRateImprovements.push_back(errorRateImprovement);
251                     }
252                 } else {
253                     delete decisionTree;
254                 }
255             } else {
256                 updateGlobalOutOfBagEstimates(decisionTree);
257                 decisionTree->purgeDataSetsFromTree();
258                 decisionTrees.push_back(decisionTree);
259                 if (doPruning) {
260                     errorRateImprovements.push_back(errorRateImprovement);
261                 }
262             }          
263         }
264         
265         double avgErrorRateImprovement = -1.0;
266         if (errorRateImprovements.size() > 0) {
267             avgErrorRateImprovement = accumulate(errorRateImprovements.begin(), errorRateImprovements.end(), 0.0);
268 //            cout << "Total " << avgErrorRateImprovement << " size " << errorRateImprovements.size() << endl;
269             avgErrorRateImprovement /= errorRateImprovements.size();
270         }
271         
272         if (m->debug && doPruning) {
273             m->mothurOut("avgErrorRateImprovement:" + toString(avgErrorRateImprovement) + "\n");
274         }
275         // m->mothurOut("globalOutOfBagEstimates = " + toStringVectorMap(globalOutOfBagEstimates)+ "\n");
276
277         
278         return 0;
279     }
280     catch(exception& e) {
281         m->errorOut(e, "RandomForest", "populateDecisionTrees");
282         exit(1);
283     }  
284 }
285 /***********************************************************************/
286 // TODO: need to finalize bettween reference and pointer for DecisionTree [partially solved]
287 // DONE: make this pure virtual in superclass
288 // DONE
289 int RandomForest::updateGlobalOutOfBagEstimates(DecisionTree* decisionTree) {
290     try {
291         for (map<int, int>::iterator it = decisionTree->outOfBagEstimates.begin(); it != decisionTree->outOfBagEstimates.end(); it++) {
292             
293             if (m->control_pressed) { return 0; }
294             
295             int indexOfSample = it->first;
296             int predictedOutcomeOfSample = it->second;
297             
298             if (globalOutOfBagEstimates.count(indexOfSample) == 0) {
299                 globalOutOfBagEstimates[indexOfSample] = vector<int>(decisionTree->numOutputClasses, 0);
300             };
301             
302             globalOutOfBagEstimates[indexOfSample][predictedOutcomeOfSample] += 1;
303         }
304         return 0;
305     }
306     catch(exception& e) {
307         m->errorOut(e, "RandomForest", "updateGlobalOutOfBagEstimates");
308         exit(1);
309     }  
310 }
311 /***********************************************************************/
312
313