Java Code Examples for weka.core.matrix.Matrix#set()

The following examples show how to use weka.core.matrix.Matrix#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GaussianProcesses.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Classifies a given instance.
 * 
 * @param inst
 *            the instance to be classified
 * @return the classification
 * @throws Exception
 *             if instance could not be classified successfully
 */
public double classifyInstance(Instance inst) throws Exception {

  // Filter instance
  inst = filterInstance(inst);

  // Build K vector
  Matrix k = new Matrix(m_NumTrain, 1);
  for (int i = 0; i < m_NumTrain; i++) {
    k.set(i, 0, m_kernel.eval(-1, i, inst));
  }

  double result = k.transpose().times(m_t).get(0, 0) + m_avg_target;
  result = (result - m_Blin) / m_Alin;

  return result;

}
 
Example 2
Source File: GaussianProcesses.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns natural logarithm of density estimate for given value based on given instance.
 *   
 * @param instance the instance to make the prediction for.
 * @param value the value to make the prediction for.
 * @return the natural logarithm of the density estimate
 * @exception Exception if the density cannot be computed
 */
public double logDensity(Instance inst, double value) throws Exception {
  
  inst = filterInstance(inst);

  // Build K vector (and Kappa)
  Matrix k = new Matrix(m_NumTrain, 1);
  for (int i = 0; i < m_NumTrain; i++) {
    k.set(i, 0, m_kernel.eval(-1, i, inst));
  }
  
  double estimate = k.transpose().times(m_t).get(0, 0) + m_avg_target;

  double sigma = computeStdDev(inst, k);
  
  // transform to GP space
  value = value * m_Alin + m_Blin;
  // center around estimate
  value = value - estimate;
  double z = -Math.log(sigma * Math.sqrt(2 * Math.PI)) 
    - value * value /(2.0*sigma*sigma); 
  
  return z + Math.log(m_Alin);
}
 
Example 3
Source File: sIB.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
private Matrix getTransposedNormedMatrix(Instances data) {
   Matrix matrix = new Matrix(data.numAttributes(), data.numInstances());
   for(int i = 0; i < data.numInstances(); i++){
     double[] vals = data.instance(i).toDoubleArray();
     double sum = Utils.sum(vals);
     for (int v = 0; v < vals.length; v++) {
vals[v] /= sum;
matrix.set(v, i, vals[v]);
     }      
   }
   return matrix;
 }
 
Example 4
Source File: GaussianProcesses.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gives standard deviation of the prediction at the given instance.
 * 
 * @param inst
 *            the instance to get the standard deviation for
 * @return the standard deviation
 * @throws Exception
 *             if computation fails
 */
public double getStandardDeviation(Instance inst) throws Exception {

  inst = filterInstance(inst);

  // Build K vector (and Kappa)
  Matrix k = new Matrix(m_NumTrain, 1);
  for (int i = 0; i < m_NumTrain; i++) {
    k.set(i, 0, m_kernel.eval(-1, i, inst));
  }

  return computeStdDev(inst, k) / m_Alin;
}
 
Example 5
Source File: PLSFilter.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * normalizes the given vector (inplace) 
 * 
 * @param v		the vector to normalize
 */
protected void normalizeVector(Matrix v) {
  double	sum;
  int		i;
  
  // determine length
  sum = 0;
  for (i = 0; i < v.getRowDimension(); i++)
    sum += v.get(i, 0) * v.get(i, 0);
  sum = StrictMath.sqrt(sum);
  
  // normalize content
  for (i = 0; i < v.getRowDimension(); i++)
    v.set(i, 0, v.get(i, 0) / sum);
}
 
