NMatrix division of arrays with different shapes

76 Views Asked by At

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!

3

There are 3 best solutions below

0
On BEST ANSWER

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] ]
0
On

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.

2
On

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.