Ejemplo n.º 1
0
void model_parameters::userfunction(void)
{
  nll=0.0;
  dvariable a2=a1+cutoff*(b1-b2);
  dvar_vector predicted(1,T);
  for(int i=1; i<=T; ++i){
    if(years(i)<cutoff){
      predicted(i)=a1+b1*years(i); 
    }
    if(years(i)>=cutoff){
      predicted(i)=a2+b2*years(i); 
    }
  }
  nll-=-log(sqrt(2.0*M_PI))-log(sdobs)-0.5*sum(square((lnssb-predicted)/sdobs));
}
Ejemplo n.º 2
0
TrainingExample::TrainingExample() {
	ANNIO inputed(0);
	ANNIO expected(0);
	ANNIO predicted(0);

	this->inputed = inputed;
	this->expected = expected;
	this->predicted = predicted;
}
Ejemplo n.º 3
0
// As arguments, takes the cell test set (reversed, so it's phenes - genes instead of genes - phenes)
// and the specific phenotype ID.
gdistmap oracle::find_cell_test_predictions_by_phenotype(const pgtable& rev_cell_test_set, phene_id_t p) const {

    // Variable to return.
    gdistmap predicted(rev_cell_test_set.size());

    // Iterate through the cells in the test set.
    for (pgtable::const_iterator i = rev_cell_test_set.lower_bound(p); i != rev_cell_test_set.upper_bound(p); ++i)
        predicted[i->second] = (*dest)(i->second, p);

    return predicted;
}
Ejemplo n.º 4
0
gdistmap oracle::find_row_test_predictions_by_phenotype(phene_id_t p, size_t genes_size) const {

    // Variable to return.
    gdistmap predicted(genes_size);

    // Iterate down the rows (we're within a column iteration)
    for (gset::const_iterator i = row_test_set.begin(); i != row_test_set.end(); ++i)
        predicted[*i] = (*dest)(*i,p);

    return predicted;
}
Ejemplo n.º 5
0
gdistmap oracle::find_predictions_by_phenotype(phene_id_t p, const gvector& genes) const {

    // Variable to return.
    gdistmap predicted(genes.size());

    // Iterate down the rows (we're within a column iteration)
    for (gvector::const_iterator i = genes.begin(); i != genes.end(); ++i)
        predicted[*i] = (*dest)(*i,p);

    return predicted;
}
void MLP::test()
{
	Mat response(1, 7, CV_32FC1);
	Mat predicted(MLP::network->getInput().cols, 7, CV_32F);
	//cout << MLP::network->getInput().cols;
	//MLP::network->getInput().convertTo(MLP::network->getInput(),CV_32FC1);
	MLP::ann.predict(MLP::network->getInput().col(0).t(),response);

	MLP::network->setOutput(response.t());
	


}
int main(int argc, char **argv[])
{
	string name;
	vector<Mat>Images(100), TestImages(50);
	vector<Mat> Descriptor(100), TestDescriptor(50), TestPcafeature(50);
	vector<vector<KeyPoint>>Keypoints(100), TestKeypoint(50);
	Mat histogram = Mat::zeros(100, Cluster, CV_32F);
	Mat Testhistogram = Mat::zeros(50, Cluster, CV_32F);
	Mat Keyword = Mat::zeros(Cluster, 20, CV_32F);
	Mat full_Descriptor, Pcafeature, Pcaduplicate, clusteridx, trainlabels(100, 1, CV_32F);
	vector<vector<DMatch>> matches(50);
	Mat predicted(Testhistogram.rows, 1, CV_32F);

	// Read Training Images.
	read_train(Images, name);

	//Calculate SIFT features for the Training Images.
	calculate_SIFT(Images,Keypoints,Descriptor);
	merge_descriptor(full_Descriptor,Descriptor);

	//Compute PCA for all the features across all Images.
	PCA pca;
	perform_PCA(full_Descriptor, Pcafeature, pca);
	
	//Perform K-Means on all the PCA reduced features.
	Pcafeature.convertTo(Pcaduplicate, CV_32F);
	calculate_Kmeans(Pcaduplicate, clusteridx);

	//Calculate the Keywords in the Feature Space.
	make_dictionary(clusteridx, Pcaduplicate, Keyword);

	//Get the Histogram for each Training Image.
	hist(Descriptor, clusteridx, histogram);

	//Read Test Image
	read_test(TestImages, name);

	//Calculate the SIFT feature for all the test Images.
	calculate_SIFT(TestImages, TestKeypoint, TestDescriptor);

	//Project the SIFT feature of each feature on the lower dimensional PCA plane calculated above. 
	pca_testProject(TestDescriptor, TestPcafeature, pca);

	//Find the Label by searching for keywords closest to current feature.
	get_matches(TestPcafeature,Keyword,matches);

	//Calculate Histogram for each test Image.
	hist_test(TestDescriptor, matches, Testhistogram);
	
	//Perform classification through Knn Classifier. 
	train_labels(trainlabels);
	KNearest knn;
	train_classifier(histogram, trainlabels, knn);
	test_classify(Testhistogram,predicted,knn);

	//Calculate Accuracy for each class.
	calculate_accuracy(predicted);
	
	getchar();
	return 0;
}
double KernelEstimationInterpolator::_estimateError(unsigned int index) const
{
  const DataFrame& df = *_df;

  vector<double> predicted(_depColumns.size(), 0.0);
  const vector<double>& uut = df.getDataVector(index);
  vector<double> simplePoint(_indColumns.size());
  for (size_t i = 0; i < _indColumns.size(); i++)
  {
    simplePoint[i] = uut[_indColumns[i]];
  }


  double n0 = Normal::normal(0, _sigma);

  KnnIteratorNd it(_getIndex(), simplePoint);
  double wSum = 0.0;
  while (it.next() && it.getDistance() < _sigma * 3.0)
  {
    size_t i = it.getId();
    if (i == index)
    {
      continue;
    }
    const vector<double>& record = df.getDataVector(i);

    // figure out the distance between point and this data vector
    double d = 0;
    for (size_t j = 0; j < _indColumns.size(); j++)
    {
      double v = uut[_indColumns[j]] - record[_indColumns[j]];
      d += v * v;
    }
    d = sqrt(d);
    if (d / _sigma < 3.0)
    {
      // calculate the weight of this sample.
      double w = Normal::normal(d, _sigma) / n0;
      wSum += w;

      assert(w <= 1.000001);

      // calculate the contribution to the predicted value.
      for (size_t j = 0; j < predicted.size(); j++)
      {
        predicted[j] += (record[_depColumns[j]] * w);
      }
    }
  }
  // do less rubber sheeting as we get far away from tie points.
  wSum = std::max(wSum, n0);

  double result = 0.0;
  for (size_t j = 0; j < predicted.size(); j++)
  {
    //cout << "uut[_depColumns[" << j << "]] " << uut[_depColumns[j]] << endl;
    //cout << "predicted[" << j << "] " << predicted[j] << endl;
    double diff = uut[_depColumns[j]] - (predicted[j] / wSum);
    result += diff * diff;
  }
  result = sqrt(result);

  //cout << "wSum: " << wSum << " result: " << result << endl;

  return result;
}
Ejemplo n.º 9
0
RcppExport SEXP correctCafie(
  SEXP measured_in,
  SEXP flowOrder_in,
  SEXP keyFlow_in,
  SEXP nKeyFlow_in,
  SEXP cafEst_in,
  SEXP ieEst_in,
  SEXP droopEst_in
) {

    SEXP rl = R_NilValue; 		// Use this when there is nothing to be returned.
    char *exceptionMesg = NULL;

    try {
	// First do some annoying but necessary type casting on the input parameters.
	// measured & nFlow
	RcppMatrix<double> measured_temp(measured_in);
	int nWell = measured_temp.rows();
	int nFlow = measured_temp.cols();
	// flowOrder
	RcppStringVector  flowOrder_temp(flowOrder_in);
	char *flowOrder = strdup(flowOrder_temp(0).c_str());
	int flowOrderLen = strlen(flowOrder);
	// keyFlow
	RcppVector<int> keyFlow_temp(keyFlow_in);
	int *keyFlow = new int[keyFlow_temp.size()];
	for(int i=0; i<keyFlow_temp.size(); i++) {
	  keyFlow[i] = keyFlow_temp(i);
	}
	// nKeyFlow
	RcppVector<int> nKeyFlow_temp(nKeyFlow_in);
	int nKeyFlow = nKeyFlow_temp(0);
	// cafEst, ieEst, droopEst
	RcppVector<double> cafEst_temp(cafEst_in);
	double cafEst = cafEst_temp(0);
	RcppVector<double> ieEst_temp(ieEst_in);
	double ieEst = ieEst_temp(0);
	RcppVector<double> droopEst_temp(droopEst_in);
	double droopEst = droopEst_temp(0);
 
	if(flowOrderLen != nFlow) {
	    exceptionMesg = copyMessageToR("Flow order and signal should be of same length");
	} else if(nKeyFlow <= 0) {
	    exceptionMesg = copyMessageToR("keyFlow must have length > 0");
	} else {
	    double *measured = new double[nFlow];
	    RcppMatrix<double> predicted(nWell,nFlow);
	    RcppMatrix<double> corrected(nWell,nFlow);
	    CafieSolver solver;
	    solver.SetFlowOrder(flowOrder);
	    solver.SetCAFIE(cafEst, ieEst);
	    for(int well=0; well < nWell; well++) {
		// Set up the input signal for the well
		for(int flow=0; flow<nFlow; flow++) {
		    measured[flow] = measured_temp(well,flow);
		}

		// Initialize the sovler object and find the best CAFIE
		solver.SetMeasured(nFlow, measured);
	        solver.Normalize(keyFlow, nKeyFlow, droopEst, false);
		solver.Solve(3, true);

		// Store the predicted & corrected signals
		for(int flow=0; flow<nFlow; flow++) {
		    predicted(well,flow) = solver.GetPredictedResult(flow);
		    corrected(well,flow) = solver.GetCorrectedResult(flow);
		}
		// Store the estimated sequence
		//const double *normalized_ptr = solver.GetMeasured();
	        //const char *seqEstimate_ptr = solver.GetSequence();
	        //int seqEstimateLen = strlen(seqEstimate_ptr);
	    }

	    // Build result set to be returned as a list to R.
	    RcppResultSet rs;
	    rs.add("predicted",  predicted);
	    rs.add("corrected",  corrected);

	    // Get the list to be returned to R.
	    rl = rs.getReturnList();

	    delete [] measured;
	}

    free(flowOrder);
	delete [] keyFlow;

    } catch(std::exception& ex) {
	exceptionMesg = copyMessageToR(ex.what());
    } catch(...) {
	exceptionMesg = copyMessageToR("unknown reason");
    }
    
    if(exceptionMesg != NULL)
	Rf_error(exceptionMesg);

    return rl;
}
Ejemplo n.º 10
0
void MainWindow::test(QString fichier){

    if(data == NULL)
        data = new MLData();

    bool erreur = false;
    QString texte = ui->txt_sep->text();
    texte.toInt(&erreur);

    if(texte.length() == 0 || erreur || texte.at(0) == '.'){
        QMessageBox* msg = new QMessageBox();
        msg->setText("Separateur incorrect, ne doit pas etre un nombre, ni le caractere '.' .");
        msg->setIcon(QMessageBox::Warning);
        msg->setModal(true);
        msg->exec();
        return;
    }
    data->set_delimiter(',');

    data->read_csv(fichier);

    if(ui->check_lastcol->checkState() == Qt::Checked){
        data->set_response_idx(data->get_values()->cols -1);
    }
    else{
        if(ui->spin_col->text().toInt() > data->get_values()->cols || ui->spin_col->text().toInt() == 0){
            QMessageBox* msg = new QMessageBox();
            msg->setText("La colonne specifiee n'existe pas ! Danse ce fichier les colonnes vont de 1 a " + QString::number(data->get_values()->cols) + " ! " );
            msg->setIcon(QMessageBox::Warning);
            msg->setModal(true);
            msg->exec();
            return;
        }
        data->set_response_idx(ui->spin_col->text().toInt() - 1);
    }
    //data->set_response_idx(data->get_values()->cols -1);

    struct TrainTestSplit spl(100, true);

    data->set_train_test_split(&spl);

    std::cout << "--- TRAIN SAMPLE --- " << std::endl;
    std::cout << "rows x cols = " << (data->get_train_sample_idx())->rows << " x " << (data->get_train_sample_idx())->cols << "\n" << std::endl;
    //std::cout << *(data->get_train_sample_idx()) << std::endl;

    std::cout << "--- TEST SAMPLE --- " << std::endl;
    std::cout << "rows x cols = " << (data->get_test_sample_idx())->rows << " x " << (data->get_test_sample_idx())->cols << std::endl;
    std::cout << *(data->get_test_sample_idx()) << std::endl;
    std::cout << "Variables idx : " << *(data->get_var_idx()) << std::endl;

    //Intialisation
    const cv::Mat* samples = data->get_values(); // samples
    const cv::Mat* responses = data->get_responses();
    const cv::Mat* train_sample = data->get_train_sample_idx();
    const cv::Mat* test_sample = data->get_test_sample_idx();
    const cv::Mat* vars = data->get_var_idx();

    //Classifier params
    /* CvSVMParams params;
    params.svm_type    = CvSVM::C_SVC;
    params.kernel_type = CvSVM::LINEAR;
    params.term_crit   = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
    */

    //Classifier
    /* CvSVM svm; */


    std::cerr << "[DEBUG] Avant term_crit" << std::endl;

    //Training
    if (svm_params == NULL) {
        std::cerr << "[DEBUG] svm_params == NULL" << std::endl;
    }

    svm_params->term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);

    std::cerr << "[DEBUG] Après term_crit" << std::endl;

    svm_classifier->train(*samples,*responses,*vars,*train_sample,*svm_params);

    std::cerr << "[DEBUG] Après Train" << std::endl;

    cv::Mat predicted(test_sample->rows,1,CV_32FC1);
    for(int i=0;i<predicted.rows;i++){
        cv::Mat sample = samples->row(test_sample->at<int>(i,0));
        predicted.at<float>(i,0) = svm_classifier->predict(sample);
    }

    std::cout << "Predictions : " << predicted << std::endl;

}