不同形状数组的NMatrix划分
NMatrix division of arrays with different shapes
我有一个像这样的 NMatrix 数组
x = NMatrix.new([3, 2], [3, 5, 5, 1, 10, 2], dtype: :float64)
我想将每列除以沿列的最大值。
使用 numpy 是这样实现的
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)
编辑
我正在尝试关注 this tutorial。为了缩放输入,本教程将每列除以该列中的最大值。我的问题是如何使用 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 数组
x = NMatrix.new([3, 2], [3, 5, 5, 1, 10, 2], dtype: :float64)
我想将每列除以沿列的最大值。
使用 numpy 是这样实现的
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)
编辑
我正在尝试关注 this tutorial。为了缩放输入,本教程将每列除以该列中的最大值。我的问题是如何使用 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
我真的不知道这有多高效,只是想分享一下。