Пример #1
0
void BP::escrever(ostream & out) {
    BP temp = *this;
    while (!temp.empty()) {
        cout << temp.front() << endl;
        temp.pop();
    }
}
Пример #2
0
int main()
{
	Vector<Data> data;
	for (int i = 0; i < 41; i++)
	{
		Data t;
		for (int j = 0; j < 3; j++)
			t.x.push_back(sample[i][j]);

		t.y.push_back(sample[i][0] + sample[i][1] + sample[i][2]);
		data.push_back(t);
	}
	BP *bp = new BP();
	bp->GetData(data);
	bp->Train();


	while (1)
	{
		Vector<Type> in;
		for (int i = 0; i < 3; i++)
		{
			Type v;
			scanf("%lf", &v);
			in.push_back(v);
		}
		Vector<Type> ou;
		ou = bp->ForeCast(in);
		printf("%lf\n", ou[0]);
	}
	return 0;
}
Пример #3
0
void gen(BP & bp) {
  static bool flip=false;
  if (flip) 
    bp.reset(new A1);
  else
    bp.reset(flop ? (B*)(new A2): (B*)(new A3));
  flip = !flip;
}
Пример #4
0
void main(void)
{   
	BP B;//生成一个BP类对象B
	B.Train();//开始训练
	B.BP_Print();//把结果打印出来
	B.After_Train_Out();//把结果保存到文件

}//end
Пример #5
0
void gen(BP & bp) {
  static bool flip=false;
  if (flip) 
    bp.reset(new A1);
  else
    bp.reset(new A2);
  flip = !flip;
}
void BruteForceOptMatching::getMaxProbAssignments(
    const BP& ia, const FactorGraph& fg, const ConnectedFactorGraph& graph,
    McDArray<McVec2i>& pairs) {

    for (int i = 0; i < graph.variables.size(); i++) {

        McDArray<int> possibleAssignments;
        getAssignmentsForVariable(graph.variables[i], possibleAssignments);
        Factor belief =
            ia.belief(Var(graph.variables[i], possibleAssignments.size() + 1));
        float maxVal = -1 * FLT_MAX;
        int maxIdx = -1;

        for (int j = 0; j < possibleAssignments.size() + 1; j++) {
            if (belief.get(j) > maxVal) {
                maxVal = belief.get(j);
                maxIdx = j;
            }
        }
        int indexOfAssignmentInVertexList =
            mapVariableAssignmentToIndexInVertexList(graph.variables[i],
                                                     maxIdx);

        McVec2i pair =
            McVec2i(graph.variables[i], indexOfAssignmentInVertexList);

        pairs.append(pair);
    }
    outputSingleFactorValues(graph);

    //    std::vector<std::size_t> maxes= ia.findMaximum();
    //    vector<std::size_t>::iterator it=maxes.begin();
}
Пример #7
0
void GI_libDAI::copyLabels_MSRC(vector<std::size_t>& labels,
                                labelType* nodeLabels,
                                BP& bp,
                                FactorGraph& fg)
{
  labelType voidLabel = classIdxToLabel[0];
  labelType moutainLabel = classIdxToLabel[4161600];
  labelType horseLabel = classIdxToLabel[8323328];

  INFERENCE_PRINT("[gi_libDAI] copyLabels_MSRC void=%d, moutain=%d, horse=%d\n",
                  (int)voidLabel, (int)moutainLabel, (int)horseLabel);

  int label;
  int n = slice->getNbSupernodes();
  for(int sid = 0; sid < n; sid++) {
    label = labels[sid];

    //if(lossPerLabel == 0 && label > 20) // void label
    if(label == voidLabel || label == moutainLabel || label == horseLabel) {
      //Factor f = bp.beliefV(sid);
      Factor f = bp.belief(fg.var(sid));
      double maxProb = -1;
      for(int i = 0; i < (int)f.states(); i++) {
        if(i != voidLabel && i != moutainLabel && i != horseLabel)
          if(maxProb < f[i]) {
            maxProb = f[i];
            label = i;
          }
      }
      //INFERENCE_PRINT("label=%d\n", label);
    }
    nodeLabels[sid] = label;
  }
}
Пример #8
0
// use bp.findmaximum instead
void GI_libDAI::getLabels(BP& bp,
                          FactorGraph& fg,
                          vector<std::size_t>& labels)
{
  float maxProb;
  int label;
  ofstream ofs("beliefs2");
  ofs << "------------------------------- UNARY -------------------------------\n";
  for(long sid = 0; sid < slice->getNbSupernodes(); sid++) {
    Factor f = bp.belief(fg.var(sid));
    maxProb = f[0];
    label = 0;
    ofs << sid;
    for(int i=1; i < (int)param->nClasses; i++) {
      ofs << " " << i << ":" << f[i];
      if(f[i] > maxProb) {
        maxProb = f[i];
        label = i;
      }
    }
    ofs << endl;
    labels[sid] = label;
  }
  ofs.close();
}
Пример #9
0
int main(int argc, char **argv)
{
    BP bp;
    int choice;
	string neg_path, pos_path, train_path, test_path, model_path;

	model_path = "model.dat";
	test_path = "test_data.dat";
	train_path = "train_data.dat";

    while( (choice=Choice()) != 0 ){
		switch( choice ){
		case TRAIN:
            if( bp.getTrainData( train_path ) > 0 ){
                bp.train(test_path);
            }else{
                cout<<"训练数据读入出错\n";
            }
            break;
        case TEST:
            if(	bp.readWeights() == 1 ){

                cout<<"Accuracy : "<< bp.test(test_path) <<endl;
            }else{
                cout<<"模型数据读入出错\n";
            }
            break;
        case CONVERT:
			neg_path = "pointing_neg_train.list";
			pos_path = "pointing_pos_train.list";
			cout<<train_path<<endl;
			Convert(pos_path, neg_path, train_path);

			neg_path = "pointing_neg_test.list";
			pos_path = "pointing_pos_test.list";
			cout<<test_path<<endl;
			Convert(pos_path, neg_path, test_path);
			break;
		case VISUALIZE:
			if(	bp.readWeights() == 1 ){
				bp.visualize();
			}else{
				cout<<"模型数据读入出错\n";
			}
			break;
        default:
            break;
        }
    }
    return 0;
}
Пример #10
0
int main(int argc, const char * argv[]) {
    BP bp;
    bp.push("O rato roeu a rolha");
    bp.push("Era uma vez uma certa personagem");
    bp.push("Para apagar");
    cout << bp << endl;
    bp.eliminar("Para apagar");
    cout << bp << endl;
    bp.eliminar(20);
    cout << bp << endl;
    return 0;
}
void BruteForceOptMatching::checkAmbiguities(const BP& ia,
                                             const FactorGraph& fg,
                                             const ConnectedFactorGraph& graph,
                                             McDArray<int>& ambiguities) {
    for (int h = 0; h < graph.variables.size(); h++) {
        McDArray<int> possibleAssignments;
        getAssignmentsForVariable(graph.variables[h], possibleAssignments);
        Factor belief =
            ia.belief(Var(graph.variables[h], possibleAssignments.size() + 1));

        float maxProb = belief.max();
        int countSame = 0;

        for (int k = 0; k < possibleAssignments.size() + 1; k++) {
            float curProb = belief.get(k);
            if (fabs(curProb - maxProb) < 0.1)
                countSame++;
        }

        /////
        cout << "\n Belief for var " << graph.variables[h] << "\n";
        for (int k = 0; k < possibleAssignments.size() + 1; k++) {
            float curProb = belief.get(k);
            cout << curProb << " ";
        }
        cout << "\n";

        ////

        if (countSame > 1) {
            // oh no! We found an ambiguos assignment!

            ambiguities.append(graph.variables[h]);

            // print it out:
            cout << "Found an ambiguous assignemnt to variable "
                 << graph.variables[h] << "\n";
            for (int k = 0; k < possibleAssignments.size() + 1; k++) {
                float curProb = belief.get(k);
                cout << curProb << " ";
            }
            cout << "\n";
        }
    }
}
Пример #12
0
void
Alifold::
fold(const ALN& aln, const std::vector<Fasta>& fa, const std::string& str, BP& bp) const
{
  const uint L=aln.front().second.size();
  std::string p(str);
  std::replace(p.begin(), p.end(), '.', 'x');
  std::replace(p.begin(), p.end(), '?', '.');

  int bk = Vienna::fold_constrained;
  Vienna::fold_constrained = 1;

  char** seqs = alloc_aln(aln, fa);

  // scaling parameters to avoid overflow
  std::string res(p);
#ifdef HAVE_VIENNA20
  double min_en = Vienna::alifold((const char**)seqs, &res[0]);
#else
  double min_en = Vienna::alifold(seqs, &res[0]);
#endif
  double kT = (Vienna::temperature+273.15)*1.98717/1000.; /* in Kcal */
  Vienna::pf_scale = exp(-(1.07*min_en)/kT/L);
  Vienna::free_alifold_arrays();

  pair_info* pi;
#ifdef HAVE_VIENNA20
  Vienna::alipf_fold((const char**)seqs, &p[0], &pi);
#else
  Vienna::alipf_fold(seqs, &p[0], &pi);
#endif

  bp.resize(L);
  for (uint k=0; pi[k].i!=0; ++k)
    if (pi[k].p>th_)
      bp[pi[k].i-1].push_back(std::make_pair(pi[k].j-1, pi[k].p));

  free(pi);
  Vienna::free_alipf_arrays();
  free_aln(seqs);
  Vienna::fold_constrained = bk;
}
Пример #13
0
/**
 * The specified inference algorithm is run. First, the MLN and evidence files
 * are parsed and the database is filled. All evidence predicates are
 * closed-world by default (this can be changed with the -o option) and all
 * non-evidence predicates (query and hidden predicates) are open-world by
 * default (this can be changed with the -c option, however query atoms are
 * always open-world).
 */
