float normMaxEval(Matrix U, Matrix uVal, Matrix uVec) {
    /* *
     * Decomposition:
     * U = V * D * V.inv()
     * V has eigenvectors as columns
     * D is a diagonal Matrix with eigenvalues as elements
     * V.inv() is the inverse of V
     * */
    //		uVec = uVec.transpose();
    Matrix uVinv = uVec.inverse();

    // Normalize min eigenvalue to 1 to expand patch in the direction of min eigenvalue of U.inv()
    double uval1 = uVal.get(0, 0);
    double uval2 = uVal.get(1, 1);

    if (Math.abs(uval1) < Math.abs(uval2)) {
      uVal.set(0, 0, 1);
      uVal.set(1, 1, uval2 / uval1);

    } else {
      uVal.set(1, 1, 1);
      uVal.set(0, 0, uval1 / uval2);
    }

    // U normalized
    U.setMatrix(0, 1, 0, 1, uVec.times(uVal).times(uVinv));

    return (float)
        (Math.max(Math.abs(uVal.get(0, 0)), Math.abs(uVal.get(1, 1)))
            / Math.min(
                Math.abs(uVal.get(0, 0)),
                Math.abs(uVal.get(1, 1)))); // define the direction of warping
  }
  /*
   * Calculates second moments matrix square root
   */
  float calcSecondMomentSqrt(AbstractStructureTensorIPD ipd, Pixel p, Matrix Mk) {
    Matrix M, V, eigVal, Vinv;

    M = calcSecondMomentMatrix(ipd, p.x, p.y);

    /* *
     * M = V * D * V.inv()
     * V has eigenvectors as columns
     * D is a diagonal Matrix with eigenvalues as elements
     * V.inv() is the inverse of V
     * */
    //		EigenvalueDecomposition meig = M.eig();
    EigenValueVectorPair meig = MatrixUtils.symmetricEig2x2(M);
    eigVal = meig.getValues();
    V = meig.getVectors();

    //		V = V.transpose();
    Vinv = V.inverse();

    double eval1 = Math.sqrt(eigVal.get(0, 0));
    eigVal.set(0, 0, eval1);
    double eval2 = Math.sqrt(eigVal.get(1, 1));
    eigVal.set(1, 1, eval2);

    // square root of M
    Mk.setMatrix(0, 1, 0, 1, V.times(eigVal).times(Vinv));

    // return q isotropic measure
    return (float) (Math.min(eval1, eval2) / Math.max(eval1, eval2));
  }
  /**
   * @param m Matrix with 2 rows, one column (2x1)
   * @return Point with same coordinates as in Matrix
   * @throws InvalidParameterException if the Matrix has wrong dimensions
   */
  public static Point2d matrixToPoint(final Matrix m) throws InvalidParameterException {
    if (m.getColumnDimension() != 1)
      throw new InvalidParameterException(
          "Circle.matrixToPoint: wrong number of columns: " + m.getColumnDimension());
    if (m.getRowDimension() != 2)
      throw new InvalidParameterException(
          "Circle.matrixToPoint: wrong number of rows: " + m.getRowDimension());

    Point2d point = new Point2d(m.get(0, 0), m.get(1, 0));

    return point;
  }
  /**
   * @param m Matrix with 2 rows, one column (2x1)
   * @return Vector2d with same coordinates as in Matrix
   * @throws InvalidParameterException if the Matrix has wrong dimensions
   */
  public static Vector2d matrixToVector(final Matrix m) throws InvalidParameterException {
    if (m.getColumnDimension() != 1)
      throw new InvalidParameterException(
          "Circle.matrixToPoint: wrong number of columns: " + m.getColumnDimension());
    if (m.getRowDimension() != 2)
      throw new InvalidParameterException(
          "Circle.matrixToPoint: wrong number of rows: " + m.getRowDimension());

    Vector2d vector = new Vector2d(m.get(0, 0), m.get(1, 0));

    return vector;
  }
 @Override
 public Matrix getHessianMatrix(Matrix x) {
   Matrix hess = new Matrix(n, n);
   for (int i = 0; i < n; i++) {
     for (int j = 0; j < n; j++) {
       for (int k = 0; k < n; k++) {
         hess.set(i, j, hess.get(i, j) + 2 * coefficients.get(k, i) * coefficients.get(k, j));
       }
     }
   }
   return hess;
 }
  /** Gets the max score in a matrix m. */
  private double getMaxScore(final Matrix m) {
    final double blockingValue = (Double) settings.get(KEY_BLOCKING_VALUE);
    double max = Double.NEGATIVE_INFINITY;

    for (int i = 0; i < m.getRowDimension(); i++) {
      for (int j = 0; j < m.getColumnDimension(); j++) {
        if (m.get(i, j) > max && m.get(i, j) < blockingValue) {
          max = m.get(i, j);
        }
      }
    }
    return max;
  }
  @Override
  public double getFunctionValue(Matrix x) {
    Matrix err = coefficients.times(x).minus(y);
    for (int i = 0; i < n; i++) {
      err.set(i, 0, Math.pow(err.get(i, 0), 2));
    }

    double value = 0.0;
    for (int i = 0; i < n; i++) {
      value += err.get(i, 0);
    }
    return value;
  }
  private double[] estimateVariance() {
    double[] beta = getBestValuesEver();

    Matrix hessian = new Matrix(beta.length, beta.length);
    for (Example example : exampleSet) {
      double[] values = new double[beta.length];
      double eta = 0.0d;
      int j = 0;
      for (Attribute attribute : example.getAttributes()) {
        double value = example.getValue(attribute);
        values[j] = value;
        eta += beta[j] * value;
        j++;
      }
      if (addIntercept) {
        values[beta.length - 1] = 1.0d;
        eta += beta[beta.length - 1];
      }
      double pi = Math.exp(eta) / (1 + Math.exp(eta));

      double weightValue = 1.0d;
      if (weight != null) weightValue = example.getValue(weight);
      for (int x = 0; x < beta.length; x++) {
        for (int y = 0; y < beta.length; y++) {
          // sum is second derivative of log likelihood function
          double h = hessian.get(x, y) - values[x] * values[y] * weightValue * pi * (1 - pi);
          hessian.set(x, y, h);
        }
      }
    }

    double[] variance = new double[beta.length];
    Matrix varianceCovarianceMatrix = null;
    try {
      // asymptotic variance-covariance matrix is inverse of hessian matrix
      varianceCovarianceMatrix = hessian.inverse();
    } catch (Exception e) {
      logging.logWarning("could not determine variance-covariance matrix, hessian is singular");
      for (int j = 0; j < beta.length; j++) {
        variance[j] = Double.NaN;
      }
      return variance;
    }
    for (int j = 0; j < beta.length; j++) {
      // get diagonal elements
      variance[j] = Math.abs(varianceCovarianceMatrix.get(j, j));
    }

    return variance;
  }
  @Override
  public Matrix getGradientValue(Matrix x) {
    Matrix err = coefficients.times(x).minus(y).times(2);
    Matrix grad = new Matrix(n, 1);
    for (int i = 0; i < n; i++) {
      double value = 0.0;
      for (int j = 0; j < n; j++) {
        value += err.get(j, 0) * coefficients.get(j, i);
      }
      grad.set(i, 0, value);
    }

    return grad;
  }
 /**
  * Returns a rows x columns matrix with reciprocal elements
  *
  * @param m - the input matrix
  * @return Matrix - the result matrix
  */
 public static Matrix getReciprocalMatrix(Matrix m) {
   final int rows = m.getRowDimension();
   final int cols = m.getColumnDimension();
   Matrix resultM = new Matrix(rows, cols);
   for (int i = 0; i < rows; i++) {
     for (int j = 0; j < cols; j++) {
       if (m.get(i, j) != 0.0) {
         resultM.set(i, j, 1.0 / m.get(i, j));
       } else {
         resultM.set(i, j, 0.0);
       }
     }
   }
   return resultM;
 }
