如何将函数应用于浮点数组? [英] How To Apply a Function to an Array of float Arrays?
问题描述
假设我有n个数组,其中n是一个变量(一些数字大于2,通常小于10).
Let's suppose I have n arrays, where n is a variable (some number greater than 2, usually less than 10).
每个数组都有k个元素.
Each array has k elements.
我还有一个长度为n的数组,其中包含一组权重,这些权重决定了我希望如何线性组合所有数组.
I also have an array of length n that contains a set of weights that dictate how I would like to linearly combine all the arrays.
我正在尝试创建一个高性能的高阶函数,以在F#中组合这些数组.
I am trying to create a high performance higher order function to combine these arrays in F#.
如何执行此操作,以便获得一个函数,该函数需要一个数组数组(arrs是一个样本),一个weights数组(weights),然后根据这些权重计算加权总和?
How can I do this, so that I get a function that takes an array of arrays (arrs is a sample), a weights array (weights), and then computed a weighted sum based on the weights?
let weights = [|.6;;.3;.1|]
let arrs = [| [|.0453;.065345;.07566;1.562;356.6|] ;
[|.0873;.075565;.07666;1.562222;3.66|] ;
[|.06753;.075675;.04566;1.452;3.4556|] |]
感谢任何想法.
推荐答案
这里是一种解决方案:
let combine weights arrs =
Array.map2 (fun w -> Array.map ((*) w)) weights arrs
|> Array.reduce (Array.map2 (+))
编辑
这里有一些(非常需要的)解释它是如何工作的.从逻辑上讲,我们要执行以下操作:
Here's some (much needed) explanation of how this works. Logically, we want to do the following:
- 将每个权重应用于其对应的行.
- 将权重调整后的行加在一起.
上面的两行就是这样做的.
The two lines above do just that.
- 我们使用
Array.map2
函数组合相应的权重和行;我们将它们组合的方式是将行中的每个元素乘以权重,这是通过内部的Array.map
来实现的. - 现在我们有一个加权行数组,需要将它们加在一起.我们可以通过保持一个连续的总和,依次添加每个数组,一次完成一个步骤.我们逐点求和两个数组的方法是再次使用
Array.map2
,并使用(+)
作为合并每个数组中元素的函数.我们将其包装在Array.reduce
中,以便从第一行开始依次将此附加功能应用于每行.
- We use the
Array.map2
function to combine corresponding weights and rows; the way that we combine them is to multiply each element in the row by the weight, which is accomplished via the innerArray.map
. - Now we have an array of weighted rows and need to add them together. We can do this one step at a time by keeping a running sum, adding each array in turn. The way we sum two arrays pointwise is to use
Array.map2
again, using(+)
as the function for combining the elements from each. We wrap this in anArray.reduce
to apply this addition function to each row in turn, starting with the first row.
希望这是解决问题的一种相当优雅的方法,尽管公认的无点风格使其遵循起来有些棘手.但是,请注意,它并不是特别出色;进行就地更新,而不是使用map
,map2
和reduce
的每个应用程序创建新的数组会更有效.不幸的是,标准库没有包含这些可以就地工作的操作的相似物.但是,创建这样的类似物相对容易,并且它们的使用方式几乎与我在此处使用的方式完全相同.
Hopefully this is a reasonably elegant approach to the problem, though the point-free style admittedly makes it a bit tricky to follow. However, note that it's not especially performant; doing in-place updates rather than creating new arrays with each application of map
, map2
, and reduce
would be more efficient. Unfortunately, the standard library doesn't contain nice analogues of these operations which work in-place. It would be relatively easy to create such analogues, though, and they could be used in almost exactly the same way as I've done here.
这篇关于如何将函数应用于浮点数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!