Example 6
Source File: NNConditionalEstimator.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/** Calculate covariance and value means */
 private void calculateCovariance() {
   
   double sumValues = 0, sumConds = 0;
   for(int i = 0; i < m_Values.size(); i++) {
     sumValues += ((Double)m_Values.elementAt(i)).doubleValue()
* ((Double)m_Weights.elementAt(i)).doubleValue();
     sumConds += ((Double)m_CondValues.elementAt(i)).doubleValue()
* ((Double)m_Weights.elementAt(i)).doubleValue();
   }
   m_ValueMean = sumValues / m_SumOfWeights;
   m_CondMean = sumConds / m_SumOfWeights;
   double c00 = 0, c01 = 0, c10 = 0, c11 = 0;
   for(int i = 0; i < m_Values.size(); i++) {
     double x = ((Double)m_Values.elementAt(i)).doubleValue();
     double y = ((Double)m_CondValues.elementAt(i)).doubleValue();
     double weight = ((Double)m_Weights.elementAt(i)).doubleValue();
     c00 += (x - m_ValueMean) * (x - m_ValueMean) * weight;
     c01 += (x - m_ValueMean) * (y - m_CondMean) * weight;
     c11 += (y - m_CondMean) * (y - m_CondMean) * weight;
   }
   c00 /= (m_SumOfWeights - 1.0);
   c01 /= (m_SumOfWeights - 1.0);
   c10 = c01;
   c11 /= (m_SumOfWeights - 1.0);
   m_Covariance = new Matrix(2, 2);
   m_Covariance.set(0, 0, c00);
   m_Covariance.set(0, 1, c01);
   m_Covariance.set(1, 0, c10);
   m_Covariance.set(1, 1, c11);
 }
 
Example 7
Source File: MahalanobisEstimator.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns value for normal kernel
 *
 * @param x the argument to the kernel function
 * @param variance the variance
 * @return the value for a normal kernel
 */
private double normalKernel(double x) {
  
  Matrix thisPoint = new Matrix(1, 2);
  thisPoint.set(0, 0, x);
  thisPoint.set(0, 1, m_ConstDelta);
  return Math.exp(-thisPoint.times(m_CovarianceInverse).
      times(thisPoint.transpose()).get(0, 0) 
      / 2) / (Math.sqrt(TWO_PI) * m_Determinant);
}
 
Example 8
Source File: MahalanobisEstimator.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Main method for testing this class.
 *
 * @param argv should contain a sequence of numeric values
 */
public static void main(String [] argv) {
  
  try {
    double delta = 0.5;
    double xmean = 0;
    double lower = 0;
    double upper = 10;
    Matrix covariance = new Matrix(2, 2);
    covariance.set(0, 0, 2);
    covariance.set(0, 1, -3);
    covariance.set(1, 0, -4);
    covariance.set(1, 1, 5);
    if (argv.length > 0) {
      covariance.set(0, 0, Double.valueOf(argv[0]).doubleValue());
    }
    if (argv.length > 1) {
      covariance.set(0, 1, Double.valueOf(argv[1]).doubleValue());
    }
    if (argv.length > 2) {
      covariance.set(1, 0, Double.valueOf(argv[2]).doubleValue());
    }
    if (argv.length > 3) {
      covariance.set(1, 1, Double.valueOf(argv[3]).doubleValue());
    }
    if (argv.length > 4) {
      delta = Double.valueOf(argv[4]).doubleValue();
    }
    if (argv.length > 5) {
      xmean = Double.valueOf(argv[5]).doubleValue();
    }
    
    MahalanobisEstimator newEst = new MahalanobisEstimator(covariance,
        delta, xmean);
    if (argv.length > 6) {
      lower = Double.valueOf(argv[6]).doubleValue();
      if (argv.length > 7) {
        upper = Double.valueOf(argv[7]).doubleValue();
      }
      double increment = (upper - lower) / 50;
      for(double current = lower; current <= upper; current+= increment)
        System.out.println(current + "  " + newEst.getProbability(current));
    } else {
      System.out.println("Covariance Matrix\n" + covariance);
      System.out.println(newEst);
    }
  } catch (Exception e) {
    System.out.println(e.getMessage());
  }
}
 
Example 9
Source File: LLGC.java    From collective-classification-weka-package with GNU General Public License v3.0 4 votes vote down vote up
/**
 * initializes the matrices
 * 
 * @throws Exception	if something goes wrong
 */
