本文整理汇总了C++中Forest类的典型用法代码示例。如果您正苦于以下问题:C++ Forest类的具体用法?C++ Forest怎么用?C++ Forest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Forest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: trainTree
void trainTree(string treeFile, string trainDir) {
SerializeHelper sHelp = SerializeHelper();
ImageReader imReader = ImageReader();
vector<Mat> depthImages = imReader.readDepthImages(trainDir);
vector<Mat> classifiedImages = imReader.readClassifiedImages(trainDir);
int times = clock();
// 7 classes, 15 deep, 200 features, 50 thresholds, 0.02 subsampling, 1 minnuminnode, 10 background penalty, feature range, threshold range
Forest forest = Forest(6, 15, 500, 100, 0.05, 10, 0, pair<double, double>(150, 150), pair<double, double>(-255,255));
// 500 image per tree. Three made at once.
forest.makeTrees(depthImages, classifiedImages, 150, 3);
int timed = clock();
cout << "Making trees took "<< (timed-times) <<" ticks.\n"<< endl;
//Forest forest = sHelp.loadForest("MediumTree100F1000.txt");
sHelp.serializeForest(forest, treeFile);
string graphvix = forest.getTrees().at(0)->graphvizPrint(-1, NULL);
}
示例2: main
int main(int argc, char ** argv) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
google::ParseCommandLineFlags(&argc, &argv, true);
wvector * weight = cmd_weights();
Ngram * lm = cmd_lm();
istringstream range(FLAGS_forest_range);
int start_range, end_range;
range >> start_range >> end_range;
for (int i = start_range; i <= end_range; i++) {
stringstream fname;
fname << FLAGS_forest_prefix << i;
Forest f = Forest::from_file(fname.str().c_str());
// Load lattice
stringstream fname2;
fname2 << FLAGS_lattice_prefix << i;
ForestLattice graph = ForestLattice::from_file(fname2.str());
int var_type;
if (FLAGS_continuous == 1) {
var_type = GRB_CONTINUOUS;
} else {
var_type = GRB_BINARY;
}
LPBuilder lp(f, graph, var_type);
const Cache <Graphnode, int> * word_cache = sync_lattice_lm(graph, *lm);
HypergraphAlgorithms alg(f);
EdgeCache * w = alg.cache_edge_weights( *weight);
try {
lp.solve_full(i, *w, *lm, lm_weight(), *word_cache);
}
catch (GRBException e) {
cerr << "Error code = " << e.getErrorCode() << endl;
cerr << e.getMessage() << endl;
cout << "*END* " << i<< " "<<0 << " " << 100 << " "<< 0 << " " << 0 << endl;
}
NodeBackCache bcache(f.num_nodes());
NodeCache ncache(f.num_nodes());
//double best = best_path(f, *w, ncache, bcache);
//cout << best << endl;
}
return 1;
}
示例3: create
static Target create( const Option& o )
{
Forest* forest = new Forest( &o );
TargetValue* THIS = new TargetValue( forest );
forest->setTHIS(THIS);
Target target = THIS;
forest->build(o);
//l.addFeature( target );
return target;
}
示例4: classifyOneImage
void classifyOneImage(string forest, string depthFile) {
Mat depthImage = imread(depthFile, 0);
SerializeHelper sHelp = SerializeHelper();
Forest f = sHelp.loadForest(forest);
Mat classified = f.classifyImage(depthImage);
Mat cimg = convertToColorForBaby(classified);
imshow("Hopethisworks", cimg);
waitKey(30);
}
示例5: analyze
FL::ParseResult AB::analyze(
const TimeSeries &ts, Forest &forest, Patterns::Matcher &matcher, PatternsSet &patterns, MetricsSet &metrics)
{
ParseResult result;
try
{
if (ts.size() < 2)
throw EAnalyze(E_INVALID_INPUT);
Tree *tree = new Tree(ts);
const int up = IDGenerator::idOf("a");
const int down = IDGenerator::idOf("b");
for (int i = 0; i < ts.size()-1; i += 1)
{
const int &id = (ts.value(i) <= ts.value(i+1)) ? up : down;
tree->add(new Node(NULL, id, i, i+1, 0));
}
forest.push_back(tree);
result.treesAdded = 1;
result.nodesAdded = (ts.size() + 1) / 2;
}
catch (const EAnalyze &e)
{
m_lastError = e;
}
return result;
}
示例6: set_forest
/**
* [Angelo::set_forest Set member data from current forest.]
* @param forest [A freshly generated forest.]
* @return [Whether setting was successful or not.]
*/
bool Angelo::set_forest( const Forest& forest )
{
// Get forest information
Forest::agl_pair_type cfg;
Forest::agl_vector_type cx;
forest.acm_export( cfg, cx );
// Remember the number of trees
n_nodes = cfg.first;
// Reset adjacency
memset( adjacency, 0, 22*sizeof(int) );
for ( auto it = cx.cbegin(); it != cx.cend(); ++it )
{
adjacency[ it->first ] |= 1 << it->second;
adjacency[ it->second ] |= 1 << it->first;
}
// Compute results
impossible = !bfs();
// Restart iterator
restart();
// // Print shot sequence
// printf("Shot sequence(%u) = [", shot_sequence.size());
// for ( auto it = shot_sequence.begin(); it != shot_sequence.end(); ) printf(" %d ", *it++);
// if (impossible) printf("] [IMP] \n"); else printf("]\n");
// Report success
return true;
}
示例7: main
int main(int argc, char* argv[])
{
double avg = 0;
struct timeval start, finish;
if (argc != 2) {
cerr << "ERROR: Check Your Input AGAIN!\n";
return 0;
}
for (int i = 0; i < 50; i++)
{
Forest* forest = new Forest();
forest->openFile(argv[1]);
int REPS = 5;
gettimeofday(&start, NULL);
forest->parseText();
for(int j = 0; j < REPS; j++)
{
forest->printFrequency();
forest->uniqueWordCount();
forest->totalWordCount();
forest->totalCharCount();
}
gettimeofday(&finish, NULL);
double totalTime = (double)((double)(finish.tv_sec - start.tv_sec) * 1000000
+ (double)(finish.tv_usec - start.tv_usec)) / (double)REPS;
cout << totalTime << " microseconds" << endl;
avg += totalTime;
delete forest;
}
cout << avg << endl;
}
示例8: specialAdvance
void Plant::specialAdvance(Forest& forest)
{
int pop = forest.getPopulation(name);
if(pop > maxNum) {
double r = rand()/static_cast<double>(RAND_MAX);
if(r < (pop-maxNum)/static_cast<double>(maxNum)) {
repr = false;
}
}
}
示例9: poruszsie
void Infantry :: poruszsie(int x, int y, Tanki* gra){
if((x!=this->getPos(true))||(y!=this->getPos(false))){
bool zwrot = gra->Tereny[gra->GLOWNA.ODzial[x][y][0]].imove;
Forest temp;
if(!temp.check(gra->GLOWNA.ODzial[x][y][1],0))
zwrot = false;
if(gra->GLOWNA.ODzial[x][y][2]!=0)
zwrot = gra->Budynki[gra->GLOWNA.ODzial[x][y][2]].imove;
int osa;
int* UnitIter;
if(team){
osa=2;
UnitIter = &(gra->IterBlue);
} else {
osa=1;
UnitIter = &(gra->IterRed);
}
if(zwrot){
if(gra->GLOWNA.ODzial[x][y][3]!=0){ // POLE ZAJÊTE
if(gra->GLOWNA.ODzial[x][y][3]==osa){
cerr<<"Pole zajete przez naszych!\n";
gra->Gracz = !(gra->Gracz);
(*UnitIter)--;
} else {
cerr<<"Wróg!\n";
this->atak(x,y,gra);
}
} else { // POLE PUSTE
gra->meGo(this->getPos(true),this->getPos(false));
this->move(x,y);
gra->meCome(x,y,osa);
}
}
}
}
示例10: runPrediction
void runPrediction(string treeFile, string testDir, bool writeToFile, string outputFileName) {
SerializeHelper sHelp = SerializeHelper();
Forest forest = sHelp.loadForest(treeFile);
string graphvix = forest.getTrees().at(0)->graphvizPrint(-1, NULL);
ofstream graphvizFile("graphvizForest.txt");
graphvizFile << graphvix;
ImageReader imReader = ImageReader();
vector<Mat> testDepthImages = imReader.readTrainingImages(testDir);
for(int k=0; k < testDepthImages.size(); k++) {
Mat classified = forest.classifyImage(testDepthImages.at(k));
std::ostringstream path;
path << outputFileName << "/" << k+1 << "Y.png";
string windowName = path.str();
//namedWindow( windowName, WINDOW_AUTOSIZE );
//Mat cimg = convertToColorForBaby(classified);
if(writeToFile) {
//imwrite(windowName, cimg);
imwrite(windowName, classified);
}
//imshow(windowName, cimg);
//imshow(windowName, classified);
waitKey(30);
}
}
示例11: FindDirtyForests
void FindDirtyForests( SceneObject *obj, void *key )
{
Forest *forest = dynamic_cast<Forest*>(obj);
if ( forest && forest->getData()->isDirty() )
*((bool*)(key)) = true;
}
示例12: main
int
#ifdef _MSC_VER
__cdecl
#endif
main(int argc, char *argv[])
{
INITLEAK;
cin.tie(0);
istream_arg forest_in;
ostream_arg graphviz_out;
const unsigned MEGS = 1024*1024;
unsigned max_megs = (MAX_FOREST_NODES*sizeof(ForestNode)+MEGS-1)/MEGS;
string prelude;
options_description options("General options");
bool help, same_rank, number_edges, pointer_nodes;
options.add_options()
("help,h", bool_switch(&help),"produce help message")
("number-children,n", bool_switch(&number_edges),"label child edges 1,2,...,n")
("pointer-nodes,p", bool_switch(&pointer_nodes),"show dot-shaped pointer nodes for shared subforests")
("same-rank-children,s", bool_switch(&same_rank),"force children nodes to the same rank (implies -p)")
("graphviz-prelude,g", value<string>(&prelude), "graphviz .dot directives to be inserted in output graphs")
("forest-megs,M", value<unsigned>(&max_megs)->default_value(100), "Number of megabytes reserved to hold forests")
("in-forest-file,i", value<istream_arg>(&forest_in)->default_value(stdin_arg(),"STDIN"),"file containing one or more forests e.g. (OR (1 4) (1 3)) (1 #1(4 3) OR(#1 2))")
("out-graphviz-file,o", value<ostream_arg>(&graphviz_out)->default_value(stdout_arg(),"STDOUT"),"Output Graphviz .dot file (run dot -Tps out.dot -o out.ps)");
positional_options_description pos;
pos.add("in-forest-file", -1);
const char *progname = argv[0];
try {
variables_map vm;
store(command_line_parser(argc, argv).options(options).positional(pos).run(), vm);
notify(vm);
#define RETURN(i) retval = i; goto done
if (help) {
cerr << progname << ":\n";
cerr << options << "\n";
cerr << "\n" << docstring << "\n";
ABORT;
}
if (same_rank)
pointer_nodes = true;
unsigned n_nodes = max_megs*MEGS/sizeof(ForestNode);
auto_array<ForestNode> fnodes(n_nodes);
Forest f;
ForestVizPrinter<> fviz(*graphviz_out, prelude);
bool first = true;
while (*forest_in) {
f.reset(fnodes.begin(), fnodes.end());
*forest_in >> f;
if (forest_in->bad() || f.ran_out_of_space()) {
cerr << "Error reading input forest:\n";
show_error_context(*forest_in, cerr);
ABORT;
}
if (*forest_in) {
if (first)
first = false;
else
fviz.next();
fviz.print(f, same_rank, number_edges, pointer_nodes);
}
}
} catch(std::exception& e) {
cerr << "ERROR: " << e.what() << "\n\n";
cerr << options << "\n";
ABORT;
}
return 0;
}
示例13: main
int main( int argc, char** argv )
{
help();
VideoCapture capture;
SerializeHelper sHelp = SerializeHelper();
Forest forest = sHelp.loadForest("adult.txt");
// Open webcam
capture.open(CV_CAP_INTELPERC);
//cap.open("d2.avi");
if( !capture.isOpened() )
{
cout << "Could not initialize capturing...\n";
return -1;
}
capture.set(CV_CAP_INTELPERC_IMAGE_GENERATOR | CV_CAP_PROP_INTELPERC_PROFILE_IDX, 0);
capture.set(CV_CAP_INTELPERC_DEPTH_GENERATOR | CV_CAP_PROP_INTELPERC_PROFILE_IDX, 0);
namedWindow( "Depth", 1 );
namedWindow( "Color", 1 );
Mat gray, prevGray, image;
vector<Point2f> points[2];
//rect =
ImagePacket images = getFrames(capture);
Mat threshDepth;
int threshDist = 750;
threshold(images.getDepth(), threshDepth, threshDist, 100000, THRESH_TOZERO_INV);
threshDepth.convertTo(threshDepth, CV_8U);
Mat segmentedImage = forest.classifyImage(threshDepth);
imshow("Segmentation", convertToColorForBaby(segmentedImage));
Rect rect = isolateBodyPart(segmentedImage, HEAD);
TemplateTracker hTrack = TemplateTracker();
cvWaitKey(10);
hTrack.initialize(rect, images.getColor(), threshDepth, 0);
Mat color, uvMap;
for(;;)
{
ImagePacket images = getFrames(capture);
threshold(images.getDepth(), threshDepth, threshDist, 100000, THRESH_TOZERO_INV);
threshDepth.convertTo(threshDepth, CV_8U);
hTrack.track(images.getColor(), threshDepth);
forehead = getForeheadFromHead(hTrack.getTrackedRegion());
color = images.getColor();
uvMap = images.getUVMap();
Mat foreheadDepth = threshDepth(forehead);
imshow("forehead", foreheadDepth);
transpose(threshDepth, threshDepth);
transpose(color, color);
transpose(foreheadDepth, foreheadDepth);
for(int i = 0; i < foreheadDepth.rows; i++) {
for(int j = 0; j < foreheadDepth.cols; j++) {
if(foreheadDepth.at<uchar>(i,j) != 0) {
Point cPoint = translateDepthToColor(Point(j+forehead.y, i+forehead.x), color, uvMap);
if(cPoint.x < color.cols && cPoint.y < color.rows)
circle( color, cPoint, 3, Scalar(0,255,0), -1, 8);
}
}
}
transpose(threshDepth, threshDepth);
transpose(color, color);
rectangle(threshDepth, hTrack.getTrackedRegion(), Scalar(255, 0, 0), 2, 8, 0);
rectangle(threshDepth, forehead, Scalar(255, 0, 0), 2, 8, 0);
//.........这里部分代码省略.........
示例14: rangerCpp
// [[Rcpp::export]]
Rcpp::List rangerCpp(uint treetype, std::string dependent_variable_name,
Rcpp::NumericMatrix input_data, std::vector<std::string> variable_names, uint mtry, uint num_trees, bool verbose,
uint seed, uint num_threads, bool write_forest, uint importance_mode_r, uint min_node_size,
std::vector<std::vector<double>>& split_select_weights, bool use_split_select_weights,
std::vector<std::string>& always_split_variable_names, bool use_always_split_variable_names,
std::string status_variable_name, bool prediction_mode, Rcpp::List loaded_forest, Rcpp::RawMatrix sparse_data,
bool sample_with_replacement, bool probability, std::vector<std::string>& unordered_variable_names,
bool use_unordered_variable_names, bool save_memory, uint splitrule_r,
std::vector<double>& case_weights, bool use_case_weights, bool predict_all,
bool keep_inbag, double sample_fraction, double alpha, double minprop, bool holdout, uint prediction_type_r) {
Rcpp::List result;
Forest* forest = 0;
Data* data = 0;
try {
// Empty split select weights and always split variables if not used
if (!use_split_select_weights) {
split_select_weights.clear();
}
if (!use_always_split_variable_names) {
always_split_variable_names.clear();
}
if (!use_unordered_variable_names) {
unordered_variable_names.clear();
}
if (!use_case_weights) {
case_weights.clear();
}
std::ostream* verbose_out;
if (verbose) {
verbose_out = &Rcpp::Rcout;
} else {
verbose_out = new std::stringstream;
}
size_t num_rows = input_data.nrow();
size_t num_cols = input_data.ncol();
// Initialize data with double memmode
data = new DataDouble(input_data.begin(), variable_names, num_rows, num_cols);
// If there is sparse data, add it
if (sparse_data.nrow() > 1) {
data->addSparseData(sparse_data.begin(), sparse_data.ncol());
}
switch (treetype) {
case TREE_CLASSIFICATION:
if (probability) {
forest = new ForestProbability;
} else {
forest = new ForestClassification;
}
break;
case TREE_REGRESSION:
forest = new ForestRegression;
break;
case TREE_SURVIVAL:
forest = new ForestSurvival;
break;
case TREE_PROBABILITY:
forest = new ForestProbability;
break;
}
ImportanceMode importance_mode = (ImportanceMode) importance_mode_r;
SplitRule splitrule = (SplitRule) splitrule_r;
PredictionType prediction_type = (PredictionType) prediction_type_r;
// Init Ranger
forest->initR(dependent_variable_name, data, mtry, num_trees, verbose_out, seed, num_threads,
importance_mode, min_node_size, split_select_weights, always_split_variable_names, status_variable_name,
prediction_mode, sample_with_replacement, unordered_variable_names, save_memory, splitrule, case_weights,
predict_all, keep_inbag, sample_fraction, alpha, minprop, holdout, prediction_type);
// Load forest object if in prediction mode
if (prediction_mode) {
size_t dependent_varID = loaded_forest["dependent.varID"];
//size_t num_trees = loaded_forest["num.trees"];
std::vector<std::vector<std::vector<size_t>> > child_nodeIDs = loaded_forest["child.nodeIDs"];
std::vector<std::vector<size_t>> split_varIDs = loaded_forest["split.varIDs"];
std::vector<std::vector<double>> split_values = loaded_forest["split.values"];
std::vector<bool> is_ordered = loaded_forest["is.ordered"];
if (treetype == TREE_CLASSIFICATION) {
std::vector<double> class_values = loaded_forest["class.values"];
((ForestClassification*) forest)->loadForest(dependent_varID, num_trees, child_nodeIDs, split_varIDs,
split_values, class_values, is_ordered);
} else if (treetype == TREE_REGRESSION) {
((ForestRegression*) forest)->loadForest(dependent_varID, num_trees, child_nodeIDs, split_varIDs, split_values,
is_ordered);
} else if (treetype == TREE_SURVIVAL) {
size_t status_varID = loaded_forest["status.varID"];
std::vector<std::vector<std::vector<double>> > chf = loaded_forest["chf"];
std::vector<double> unique_timepoints = loaded_forest["unique.death.times"];
((ForestSurvival*) forest)->loadForest(dependent_varID, num_trees, child_nodeIDs, split_varIDs, split_values,
status_varID, chf, unique_timepoints, is_ordered);
//.........这里部分代码省略.........
示例15: getForestPrediction2Forests
DBfileindex getForestPrediction2Forests(DepthDBWithVotesSImpl<VoteType,VoteDim> &db,
Forest<DepthFeature, Stats> &forest1,
Forest<DepthFeature, Stats> &forest2,
AggregatedLeafs<DepthFeature,Stats,VoteType,VoteDim> &aggLeafs1,
AggregatedLeafs<DepthFeature,Stats,VoteType,VoteDim> &aggLeafs2,
LocalCache &cache,
const Configuration &config,
VoteType w1, VoteType w2,
std::vector<cv::Vec<VoteType,VoteDim> > &prediction, //OUT
std::vector<double> &weights, //OUT
DBindex &idx) //OUT
{
//strong assumption: the pixels of one image are following one another
std::ostream &log = cache.log();
DBfileindex img = db.getImageIdx(idx);
std::vector<DBindex> oneimage;
while(idx < db.Count() && db.getImageIdx(idx) == img){
oneimage.push_back(idx++);
}
//we dont need GT, so simple filebased index will do
SubindexFileBasedImageDB dboneimage(db,oneimage);
std::vector<std::vector<int> > leafIndicesPerTree1;
ProgressStream progress(cache.log(),Verbose);
forest1.Apply(dboneimage,leafIndicesPerTree1,&progress);
VotesAggregator<VoteType,VoteDim> imageVotes(db.voteClassCount());
for(int t=0; t< forest1.TreeCount(); t++){
for(int i=0; i< dboneimage.Count(); i++){
if(leafIndicesPerTree1[t][i]>0){
imageVotes.AddVotes(aggLeafs1.get(t,leafIndicesPerTree1[t][i]),w1);
}
}
}
std::vector<std::vector<int> > leafIndicesPerTree2;
forest2.Apply(dboneimage,leafIndicesPerTree2,&progress);
for(int t=0; t< forest2.TreeCount(); t++){
for(int i=0; i< dboneimage.Count(); i++){
if(leafIndicesPerTree2[t][i]>0){
imageVotes.AddVotes(aggLeafs2.get(t,leafIndicesPerTree2[t][i]),w1);
}
}
}
mean_shift::MeanShift finalshift;
finalshift.setRadius(config.meanShiftR());
finalshift.setMaxIter(config.meanShiftMaxIter());
finalshift.setMaxNeigboursCount(config.maxNN());
std::vector<float> imean;
std::vector<float> istd;
imean.resize(db.voteClassCount()*VoteDim);
istd.resize(db.voteClassCount()*VoteDim);
//imageVotes.Normalize(imean,istd);
std::cerr << "istd: " << istd[0] << std::endl;
imageVotes.Prediction(prediction,weights,finalshift);
imageVotes.Serialize(cache.openBinStream("imageVotes"));
/*for(int i=0; i<prediction.size();i++){
for(int j=0; j<VoteDim; j++){
prediction[i][j] = prediction[i][j]*istd[i*VoteDim+j] + imean[i*VoteDim+j];
}
}*/
log << "prediction computed" << std::endl;
return img;
}