Ruby n不同形状阵列的矩阵划分

Ruby n不同形状阵列的矩阵划分,ruby,nmatrix,Ruby,Nmatrix,我有一个像这样的NMatrix数组 x = NMatrix.new([3, 2], [3, 5, 5, 1, 10, 2], dtype: :float64) Y = np.array(([3,5], [5,1], [10,2]), dtype=float) Y = Y / np.amax(Y, axis = 0) 我想将每列除以该列上的最大值 使用numpy可以这样实现 x = NMatrix.new([3, 2], [3, 5, 5, 1, 10, 2], dtype: :float64

我有一个像这样的NMatrix数组

x = NMatrix.new([3, 2], [3, 5, 5, 1, 10, 2], dtype: :float64)
Y = np.array(([3,5], [5,1], [10,2]), dtype=float)
Y = Y / np.amax(Y, axis = 0)
我想将每列除以该列上的最大值

使用numpy可以这样实现

x = NMatrix.new([3, 2], [3, 5, 5, 1, 10, 2], dtype: :float64)
Y = np.array(([3,5], [5,1], [10,2]), dtype=float)
Y = Y / np.amax(Y, axis = 0)
但当我尝试此操作时,NMatrix会抛出此错误

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

我试着跟着。为了缩放输入,本教程将每列除以该列中的最大值。我的问题是如何使用nmatrix实现这一步骤

我的问题是如何使用NMatrix实现同样的功能


谢谢

有两种方法可以完成您的尝试。最直接的可能是这样的:

x_max = x.max(0)
x.each_with_indices do |val,i,j|
  x[i,j] /= x_max[j]
end
你也可以这样做:

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

这可能会稍微快一点。

一种面向列的通用方法:

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

谢谢你的回答

我使用下面的代码片段使它工作

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

我真的不知道这有多有效,但我只是想分享一下。

NMatrix\max
有一个可选的维度参数。尝试类似于
X.max(0)
(我现在无法测试。)@Amadan,X.max返回一个nmatrix对象。对该对象调用
以_a
将为我们提供一个数组,每个列中都有最大值(这正是我想要的)。将原始矩阵除以这个X.max就是给出参数错误的步骤。我不确定最后一行应该做什么。@johnny,是的。这是多余的和糟糕的。编辑我的答案。