reluMatrix function

Tensor<Matrix> reluMatrix(
  1. Tensor<Matrix> m
)

Implementation

Tensor<Matrix> reluMatrix(Tensor<Matrix> m) {
  int numRows = m.shape[0];
  int numCols = m.shape[1];

  Matrix mMat = m.value;

  Matrix outValue = [];
  for (int i = 0; i < numRows; i = i + 1) {
    Vector row = [];
    for (int j = 0; j < numCols; j = j + 1) {
      double val = mMat[i][j];
      row.add(val > 0.0 ? val : 0.0);
    }
    outValue.add(row);
  }

  Tensor<Matrix> out = Tensor<Matrix>(outValue);

  out.creator = Node(
    [m],
        () {
      int length = m.data.length;
      for (int i = 0; i < length; i = i + 1) {
        m.grad[i] = m.grad[i] + out.grad[i] * (m.data[i] > 0.0 ? 1.0 : 0.0);
      }
    },
    opName: 'relu_matrix',
    cost: numRows * numCols,
  );
  return out;
}