int main(int argc, char* argv[])
{
    ///////////////////////////  read & prepare parameters ///////////////////////
    ARGS::parse(argc, argv, &cout);
    Timer timer;
    double begSec = timer.time();

    Array<Predicate *> queryPreds;
    Array<TruthValue> queryPredValues;

    ofstream resultsOut(aresultsFile);
    if (!resultsOut.good())
    {
        cout << "ERROR: unable to open " << aresultsFile << endl;
        return -1;
    }

    Domain* domain = NULL;
    Inference* inference = NULL;
    if (buildInference(inference, domain, aisQueryEvidence, queryPreds,
                       queryPredValues) > -1)
    {
        //for(int i=0;i<queryPreds.size();i++)
        //{
        //  queryPreds[i]->print(cout,domain);
        // cout<<endl;
        //}
        double initTime, runTime;
        Timer timer1;

        timer1.reset();
        inference->init();
        initTime = timer1.time();

        timer1.reset();

        // No inference, just output network
        if (aoutputNetwork)
        {
            cout << "Writing network to file ..." << endl;
            inference->printNetwork(resultsOut);
        }
        // Perform inference
        else
        {
            if (adecisionInfer)
            {
                BP* bp = dynamic_cast<BP*>(inference);
                if (bp) bp->runDecisionBP();
            }
            else
            {
                inference->infer();
            }

            runTime = timer1.time();
            cout<<"Time-Results: Init "<<initTime<<" Run "<<runTime<<" Total "<<(initTime+runTime)<<endl;


            if (aHybrid)
            {
                printResults(queryFile, queryPredsStr, domain, resultsOut, &queries,
                             inference, inference->getHState());
            }
            else
            {
                if (adecisionInfer)
                {
                    BP* bp = dynamic_cast<BP*>(inference);
                    if (bp) bp->printDecisionResults(resultsOut);
                }
                else
                {
                    printResults(queryFile, queryPredsStr, domain, resultsOut, &queries,
                                 inference, inference->getState());
                }
            }
        }
    }

    resultsOut.close();
    if (domain) delete domain;
    for (int i = 0; i < knownQueries.size(); i++)
        if (knownQueries[i]) delete knownQueries[i];
    if (inference) delete inference;

    cout << "total time taken = ";
    Timer::printTime(cout, timer.time()-begSec);
    cout << endl;
}