protected void initialize() throws Exception {
  int           numInst;
  int           numCls;
  int           i;
  int           n;
  double        d;
  double        sum;
  double        factor;
  
  numInst = m_Data.size();
  numCls  = m_TrainsetNew.numClasses();
  
  // the classification matrix Y
  clock();
  m_MatrixY = new Matrix(numInst, numCls);
  for (i = 0; i < numInst; i++) {
    if (!m_Data.get(i).classIsMissing())
      m_MatrixY.set(i, (int) m_Data.get(i).classValue(), 1.0);
  }
  clock("Matrix Y");

  // the affinity matrix W
  // calc distances and variance of distances (i.e., sample variance)
  clock();
  if (getIncludeNumAttributes())
    factor = m_TrainsetNew.numAttributes();
  else
    factor = 1;
  m_DistanceFunction.setInstances(m_TrainsetNew);
  m_MatrixW = new Matrix(numInst, numInst);
  for (i = 0; i < numInst; i++) {
    for (n = 0; n < numInst; n++) {
      if (i == n) {
        d = 0;
      }
      else {
        d = m_DistanceFunction.distance(m_Data.get(i), m_Data.get(n));
        d = StrictMath.exp(
              -StrictMath.pow(d, 2) 
              / (2 * getSigma() * getSigma() * factor));
      }
      
      m_MatrixW.set(i, n, d);
    }
  }
  clock("Matrix W");
  
  // the diagonal matrix D
  clock();
  m_MatrixD = new Matrix(numInst, numInst);
  for (i = 0; i < numInst; i++) {
    sum = 0;
    for (n = 0; n < numInst; n++)
      sum += m_MatrixW.get(i, n);
    m_MatrixD.set(i, i, sum);
  }
  clock("Matrix D");

  // calc S or P (both results are stored in S for simplicity)
  clock();
  switch (m_SequenceLimit) {
    case SEQ_LIMIT_GRAPHKERNEL:
      // D^-1/2
      m_MatrixD = m_MatrixD.sqrt().inverse();
      // S = D^-1/2 * W * D^-1/2
      m_MatrixS = m_MatrixD.times(m_MatrixW).times(m_MatrixD);
      break;

    case SEQ_LIMIT_STOCHASTICMATRIX:
      // P = D^-1 * W
      m_MatrixS = m_MatrixD.inverse().times(m_MatrixW);
      break;
      
    case SEQ_LIMIT_STOCHASTICMATRIX_T:
      // P^T = (D^-1 * W)^T
      m_MatrixS = m_MatrixD.inverse().times(m_MatrixW).transpose();
      break;
      
    default: 
      throw new Exception("Unknown sequence limit function: " 
          + m_SequenceLimit + "!");
  }
  clock("Matrix S/P");
}
 
Example 10
Source File: GaussianProcesses.java    From tsml with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Computes a prediction interval for the given instance and confidence
 * level.
 * 
 * @param inst
 *            the instance to make the prediction for
 * @param confidenceLevel
 *            the percentage of cases the interval should cover
 * @return a 1*2 array that contains the boundaries of the interval
 * @throws Exception
 *             if interval could not be estimated successfully
 */
public double[][] predictIntervals(Instance inst, double confidenceLevel) throws Exception {

  inst = filterInstance(inst);

  // Build K vector (and Kappa)
  Matrix k = new Matrix(m_NumTrain, 1);
  for (int i = 0; i < m_NumTrain; i++) {
    k.set(i, 0, m_kernel.eval(-1, i, inst));
  }

  double estimate = k.transpose().times(m_t).get(0, 0) + m_avg_target;

  double sigma = computeStdDev(inst, k);

  confidenceLevel = 1.0 - ((1.0 - confidenceLevel) / 2.0);

  double z = Statistics.normalInverse(confidenceLevel);

  double[][] interval = new double[1][2];

  interval[0][0] = estimate - z * sigma;
  interval[0][1] = estimate + z * sigma;

  interval[0][0] = (interval[0][0] - m_Blin) / m_Alin;
  interval[0][1] = (interval[0][1] - m_Blin) / m_Alin;

  return interval;

}