示例#11
0
文件: Mat.java 项目: Peachball/ML-Fun
  public static Matrix addBotMatrix(Matrix a, Matrix b) {
    Matrix c = new Matrix(a.getRowDimension() + b.getRowDimension(), a.getColumnDimension());
    for (int i = 0; i < a.getRowDimension(); i++) {
      for (int j = 0; j < a.getColumnDimension(); j++) {
        c.set(i, j, a.get(i, j));
      }
    }
    for (int i = 0; i < b.getRowDimension(); i++) {
      for (int j = 0; j < b.getColumnDimension(); j++) {
        c.set(i + a.getRowDimension(), j, b.get(i, j));
      }
    }

    return c;
  }
示例#12
0
    private Matrix SqrtSPKF(Matrix PDash) {
      // Only works with a symmetric Positive Definite matrix
      // [V,D] = eig(A)
      // S = V*diag(sqrt(diag(D)))*V'
      //
      // //PDash in
      // System.out.println("PDash: ");
      // PDash.print(3, 2);

      // Matrix NegKeeper = Matrix.identity(9, 9);
      // //Testing Forced Compliance
      // for(int i = 0; i< 9; i++){
      // if (PDash.get(i, i)< 0){
      // NegKeeper.set(i,i,-1);
      // PDash.set(i, i, -PDash.get(i, i));
      // }
      // }
      EigenvalueDecomposition eig = PDash.eig();
      Matrix V = eig.getV();
      Matrix D = eig.getD();
      int iDSize = D.getRowDimension();
      for (int i = 0; i < iDSize; i++) {
        D.set(i, i, Math.sqrt(D.get(i, i)));
      }
      Matrix S = V.times(D).times(V.inverse());
      // S = S.times(NegKeeper);
      return S;
    }
