2

I have an NMatrix array like this

x = NMatrix.new([3, 2], [3, 5, 5, 1, 10, 2], dtype: :float64)

I want to divide each column by maximum value along the column.

Using numpy this is achieved like this

Y = np.array(([3,5], [5,1], [10,2]), dtype=float)
Y = Y / np.amax(Y, axis = 0)

But NMatrix throws this error when I try this

X = X / X.max
The left- and right-hand sides of the operation must have the same shape. (ArgumentError)

Edit

I'm trying to follow this tutorial. And to scale input, the tutorial divides each column by the maximum value in that column. My question is how to achieve that step using nmatrix.

My question is how to achieve the same with NMatrix.

Thanks!

prajwaldp
  • 178
  • 1
  • 14
  • `NMatrix#max` has an optional parameter for dimension. Try something like `X.max(0)` (I can't test now.) – Amadan Mar 07 '16 at 04:47
  • @Amadan, X.max returns an nmatrix object. Calling `to_a` on that object will give us an array with the max value in each column (that's exactly what I want). Dividing the original matrix with this X.max is the step that's giving the argument error. – prajwaldp Mar 07 '16 at 05:28

3 Answers3

2

There are a couple of ways to accomplish what you're attempting. Probably the most straightforward is something like this:

x_max = x.max(0)
x.each_with_indices do |val,i,j|
  x[i,j] /= x_max[j]
end

You could also do:

x.each_column.with_index do |col,j|
  x[0..2,j] /= x_max[j]
end

which may be slightly faster.

Translunar
  • 3,739
  • 33
  • 55
1

A generic column-oriented approach:

> x = NMatrix.new([3, 2], [3, 5, 5, 1, 10, 2], dtype: :float64)

> x.each_column.with_index do |col,j|
    m=col[0 .. (col.rows - 1)].max[0,0]
    x[0 .. (x.rows - 1), j] /= m
  end

> pp x

[
  [0.3, 1.0]   [0.5, 0.2]   [1.0, 0.4] ]
peak
  • 105,803
  • 17
  • 152
  • 177
0

Thanks for the answers!

I got it working using the following snippet.

x = x.each_row.map do |row|
  row / x.max
end

I don't really know how efficient this is, but just wanted to share it.

prajwaldp
  • 178
  • 1
  • 14