Exemplo n.º 1
0
//add rows of data to the table
void WekaData::Append(const realvec& in)
{
  MRSASSERT(in.getRows()==cols_);
  // skip feature vectors labeled with negative labels

  if (in(in.getRows()-1, 0) >=0)
  {
    data_ = new vector<mrs_real>(cols_);
    for(mrs_natural ii=0; ii<in.getRows(); ++ii)
    {
      data_->at(ii) = in(ii, 0);
    }
    Append(data_);
  }

}
mrs_real
QGMMModel::deltaBIC(realvec C1, mrs_natural N1, realvec C2, mrs_natural N2, realvec C, mrs_real lambda)
{
	//matrices should be square and equal sized
	if(C1.getCols() != C2.getCols() && C1.getCols() != C.getCols() &&
		C1.getCols()!= C1.getRows())
	{
		MRSERR("QGMMModel:deltaBIC: matrices should all be squared and equal sized...");
		return MAXREAL; //just a way to sinalize the above error... [!]
	}

	mrs_real res;
	mrs_real N = (mrs_real)(N1 + N2);
	mrs_real d = (mrs_real)C1.getCols();


	res = N * log(C.det());
	res -= (mrs_real)N1 * log(C1.det());
	res -= (mrs_real)N2 * log(C2.det());
	res *= 0.5f;

	res -= 0.5f * lambda * (d + 0.5f*d*(d+1.0f))* log(N);

	return res;
}
Exemplo n.º 3
0
void
PeakClusterSelect::swap(realvec& rv, mrs_natural sample1, mrs_natural sample2, mrs_bool swapColumns)
{
  if( swapColumns ) // swap two columns
  {
    int rows = rv.getRows();
    mrs_real tmp;

    for( int i=0 ; i<rows ; ++i )
    {
      tmp = rv(i, sample1);
      rv(i,sample1) = rv(i,sample2);
      rv(i,sample2) = tmp;
    }
  }
  else // swap two rows
  {
    int cols = rv.getCols();
    mrs_real tmp;

    for( int i=0 ; i<cols ; ++i )
    {
      tmp = rv(sample1,i);
      rv(sample1,i) = rv(sample2,i);
      rv(sample2,i) = tmp;
    }
  }
}
Exemplo n.º 4
0
void Map::myProcess(realvec & in, realvec & out)
{
  {
    MarControlAccessor input_access(m_input_ctl);
    realvec & input_data = input_access.to<realvec>();

    assert(input_data.getRows() == in.getRows() &&
           input_data.getCols() == in.getCols());

    input_data = in;
  }

  const realvec & output_data = m_output_ctl->to<realvec>();

  assert(output_data.getRows() == out.getRows() &&
         output_data.getCols() == out.getCols());

  out = output_data;
}
Exemplo n.º 5
0
void Parallel::myProcess(realvec& in, realvec& out)
{
  mrs_natural t,o;
  mrs_natural inIndex = 0;
  mrs_natural outIndex = 0;
  mrs_natural localIndex = 0;
  unsigned int child_count = marsystems_.size();

  if (child_count == 1)
  {
    marsystems_[0]->process(in, out);
  }
  else if (child_count > 1)
  {
    for (mrs_natural i = 0; i < child_count; ++i)
    {
      localIndex = childInfos_[i].inObservations;
      for (o = 0; o < localIndex; o++)
      {
        // avoid reading unallocated memory
        if ((inIndex + o) < in.getRows()) {
          for (t = 0; t < inSamples_; t++) //lmartins: was t < onSamples [!]
          {
            (*(slices_[2*i]))(o,t) = in(inIndex + o,t);
          }
        } else {
          for (t = 0; t < inSamples_; t++) {
            (*(slices_[2*i]))(o,t) = 0;
          }
        }
      }
      inIndex += localIndex;
      marsystems_[i]->process(*(slices_[2*i]), *(slices_[2*i+1]));
      localIndex = childInfos_[i].onObservations;
      for (o = 0; o < localIndex; o++)
      {
        for (t = 0; t < onSamples_; t++)
        {
          out(outIndex + o,t) = (*(slices_[2*i+1]))(o,t);
        }
      }
      outIndex += localIndex;
    }
  }
  else if(child_count == 0) //composite has no children!
  {
    MRSWARN("Parallel::process: composite has no children MarSystems - passing input to output without changes.");
    out = in;
  }
}
Exemplo n.º 6
0
void
MATLABengine::putVariable(realvec value, mrs_string MATLABname)
{
  //----------------------------------
  // send a realvec to a MATLAB matrix
  //----------------------------------
  mwSize dims[2]; //realvec is 2D
  dims[0] = value.getRows();
  dims[1] = value.getCols();

  //realvec are by default double precision matrices => mxDOUBLE_CLASS
  mxArray *mxMatrix = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL);
  mrs_real *data = value.getData();
  memcpy((void *)mxGetPr(mxMatrix), (void *)(data), dims[0]*dims[1]*mxGetElementSize(mxMatrix));
  engPutVariable(engine_, MATLABname.c_str(), mxMatrix);

  mxDestroyArray(mxMatrix);
}
Exemplo n.º 7
0
void
peakView::fromTable(const realvec& vecTable)
{
  //get data from header
  fs_  = vecTable(0, 1);
  frameSize_ = (mrs_natural)vecTable(0, 2);
  frameMaxNumPeaks_ = (mrs_natural)vecTable(0, 3);
  numFrames_ = (mrs_natural)vecTable(0, 4);

  //get the first frame in table (it may not be 0!!!)
  mrs_natural frame = (mrs_natural)vecTable(1, pkFrame); // start frame [!]

  //resize (and set to zero) vec_ for new peak data
  //(should accommodate empty frames before the first frame in table!)
  vec_.create(frameMaxNumPeaks_*nbPkParameters, numFrames_+frame); //[!]

  mrs_natural p = 0; // peak index inside each frame
  mrs_natural r = 1;//peak index in table (i.e. row index) - ignore header row

  //check in case realvec has less parameters than nbPkParameters
  mrs_natural actualNbPkParams = (mrs_natural)min((mrs_real)nbPkParameters, (mrs_real)vecTable.getCols());

  //iterate over table rows (i.e. peaks) - excluding header row
  while(r < vecTable.getRows()-1)
  {
    //get parameters for this peak
    for(mrs_natural prm = 0; prm < actualNbPkParams; ++prm)
    {
      (*this)(p, pkParameter(prm), frame) = vecTable(r, prm);
    }
    ++r; //move on to next table row (i.e. peak)
    p++;
    //if the next row in table is form a different frame,
    //reset peak index and get new frame index
    if(vecTable(r, pkFrame) != frame)
    {
      frame = (mrs_natural)vecTable(r, pkFrame);
      p = 0;
    }
  }
}
Exemplo n.º 8
0
void PeakConvert2::ComputePeaker (mrs_realvec in, realvec& out)
{
#ifdef ORIGINAL_VERSION
  peaker_->updControl("mrs_real/peakStrength", 0.2);// to be set as a control [!]
#else
  peaker_->updControl("mrs_real/peakStrength",1e-1);
  peaker_->updControl("mrs_real/peakStrengthRelMax" ,1e-2);
  peaker_->updControl("mrs_real/peakStrengthAbs",1e-10 );
  peaker_->updControl("mrs_real/peakStrengthTreshLpParam" ,0.95);
  peaker_->updControl("mrs_real/peakStrengthRelThresh" , 1.);
#endif

  peaker_->updControl("mrs_real/peakSpacing", 2e-3);   // 0
  peaker_->updControl("mrs_natural/peakStart", downFrequency_);   // 0
  peaker_->updControl("mrs_natural/peakEnd", upFrequency_);  // size_
  peaker_->updControl("mrs_natural/inSamples", in.getCols());
  peaker_->updControl("mrs_natural/inObservations", in.getRows());
  peaker_->updControl("mrs_natural/onSamples", out.getCols());
  peaker_->updControl("mrs_natural/onObservations", out.getRows());

  peaker_->process(in, out);
}
Exemplo n.º 9
0
summaryStatistics ClassificationReport::computeSummaryStatistics(const realvec& mat)
{
  MRSASSERT(mat.getCols()==mat.getRows());

  summaryStatistics stats;

  mrs_natural size = mat.getCols();

  vector<mrs_natural>rowSums(size);
  for(int ii=0; ii<size; ++ii) rowSums[ii] = 0;
  vector<mrs_natural>colSums(size);
  for(int ii=0; ii<size; ++ii) colSums[ii] = 0;
  mrs_natural diagonalSum = 0;

  mrs_natural instanceCount = 0;
  for(mrs_natural row=0; row<size; row++)
  {
    for(mrs_natural col=0; col<size; col++)
    {
      mrs_natural num = (mrs_natural)mat(row,col);
      instanceCount += num;

      rowSums[row] += num;
      colSums[col] += num;

      if(row==col)
        diagonalSum += num;
    }
  }
  //printf("row1 sum:%d\n",rowSums[0]);
  //printf("row2 sum:%d\n",rowSums[1]);
  //printf("col1 sum:%d\n",colSums[0]);
  //printf("col2 sum:%d\n",colSums[1]);
  //printf("diagonal sum:%d\n",diagonalSum);
  //printf("instanceCount:%d\n",instanceCount);

  mrs_natural N = instanceCount;
  mrs_natural N2 = (N*N);
  stats.instances = instanceCount;
  stats.correctInstances = diagonalSum;

  mrs_natural sum = 0;
  for(mrs_natural ii=0; ii<size; ++ii)
  {
    sum += (rowSums[ii] * colSums[ii]);
  }
  mrs_real PE = (mrs_real)sum / (mrs_real)N2;
  mrs_real PA = (mrs_real)diagonalSum / (mrs_real)N;
  stats.kappa = (PA - PE) / (1.0 - PE);

  mrs_natural not_diagonal_sum = instanceCount - diagonalSum;
  mrs_real MeanAbsoluteError = (mrs_real)not_diagonal_sum / (mrs_real)instanceCount;
  //printf("MeanAbsoluteError:%f\n",MeanAbsoluteError);
  stats.meanAbsoluteError = MeanAbsoluteError;

  mrs_real RootMeanSquaredError = sqrt(MeanAbsoluteError);
  //printf("RootMeanSquaredError:%f\n",RootMeanSquaredError);
  stats.rootMeanSquaredError = RootMeanSquaredError;

  mrs_real RelativeAbsoluteError = (MeanAbsoluteError / 0.5) * 100.0;
  //printf("RelativeAbsoluteError:%f%%\n",RelativeAbsoluteError);
  stats.relativeAbsoluteError = RelativeAbsoluteError;

  mrs_real RootRelativeSquaredError = (RootMeanSquaredError / (0.5)) * 100.0;
  //printf("RootRelativeSquaredError:%f%%\n",RootRelativeSquaredError);
  stats.rootRelativeSquaredError = RootRelativeSquaredError;

  return stats;
}//computeSummaryStatistics
void 
PeakViewMerge::myProcess(realvec& in, realvec& out)
{
	peakView	*In[kNumMatrices],
				Out (out);
	mrs_natural i, rowIdx = 0,
				numPeaks[kNumMatrices],
				outputIdx	= 0;
	const mrs_bool discNegGroups	= ctrl_noNegativeGroups_->to<mrs_bool>();

	out.setval(0.);
	
	for (i = 0; i < kNumMatrices; i++)
	{
		mrs_natural	numRows		= (i==kMat1)? ctrl_frameMaxNumPeaks1_->to<mrs_natural>() :  ctrl_frameMaxNumPeaks2_->to<mrs_natural>();
		numRows					*= peakView::nbPkParameters;
		if (numRows == 0) // if the controls have not been set assume both matrixes to be of equal size	
			numRows	= in.getRows ()/kNumMatrices;
		peakViewIn_[i].stretch (numRows, in.getCols ());
		in.getSubMatrix (rowIdx, 0, peakViewIn_[i]);
		rowIdx		+= numRows;
		In[i]		= new peakView(peakViewIn_[i]);
		numPeaks[i]	= In[i]->getTotalNumPeaks ();
	}

	if (ctrl_mode_->to<mrs_string>() == "OR")
	{
		// write all entries of the second peakView to output
		for (i = 0; i < numPeaks[1]; i++)
		{
			if (discNegGroups && (*In[1])(i,peakView::pkGroup) < 0)
				continue;
			WriteOutput (Out, In[1], i, outputIdx);
			outputIdx++;
		}

		// write all entries of the first peakView to output except duplicates
		for (i = 0; i < numPeaks[0]; i++)
		{
			mrs_natural Idx;
			if (discNegGroups && (*In[0])(i,peakView::pkGroup) < 0)
				continue;
			for (mrs_natural k = 1; k < kNumMatrices; k++)
				Idx	= FindDuplicate (In[k], (*In[0])(i, peakView::pkFrequency), numPeaks[k]);

			if (Idx < 0)
			{
				WriteOutput (Out, In[0], i, outputIdx);
				outputIdx++;
			}
		}
	}
	else if (ctrl_mode_->to<mrs_string>() == "AND")
	{
		// find duplicates and write only them to output
		for (i = 0; i < numPeaks[0]; i++)
		{
			mrs_natural Idx;
			if (discNegGroups && (*In[0])(i,peakView::pkGroup) < 0)
				continue;
			for (mrs_natural k = 1; k < kNumMatrices; k++)
				Idx	= FindDuplicate (In[k], (*In[0])(i, peakView::pkFrequency), numPeaks[k]);

			if (Idx >= 0)
			{
				if (discNegGroups && (*In[1])(Idx,peakView::pkGroup) < 0)
					continue;
				WriteOutput (Out, In[0], i, outputIdx);
				outputIdx++;
			}
		}
	}
	else if (ctrl_mode_->to<mrs_string>() == "ANDOR")
	{
		// keep the input[0] peaks that are not in input[1]
		for (i = 0; i < numPeaks[0]; i++)
		{
			mrs_natural Idx;
			if (discNegGroups && (*In[0])(i,peakView::pkGroup) < 0)
				continue;
			for (mrs_natural k = 1; k < kNumMatrices; k++)
				Idx	= FindDuplicate (In[k], (*In[0])(i, peakView::pkFrequency), numPeaks[k]);

			if (Idx < 0)
			{
				WriteOutput (Out, In[0], i, outputIdx);
				outputIdx++;
			}
		}
	}
	else if (ctrl_mode_->to<mrs_string>() == "XOR")
	{
		// find duplicates and write only residual to output
		for (i = 0; i < numPeaks[0]; i++)
		{
			if (discNegGroups && (*In[0])(i,peakView::pkGroup) < 0)
				continue;
			mrs_natural Idx	= FindDuplicate (In[1], (*In[0])(i, peakView::pkFrequency), numPeaks[1]);

			if (Idx < 0)
			{
				WriteOutput (Out, In[0], i, outputIdx);
				outputIdx++;
			}
		}
		// find duplicates and write only residual to output
		for (i = 0; i < numPeaks[1]; i++)
		{
			if (discNegGroups && (*In[1])(i,peakView::pkGroup) < 0)
				continue;
			mrs_natural Idx= FindDuplicate (In[0], (*In[1])(i, peakView::pkFrequency), numPeaks[0]);

			if (Idx < 0)
			{
				WriteOutput (Out, In[1], i, outputIdx);
				outputIdx++;
			}
		}
	}
	else 
	{
		MRSERR("PeakViewMerfe::myProcess() : illegal mode string: " << ctrl_mode_->to<mrs_string>());
	}

	for (i = 0; i < kNumMatrices; i++)
	{
		delete In[i];
	}

	ctrl_totalNumPeaks_->setValue(outputIdx);
}
Exemplo n.º 11
0
void
Filter::myProcess(realvec& in, realvec& out)
{
  //checkFlow(in,out);

  mrs_natural i,j,c;
  mrs_natural size = in.getCols();
  mrs_natural stateSize = state_.getCols();
  mrs_natural channels = in.getRows();

  mrs_real gain = getctrl("mrs_real/fgain")->to<mrs_real>();

  // State array holds the various delays for the difference equation
  // of the filter. Similar implementation as described in the manual
  // for MATLAB Signal Processing Toolbox. State corresponds to
  // the z, num_coefs to the b and denom_coefs to the a vector respectively
  // in_window is the input x(n) and out_window is the output y(n)

  //dcoeffs_/=10;


  // state_.setval(0);
  if (norder_ == dorder_) {
    for (c = 0; c < channels; ++c) {
      for (i = 0; i < size; ++i) {
        out(c,i) = ncoeffs_(0) * in(c,i) + state_(c,0);
        for (j = 0; j < stateSize - 1; j++)
        {
          state_(c,j) = ncoeffs_(j+1) * in(c,i) + state_(c,j+1) - dcoeffs_(j+1) * out(c,i);
        }
        state_(c,stateSize - 1) = ncoeffs_(order_-1) * in(c,i) - dcoeffs_(order_-1) * out(c,i);
      }
    }
  }
  else if (norder_ < dorder_) {
    for (c = 0; c < channels; ++c) {
      for (i = 0; i < size; ++i) {
        out(c,i) = ncoeffs_(0) * in(c,i) + state_(c,0);
        for (j = 0; j < norder_ - 1; j++)
        {
          state_(c,j) = ncoeffs_(j+1) * in(c,i) + state_(c,j+1) - dcoeffs_(j+1) * out(c,i);
        }
        for (j = norder_ - 1; j < stateSize - 1; j++)
        {
          state_(c,j) = state_(c,j+1) - dcoeffs_(j+1) * out(c,i);
        }
        state_(c,stateSize - 1) = -dcoeffs_(order_ - 1) * out(c,i);
      }
    }
  }
  else {
    for (c = 0; c < channels; ++c) {
      for (i = 0; i < size; ++i) {
        out(c,i) = ncoeffs_(0) * in(c,i) + state_(c,0);
        for (j = 0; j < dorder_ - 1; j++)
        {
          state_(c,j) = ncoeffs_(j+1) * in(c,i) + state_(c,j+1) - dcoeffs_(j+1) * out(c,i);
        }
        for (j = dorder_ - 1; j < stateSize - 1; j++)
        {
          state_(c,j) = ncoeffs_(j+1) * in(c,i) + state_(c,j+1);
        }
        state_(c,stateSize - 1) = ncoeffs_(order_-1) * in(c,i);
      }
    }
  }
  out *= gain;


  //		MATLAB_PUT(in, "Filter_in");
  //	 	MATLAB_PUT(out, "Filter_out");
  //	 	MATLAB_PUT(ncoeffs_, "ncoeffs_");
  //	 	MATLAB_PUT(dcoeffs_, "dcoeffs_");
  //	 	MATLAB_EVAL("MAT_out = filter(ncoeffs_, dcoeffs_, Filter_in)");
  //
  //	 	MATLAB_EVAL("spec_in = abs(fft(Filter_in));");
  //	 	MATLAB_EVAL("spec_out = abs(fft(Filter_out));");
  //	 	MATLAB_EVAL("spec_mat = abs(fft(MAT_out));");
  //
  //	 	MATLAB_EVAL("subplot(2,1,1);plot(Filter_in);hold on; plot(Filter_out, 'r'); plot(MAT_out, 'g');hold off");
  //	 	MATLAB_EVAL("subplot(2,1,2);plot(spec_in(1:end/2));hold on; plot(spec_out(1:end/2),'r');plot(spec_mat(1:end/2),'g');hold off;");
  //	 	MATLAB_EVAL("h = abs(fft([1 -.97], length(Filter_in)));");
  //	 	MATLAB_EVAL("hold on; plot(h(1:end/2), 'k'); hold off");
  //		//MATLAB_GET("MAT_out", out)
  //
}
Exemplo n.º 12
0
void
SelfSimilarityMatrix::myProcess(realvec& in, realvec& out)
{
    if(this->getctrl("mrs_natural/mode")->to<mrs_natural>() ==  SelfSimilarityMatrix::outputDistanceMatrix)
    {
        //check if there are any elements to process at the input
        //(in some cases, they may not exist!) - otherwise, do nothing
        //(i.e. output will be zeroed out)
        if(inSamples_ > 0)
        {
            unsigned int child_count = marsystems_.size();
            if(child_count == 1)
            {
                mrs_natural nfeats = in.getRows();

                //normalize input features if necessary
                if(ctrl_normalize_->to<mrs_string>() == "MinMax")
                    in.normObsMinMax(); // (x - min)/(max - min)
                else if(ctrl_normalize_->to<mrs_string>() == "MeanStd")
                    in.normObs(); // (x - mean)/std

                //calculate the Covariance Matrix from the input, if defined
                if(ctrl_calcCovMatrix_->to<mrs_natural>() & SelfSimilarityMatrix::fixedStdDev)
                {
                    //fill covMatrix diagonal with fixed value (remaining values are zero)
                    MarControlAccessor acc(ctrl_covMatrix_);
                    realvec& covMatrix = acc.to<mrs_realvec>();
                    covMatrix.create(inObservations_, inObservations_);
                    mrs_real var = ctrl_stdDev_->to<mrs_real>();
                    var *= var;
                    for(mrs_natural i=0; i< inObservations_; ++i)
                    {
                        covMatrix(i,i) = var;
                    }
                }
                else if(ctrl_calcCovMatrix_->to<mrs_natural>() & SelfSimilarityMatrix::diagCovMatrix)
                {
                    in.varObs(vars_); //FASTER -> only get the vars for each feature
                    mrs_natural dim = vars_.getSize();
                    //fill covMatrix diagonal with var values (remaining values are zero)
                    MarControlAccessor acc(ctrl_covMatrix_);
                    realvec& covMatrix = acc.to<mrs_realvec>();
                    covMatrix.create(dim, dim);
                    for(mrs_natural i=0; i< dim; ++i)
                    {
                        covMatrix(i,i) = vars_(i);
                    }
                }
                else if(ctrl_calcCovMatrix_->to<mrs_natural>() & SelfSimilarityMatrix::fullCovMatrix)
                {
                    MarControlAccessor acc(ctrl_covMatrix_);
                    realvec& covMatrix = acc.to<mrs_realvec>();
                    in.covariance(covMatrix); //SLOWER -> estimate the full cov matrix
                }
                else if(ctrl_calcCovMatrix_->to<mrs_natural>() == SelfSimilarityMatrix::noCovMatrix)
                {
                    ctrl_covMatrix_->setValue(realvec());
                }

                for(mrs_natural i=0; i < in.getCols(); ++i)
                {
                    in.getCol(i, i_featVec_);
                    for(mrs_natural j=0; j <= i; ++j)
                    {
                        in.getCol(j, j_featVec_);

                        //stack i and j feat vecs
                        for(mrs_natural r=0; r < nfeats; ++r)
                        {
                            stackedFeatVecs_(r, 0) = i_featVec_(r);
                            stackedFeatVecs_(r+nfeats, 0) = j_featVec_(r);
                        }
                        //do the metric calculation for these two feat vectors
                        //and store it in the similarity matrix (which is symmetric)
                        marsystems_[0]->process(stackedFeatVecs_, metricResult_);
                        out(i,j) = metricResult_(0,0);
                        //metric should be symmetric!
                        out(j, i) = out(i, j);
                    }
                }
            }
            else
            {
                out.setval(0.0);
                if(child_count == 0)
                {
                    MRSWARN("SelfSimilarityMatrix::myProcess - no Child Metric MarSystem added - outputting zero similarity matrix!");
                }
                else
                {
                    MRSWARN("SelfSimilarityMatrix::myProcess - more than one Child MarSystem exists (i.e. invalid metric) - outputting zero similarity matrix!");
                }
            }
        }

        //MATLAB_PUT(out, "simMatrix");
        //MATLAB_EVAL("figure(1);imagesc(simMatrix);");

        //MATLAB_PUT(out, "simMat");
        //MATLAB_EVAL(name_+"=["+name_+",simMat(:)'];");
    }
    else if(this->getctrl("mrs_natural/mode")->to<mrs_natural>() ==  SelfSimilarityMatrix::outputPairDistance)
    {
        if(inSamples_ == 2) //we always need two column vector instances at input
        {
            unsigned int child_count = marsystems_.size();
            if(child_count == 1)
            {
                MarControlAccessor acc(ctrl_instanceIndexes_);
                realvec& instIdxs = acc.to<mrs_realvec>();
                mrs_natural i = mrs_natural(instIdxs(0));
                mrs_natural j = mrs_natural(instIdxs(1));

                //check for out of bound indexes (which could have been set
                //by someone outside changing the value of the ctrl_instanceIndexes control)
                mrs_natural nInstances = ctrl_nInstances_->to<mrs_natural>();
                if(i >= nInstances || j >= nInstances)
                    ctrl_done_->setValue(true);


                if(!ctrl_done_->isTrue())
                {
                    mrs_natural nfeats = in.getRows();

                    //COMPUTE DISTANCE between the two column vector at input
                    in.getCol(0, i_featVec_);
                    in.getCol(1, j_featVec_);

                    //stack i and j feat vecs
                    for(mrs_natural r=0; r < nfeats; ++r)
                    {
                        stackedFeatVecs_(r, 0) = i_featVec_(r);
                        stackedFeatVecs_(r+nfeats, 0) = j_featVec_(r);
                    }

                    //do the metric calculation for these two feat vectors
                    //and send it to the output
                    marsystems_[0]->process(stackedFeatVecs_, out);
                    //out(0) = metricResult_(0,0);
                }
                else
                {
                    //Self Similarity has completed all pair-wise similarity computations
                    //so, it will just send zero valued values and a warning
                    out(0) = 0.0;
                    MRSWARN("SelfSimilarityMatrix::myProcess - no more pairwise similarity computations to be performed - outputting zero similarity value!")
                }

                //Select indexes for next pair of instances for distance computation
                //Similarity matrix is tringular simetric, so we should just compute
                //half of it (including diagonal). These indexes are to be used by some
                //source MarSystem that has a control linked to ctrl_instanceIndexes (e.g. WekaSource)
                if (i < j)
                    ++i;
                else
                {
                    ++j;
                    i = 0;
                }
                if (j >= nInstances)
                {
                    ctrl_done_->setValue(true);
                    j = -1; //used to signal that there are no more instance pairs to compute
                    i = -1; //used to signal that there are no more instance pairs to compute
                }
                else
                    ctrl_done_->setValue(false);

                //set indexes into the ctrl_instanceIndexes_ control
                instIdxs(0) = i;
                instIdxs(1) = j;
            }
            else
            {
Exemplo n.º 13
0
void 
OneRClassifier::myProcess(realvec& in, realvec& out)
{
  cout << "OneRClassifier::myProcess" << endl;
  cout << "in.getCols() = " << in.getCols() << endl;
  cout << "in.getRows() = " << in.getRows() << endl;
  //get the current mode, either train of predict mode
  bool trainMode = (getctrl("mrs_string/mode")->to<mrs_string>() == "train");
  row_.stretch(in.getRows());
  if (trainMode)
    {
      if(lastModePredict_ || instances_.getCols()<=0)
	{
	  mrs_natural nAttributes = getctrl("mrs_natural/inObservations")->to<mrs_natural>();
	  cout << "nAttributes = " << nAttributes << endl;
	  instances_.Create(nAttributes);
	}
      
      lastModePredict_ = false;
      
      //get the incoming data and append it to the data table
      for (mrs_natural ii=0; ii< inSamples_; ++ii)
	{
	  mrs_real label = in(inObservations_-1, ii);
	  instances_.Append(in);
	  out(0,ii) = label;
	  out(1,ii) = label;
	}//for t
    }//if
  else
    {//predict mode

	  cout << "OneRClassifier::predict" << endl;
	  if(!lastModePredict_)
	    {
	      //get the number of class labels and build the classifier
	      mrs_natural nAttributes = getctrl("mrs_natural/inObservations")->to<mrs_natural>();
	      cout << "BUILD nAttributes = " << nAttributes << endl;
	      Build(nAttributes);
	    }//if
	  lastModePredict_ = true;
	  cout << "After lastModePredict" << endl;


      //foreach row of predict data, extract the actual class, then call the
      //classifier predict method. Output the actual and predicted classes.
      for (mrs_natural ii=0; ii<inSamples_; ++ii)
	{
	  //extract the actual class
	  mrs_natural label = (mrs_natural)in(inObservations_-1, ii);
	      
	  //invoke the classifier predict method to predict the class
	  in.getCol(ii,row_);
	  mrs_natural prediction = Predict(row_);
	  cout << "PREDICTION = " << prediction << endl;
	  cout << "row_ " << row_ << endl;

	  //and output actual/predicted classes
	  out(0,ii) = (mrs_real)prediction;
	  out(1,ii) = (mrs_real)label;
	}//for t
    }//if
	
}//myProcess
Exemplo n.º 14
0
void 
SOM::myProcess(realvec& in, realvec& out)
{
	mrs_string mode = getctrl("mrs_string/mode")->to<mrs_string>();

	mrs_natural o,t;
	mrs_real geom_dist;
	mrs_real geom_dist_gauss;
  
	int px;
	int py;

	MarControlAccessor acc_grid(ctrl_gridmap_);
	realvec& grid_map = acc_grid.to<mrs_realvec>();  


	if (mode == "train")  
	{
		
		mrs_real dx;
		mrs_real dy;
		mrs_real adj;

		for (t=0; t < inSamples_; t++) 
		{

			
			px = (int) in(inObservations_-2, t);
			py = (int) in(inObservations_-1, t);


			
			if ((px == -1.0)&&(px == -1.0))
			{
				find_grid_location(in, t);
				px = (int) grid_pos_(0);
				py = (int) grid_pos_(1);				
			}
			out(0,t) = px;
			out(1,t) = py;
			out(2,t) = in(inObservations_-3,t);	  
			
			for (int x=0; x < grid_width_; x++) 
				for (int y=0; y < grid_height_; y++)
				{
					dx = px-x;
					dy = py-y;
					geom_dist = sqrt((double)(dx*dx + dy*dy));
					geom_dist_gauss = gaussian( geom_dist, 0.0, neigh_std_, false);
					
					// subtract map vector from training data vector 
					adj = alpha_ * geom_dist_gauss;
					for (o=0; o < inObservations_-3; o++) 
					{
						adjustments_(o) = in(o,t) - grid_map(x * grid_height_ + y, o);
						adjustments_(o) *= adj;
						grid_map(x * grid_height_ + y, o) += adjustments_(o);
					}
				}
		}
		
		alpha_ *= getctrl("mrs_real/alpha_decay_train")->to<mrs_real>();
		neigh_std_ *= getctrl("mrs_real/neighbourhood_decay_train")->to<mrs_real>();	  

		

	}
	if (mode == "init")
	{
		mrs_real dx;
		mrs_real dy;
		mrs_real adj;

		mrs_real std_ = getctrl("mrs_real/std_factor_init")->to<mrs_real>();
		neigh_std_ = ((0.5*(grid_width_+grid_height_)) * std_);

		for (t=0; t < inSamples_; t++) 
		{
			// no need to find grid locations, just read from the file
			px = (int) in( in.getRows() - 2, t);
			py = (int) in( in.getRows() - 1, t);
			for(int i =0; i < inObservations_ - 3; ++i)
			{
				grid_map(px * grid_height_ + py, i) = in(i);
			}	

			for (int x=0; x < grid_width_; x++) 
				for (int y=0; y < grid_height_; y++)
				{
					dx = px-x;
					dy = py-y;
					geom_dist = sqrt((double)(dx*dx + dy*dy));
					geom_dist_gauss = gaussian( geom_dist, 0.0, neigh_std_, false);

					// subtract map vector from training data vector 
					adj = alpha_ * geom_dist_gauss;
					for (o=0; o < inObservations_-3; o++) 
					{
						adjustments_(o) = in(o,t) - grid_map(x * grid_height_ + y, o);
						adjustments_(o) *= adj;
						grid_map(x * grid_height_ + y, o) += adjustments_(o);
					}
					
				}
				
		
		}
		//WARNING: UGLY HACK
		// Last two rows of init features are x,y locations 
		// so we want to set all the coresponding rows in the SOM to 0
		// to prevent randomness from creaping in.
		for (int x=0; x < grid_width_; x++) 
		{
			for (int y=0; y < grid_height_; y++)
			{
					grid_map(x * grid_height_ + y, grid_map.getCols() - 2) = 0;
					grid_map(x * grid_height_ + y, grid_map.getCols() - 1) = 0;
					cout << "x: " << x << " y: " << y << endl;
			}
		}
		alpha_ *= getctrl("mrs_real/alpha_decay_init")->to<mrs_real>();
		neigh_std_ *= getctrl("mrs_real/neighbourhood_decay_init")->to<mrs_real>();	  	

	}
	if (mode == "predict")
	{
		for (t=0; t < inSamples_; t++) 
		{
			find_grid_location(in, t);
			px = (int) grid_pos_(0);
			py = (int) grid_pos_(1);

			

			out(0,t) = px;
			out(1,t) = py;
			out(2,t) = in(inObservations_-3,t);	  
		}
	}
	
	

  
  
}
Exemplo n.º 15
0
void
SimilarityMatrix::myProcess(realvec& in, realvec& out)
{
  //check if there are any elements to process at the input
  //(in some cases, they may not exist!) - otherwise, do nothing
  //(i.e. output is also an empty vector)
  mrs_natural i, j, k, l;

  if(inSamples_ > 0)
  {
    child_count_t child_count = marsystems_.size();
    if(child_count == 1)
    {
      mrs_natural nfeats = in.getRows()/sizes_.getSize();

      // calculate hte Covariance Matrix from the input, if defined
      mrs_natural obs = 0;
      for(i=0; i<sizes_.getSize(); ++i)
      {
        for(j=0; j<sizes_(i); j++)
        {
          for(k=0; (mrs_natural)k<invecs_[i].getRows(); k++)
          {
            invecs_[i](k, j) = in(k+obs, j);
          }
        }
        obs += invecs_[i].getRows();
      }

      // normalize input features if necessary
      if(ctrl_normalize_->to<mrs_string>() == "MinMax")
        for(i=0; i<sizes_.getSize(); ++i)
        {
          invecs_[i].normObsMinMax(); // (x - min)/(max - min)
        }
      else if(ctrl_normalize_->to<mrs_string>() == "MeanStd")
        for(i=0; i<sizes_.getSize(); ++i)
        {
          invecs_[i].normObs();  // (x - mean)/std
        }

      if(ctrl_calcCovMatrix_->to<mrs_natural>() & SimilarityMatrix::fixedStdDev)
      {
        MarControlAccessor acc(ctrl_covMatrix_);
        realvec& covMatrix = acc.to<mrs_realvec>();
        covMatrix.create(inObservations_/sizes_.getSize(), inObservations_/sizes_.getSize());
        mrs_real var = ctrl_stdDev_->to<mrs_real>();
        var *= var;
        for(i=0; i< inObservations_/sizes_.getSize(); ++i)
        {
          covMatrix(i,i) = var;
        }
      }
      else if(ctrl_calcCovMatrix_->to<mrs_natural>() & SimilarityMatrix::diagCovMatrix)
      {
        invecs_[0].varObs(vars_); // Faster
        mrs_natural dim = vars_.getSize();
        // fill covMatrix diagonal with var values (remaining values are zero)
        MarControlAccessor acc(ctrl_covMatrix_);
        realvec& covMatrix = acc.to<mrs_realvec>();
        covMatrix.create(dim, dim);
        for(i=0; i<(mrs_natural)dim; ++i)
        {
          covMatrix(i,i) = vars_(i);
        }
      }
      else if(ctrl_calcCovMatrix_->to<mrs_natural>() & SimilarityMatrix::fullCovMatrix)
      {
        MarControlAccessor acc(ctrl_covMatrix_);
        realvec& covMatrix = acc.to<mrs_realvec>();
        invecs_[0].covariance(covMatrix); // Slower
      }
      else if(ctrl_calcCovMatrix_->to<mrs_natural>() & SimilarityMatrix::noCovMatrix)
      {
        ctrl_covMatrix_->setValue(realvec());
      }

      for(i=0; i<sizes_(0); ++i)
      {
        obs = 0;
        invecs_[0].getCol(i, i_featVec_);
        for(l=0; l<(mrs_natural)nfeats; l++)
        {
          stackedFeatVecs_(l,0) = i_featVec_(l);
        }
        for(j=1; j<sizes_.getSize(); j++)
        {
          for(k=0; k<sizes_(j); k++)
          {
            invecs_[j].getCol(k, j_featVec_);
            // stack i and j feat vectors
            for(l=0; l<(mrs_natural)nfeats; l++)
            {
              stackedFeatVecs_(l+nfeats,0) = j_featVec_(l);
            }
            marsystems_[0]->process(stackedFeatVecs_, metricResult_);
            out(k+obs,i) = metricResult_(0,0);
          }
          obs += (mrs_natural)sizes_(j);
        }
      }
    }
    else
    {
      out.setval(0.0);
      if(child_count == 0)
      {
        MRSWARN("SimilarityMatrix::myProcess - no Child Metric MarSystem added - outputting zero similarity matrix!");
      }
      else
      {
        MRSWARN("SimilarityMatrix::myProcess - more than one Child MarSystem exists (i.e. invalid metric) - outputting zero similarity matrix!");
      }
    }
  }
  //MATLAB_PUT(out, "simMat");
  //MATLAB_EVAL(name_+"=["+name_+",simMat(:)'];");
}