示例#13
0
  /**
   * * Least-square solution y = X * b where: y_i = b_0 + b_1*x_1i + b_2*x_2i + ... + b_k*x_ki
   * including intercep term y_i = b_1*x_1i + b_2*x_2i + ... + b_k*x_ki without intercep term
   *
   * @param datay
   * @param dataX
   */
  private void multipleLinearRegression(Matrix datay, Matrix dataX) {
    Matrix X, y;
    try {
      X = dataX;
      y = datay;
      b = X.solve(y);
      coeffs = new double[b.getRowDimension()];
      for (int j = 0; j < b.getRowDimension(); j++) {
        coeffs[j] = b.get(j, 0);
        // System.out.println("coeff[" + j + "]=" + coeffs[j]);
      }

      // Residuals:
      Matrix r = X.times(b).minus(y);
      residuals = r.getColumnPackedCopy();
      // root mean square error (RMSE)
      rmse = Math.sqrt(MathUtils.sumSquared(residuals) / residuals.length);

      // Predicted values
      Matrix p = X.times(b);
      predictedValues = p.getColumnPackedCopy();

      // Correlation between original values and predicted ones
      correlation = MathUtils.correlation(predictedValues, y.getColumnPackedCopy());

    } catch (RuntimeException re) {
      throw new Error("Error solving Least-square solution: y = X * b");
    }
  }
