tanhMatrix function

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

Implementation

Tensor<Matrix> tanhMatrix(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 x = mMat[i][j];
      double e2x = exp(2.0 * x);
      if (e2x.isInfinite) {
        row.add(1.0);
      } else {
        row.add((e2x - 1.0) / (e2x + 1.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) {
        double val = out.data[i];
        m.grad[i] = m.grad[i] + out.grad[i] * (1.0 - (val * val));
      }
    },
    opName: 'tanh_matrix',
    cost: numRows * numCols,
  );
  return out;
}