SciRuby / nmatrix

Dense and sparse linear algebra library for Ruby via SciRuby
Other
469 stars 133 forks source link

NMatrix#max returns different shape/dimension compared to np#max #560

Closed mokpro closed 7 years ago

mokpro commented 7 years ago

Problem

While comparing #max betweek NMatrix and Numpy, I found following differences in shape/dimension:

Numpy:

>>> from sklearn.utils import check_array
>>> import numpy as np
>>> 
>>> arr = [[0, 0, 3], [1, 1, 0]]
[[0, 0, 3], [1, 1, 0]]
>>> mat = check_array(arr)
array([[0, 0, 3],
       [1, 1, 0]])
>>> sol = np.max(mat, axis=0)
array([1, 1, 3])
>>> sol.shape
(3,)
>>> sol.ndim
1

NMatrix:

[1] pry(main)> arr = [[0, 0, 3], [1, 1, 0]]
=> [[0, 0, 3], [1, 1, 0]]
[2] pry(main)> mat = arr.to_nm
=>
[
  [0, 0, 3]
  [1, 1, 0]
]
[3] pry(main)> sol = mat.max(0)
=>
[
  [1.0, 1.0, 3.0]
]
[4] pry(main)> sol.shape
=> [1, 3]
[5] pry(main)> sol.dim
=> 2

Workaround/ solution

def max(dimen=0)
    inject_rank(dimen) do |max, sub_mat|
      if max.is_a? NMatrix then
        max * (max >= sub_mat).cast(self.stype, self.dtype) + ((max)*0.0 + (max < sub_mat).cast(self.stype, self.dtype)) * sub_mat
      else
        max >= sub_mat ? max : sub_mat
      end
    end
  end.to_a.to_nm

Do let me know if this is a bug. I want to work on the fix.

Thanks!

translunar commented 7 years ago

It's not a bug, just a difference. In my experience, it's easier to have a universe that consists entirely of 2D matrices than one that has 2D matrices and 1D vectors (of ambiguous orientation).