示例#14
0
  /**
   * Computes the pseudo-inverse of a matrix using Singular Value Decomposition
   *
   * @param M - the input {@link Matrix}
   * @param threshold - the threshold for inverting diagonal elements (suggested 0.001)
   * @return the inverted {@link Matrix} or an approximation with lowest possible squared error
   */
  public static final Matrix computePseudoInverseMatrix(final Matrix M, final double threshold) {
    final SingularValueDecomposition svd = new SingularValueDecomposition(M);

    Matrix U = svd.getU(); // U Left Matrix
    final Matrix S = svd.getS(); // W
    final Matrix V = svd.getV(); // VT Right Matrix

    double temp;

    // invert S
    for (int j = 0; j < S.getRowDimension(); ++j) {
      temp = S.get(j, j);

      if (temp < threshold) // this is an inaccurate inverting of the matrix
      temp = 1.0 / threshold;
      else temp = 1.0 / temp;

      S.set(j, j, temp);
    }

    // transponse U
    U = U.transpose();

    //
    // compute result
    //
    return ((V.times(S)).times(U));
  }
  public Matrix matrix(boolean centered) {
    String[] genes = genes();
    Matrix matrix = new Matrix(genes.length, coefs.size());

    for (int j = 0; j < coefs.size(); j++) {
      Map<String, Double> values = coefs.get(j).geneValues(args.compare);
      double sum = 0.0;

      for (int i = 0; i < genes.length; i++) {
        Double value = values.get(genes[i]);
        if (value != null) {
          matrix.set(i, j, value);
          sum += value;
        } else {
          matrix.set(i, j, 0.0);
        }
      }

      if (centered) {
        sum /= (double) genes.length;
        for (int i = 0; i < genes.length; i++) {
          matrix.set(i, j, matrix.get(i, j) - sum);
        }
      }
    }

    return matrix;
  }
 public static double[] column(Matrix m, int i) {
   double[] array = new double[m.getRowDimension()];
   for (int k = 0; k < array.length; k++) {
     array[k] = m.get(k, i);
   }
   return array;
 }
 public static double[] row(Matrix m, int i) {
   double[] array = new double[m.getColumnDimension()];
   for (int k = 0; k < array.length; k++) {
     array[k] = m.get(i, k);
   }
   return array;
 }
示例#18
0
 @Override
 public String toResultString() {
   StringBuilder result =
       new StringBuilder(
           Tools.getLineSeparator() + "Principal Components:" + Tools.getLineSeparator());
   if (manualNumber) {
     result.append("Number of Components: " + numberOfComponents + Tools.getLineSeparator());
   } else {
     result.append("Proportion Threshold: " + proportionThreshold + Tools.getLineSeparator());
   }
   for (int i = 0; i < vMatrix.getColumnDimension(); i++) {
     result.append("PC " + (i + 1) + ": ");
     for (int j = 0; j < attributeNames.length; j++) {
       double value = vMatrix.get(i, j);
       if (value > 0) {
         result.append(" + ");
       } else {
         result.append(" - ");
       }
       result.append(Tools.formatNumber(Math.abs(value)) + " * " + attributeNames[j]);
     }
     result.append(Tools.getLineSeparator());
   }
   return result.toString();
 }
 protected void addToCentroid(Matrix m, PositionWeightMatrix pwm) {
   for (int i = 0; i < m.getColumnDimension(); i++) {
     PositionWeightColumn c = pwm.get(i);
     for (int j = 0; j < m.getRowDimension(); j++) {
       m.set(j, i, m.get(j, i) + c.getWeight(j));
     }
   }
 }
示例#20
0
 public static PImage invert(Matrix H, PImage img, Point dstDimension) {
   PImage res = new PImage(dstDimension.x, dstDimension.y);
   //		PImage res = new PImage(img.width, img.height);
   for (int x = 0; x < img.width; x++) {
     for (int y = 0; y < img.height; y++) {
       // Point inverse theorique (x0,y0) ?
       double[][] q_array = {{x}, {y}, {1}};
       Matrix P = H.times(new Matrix(q_array));
       double x0 = P.get(0, 0) / P.get(2, 0);
       double y0 = P.get(1, 0) / P.get(2, 0);
       // S'il est hors de l'image originale, on rend le pixel transparant.
       if (x0 < 0 || x0 >= img.width || y0 < 0 || y0 >= img.height) res.set(x, y, 0x00000000);
       else res.set(x, y, img.get((int) x0, (int) y0));
     }
   }
   return res;
 }
 /**
  * Checks if a matrix contains zeros in diagonale Input must be a nxm matrix with n = m
  *
  * @param m - original matrix
  * @return boolean
  */
 public static boolean matrixHasZerosInDiagonale(Matrix m) {
   for (int i = 0; i < m.getRowDimension(); i++) {
     if (m.get(i, i) == 0.0) {
       return true;
     }
   }
   return false;
 }
