Rudhra
Rudhra

Reputation: 284

Write the output to a file for every n iterations

Hello Everyone, This is the following code of a package:

for (int iter = 0; iter < flags.total_iterations_; ++iter) {
std::cout << "Iteration " << iter << " ...\n";
if (flags.compute_likelihood_ == "true") {
  double loglikelihood = 0;
  for (list<LDADocument*>::const_iterator iterator = corpus.begin();
       iterator != corpus.end();
       ++iterator) {
    loglikelihood += sampler.LogLikelihood(*iterator);
  }
  std::cout << "Loglikelihood: " << loglikelihood << std::endl;
}
sampler.DoIteration(&corpus, true, iter < flags.burn_in_iterations_);
}
accum_model.AverageModel(
  flags.total_iterations_ - flags.burn_in_iterations_);

FreeCorpus(&corpus);

std::ofstream fout(flags.model_file_.c_str());
accum_model.AppendAsString(word_index_map, fout);

return 0;

I would like to tweak this in such a way that for every 20 iterations, I would like to write a file that stores the result of fout. I am actually beginner in code coding in python. Since the package has the codes in c++, I have no idea what to input where.

I understand the logic like:

There must be a counter which counts the iteration and for every 20th iteration, a file must be created and the result of fout must be saved in that file. And for every 20th iteration I need new files to be created as I do not want the contents to be overwritten for analysis purpose.

Please help me as am a newbie and totally clueless about c++. Thanks in advance!

Upvotes: 0

Views: 1596

Answers (1)

Sanathana
Sanathana

Reputation: 284

Try this:

    for (int iter = 0; iter < flags.total_iterations_; ++iter) { 
      double loglikelihood = 0;
      std::cout << "Iteration " << iter << " ...\n";
      if(iter%20==0) {
         const char *path1 = "Your path to the files" 
         std::ofstream llh_file;
         std::ofstream myfile;
         std::string result;
         char numstr[30];
         sprintf(numstr, "%d", iter);
         result = path1 + std::string (numstr) + ".txt";
         myfile.open(result.c_str());
         model.AppendAsString(myfile);   
         myfile.close();   

Upvotes: 1

Related Questions