softmax function

Matrix softmax(
  1. Matrix matrix
)

Softmax of a matrix

  • matrix The matrix to find the softmax
  • Returns The new matrix

Implementation

Matrix softmax(Matrix matrix) {
  Matrix result = Matrix(matrix.row, matrix.col);
  for (int i = 0; i < matrix.row; i++) {
    List<double> row = matrix[i] as List<double>;
    double maxV = row.reduce((a, b) => a > b ? a : b);
    List<double> expValues = row.map((x) => exp(x - maxV)).toList();
    double sumExp = expValues.reduce((a, b) => a + b);
    for (int j = 0; j < row.length; j++) {
      result.setAt(i, j, value: expValues[j] / sumExp);
    }
  }
  return result;
}