示例#22
0
文件: Mat.java 项目: Peachball/ML-Fun
 public static Matrix remove1stColumn(Matrix m) {
   Matrix a = new Matrix(m.getRowDimension(), m.getColumnDimension() - 1);
   for (int i = 0; i < a.getRowDimension(); i++) {
     for (int j = 0; j < a.getColumnDimension(); j++) {
       a.set(i, j, m.get(i, j + 1));
     }
   }
   return a;
 }
示例#23
0
 /**
  * Returns C = A + b, where b is a scalar
  *
  * @param val
  * @return
  */
 public MatrixObject scalarAdd(int val) {
   Matrix m = matrix.copy();
   for (int i = 0; i < rows(); i++) {
     for (int j = 0; j < cols(); j++) {
       m.set(i, j, m.get(i, j) + val);
     }
   }
   return new MatrixObject(m);
 }
  private Matrix makeHessienne(double R0, double Z0) {
    Matrix hessienne = new Matrix(2, 2);

    hessienne.set(0, 0, d2_phi_d_R2(R0, Z0));
    hessienne.set(0, 1, d2_phi_d_R_d_Z(R0, Z0));
    hessienne.set(1, 0, hessienne.get(0, 1));
    hessienne.set(1, 1, d2_phi_d_Z2(R0, Z0));

    return hessienne;
  }
 public static String convertWeightsToTabSeparatedString(Matrix w) {
   StringBuffer retval = new StringBuffer();
   for (int i = 0; i < w.getRowDimension(); i++) {
     if (i != 0) {
       retval.append("\t");
     }
     retval.append(String.format("%f", w.get(i, 0)));
   }
   return retval.toString();
 }
 /**
  * Checks if a matrix contains NaN elements
  *
  * @param m - original matrix
  * @return boolean
  */
 public static boolean matrixHasNanElements(Matrix m) {
   for (int i = 0; i < m.getRowDimension(); i++) {
     for (int j = 0; j < m.getColumnDimension(); j++) {
       if (Double.isNaN(m.get(i, j))) {
         return true;
       }
     }
   }
   return false;
 }
示例#27
0
文件: Mat.java 项目: Peachball/ML-Fun
 public static Matrix add1sColumn(Matrix m) {
   Matrix a = new Matrix(m.getRowDimension(), m.getColumnDimension() + 1);
   for (int i = 0; i < a.getRowDimension(); i++) {
     a.set(i, 0, 1);
     for (int j = 1; j < a.getColumnDimension(); j++) {
       a.set(i, j, m.get(i, j - 1));
     }
   }
   return a;
 }
  /**
   * Returns a matrix which contains on the diagonal the original elements, and zeros elsewhere
   * Input must be a nxm matrix with n = m
   *
   * @param m - original matrix
   * @return Matrix - the filtered matrix
   */
  public static Matrix getRectangularDiagonalMatrix(Matrix m) {
    if (m.getRowDimension() != m.getColumnDimension()) {
      return null;
    }

    Matrix diag = new Matrix(m.getRowDimension(), m.getRowDimension());
    for (int i = 0; i < m.getRowDimension(); i++) {
      diag.set(i, i, m.get(i, i));
    }
    return diag;
  }
 /**
  * Returns the product of all elements of a matrix (equivalent to Python's numpy.product(m))
  *
  * @param m - the input matrix
  * @return double - the result
  */
 public static double getMatrixAllElementsProduct(Matrix m) {
   final int rows = m.getRowDimension();
   final int cols = m.getColumnDimension();
   double result = 1.0;
   for (int i = 0; i < rows; i++) {
     for (int j = 0; j < cols; j++) {
       result *= m.get(i, j);
     }
   }
   return result;
 }
  public static RealMatrix getRealMatrixFromJamaMatrix(Matrix m) {
    final int rDim = m.getRowDimension();
    final int cDim = m.getColumnDimension();
    RealMatrix rm = new Array2DRowRealMatrix(rDim, cDim);
    for (int i = 0; i < rDim; i++) {
      for (int j = 0; j < cDim; j++) {
        rm.setEntry(i, j, m.get(i, j));
      }
    }

    return rm;
  }