6

我仍在研究 F# 的东西 - 试图弄清楚如何在 F# 中“思考”,而不仅仅是从我知道的其他语言翻译。

我最近一直在考虑在之前和之后之间没有 1:1 映射的情况。List.map 崩溃的情况。

其中一个示例是移动平均线,通常在对 n 个项目进行平均时,对于长度为 len 的列表,您将得到 len-n+1 个结果。

对于那里的大师来说,这是一个好方法吗(使用从Jomo Fisher捏出来的队列)?

//Immutable queue, with added Length member
type Fifo<'a> =
    new()={xs=[];rxs=[]}
    new(xs,rxs)={xs=xs;rxs=rxs}

    val xs: 'a list;
    val rxs: 'a list;

    static member Empty() = new Fifo<'a>()
    member q.IsEmpty = (q.xs = []) && (q.rxs = [])
    member q.Enqueue(x) = Fifo(q.xs,x::q.rxs)
    member q.Length() = (List.length q.xs) + (List.length q.rxs)
    member q.Take() =
        if q.IsEmpty then failwith "fifo.Take: empty queue"
        else match q.xs with
                | [] -> (Fifo(List.rev q.rxs,[])).Take()
                | y::ys -> (Fifo(ys, q.rxs)),y

//List module, add function to split one list into two parts (not safe if n > lst length)
module List =
    let splitat n lst =
        let rec loop acc n lst =
            if List.length acc = n then
                (List.rev acc, lst)
            else
                loop (List.hd lst :: acc) n (List.tl lst)
        loop [] n lst

//Return list with moving average accross len elements of lst
let MovingAverage (len:int) (lst:float list) = 
    //ugly mean - including this in Fifo kills genericity
    let qMean (q:Fifo<float>) = ((List.sum q.xs) + (List.sum q.rxs))/(float (q.Length()))

    //get first part of list to initialise queue
    let (init, rest) = List.splitat len lst

    //initialise queue with first n items
    let q = new Fifo<float>([], init)

    //loop through input list, use fifo to push/pull values as they come
    let rec loop (acc:float list) ls (q:Fifo<float>) =
        match ls with
        | [] -> List.rev acc
        | h::t -> 
            let nq = q.Enqueue(h) //enqueue new value
            let (nq, _) = nq.Take() //drop old value
            loop ((qMean nq)::acc) t nq //tail recursion

    loop [qMean q] rest q

//Example usage    
MovingAverage 3 [1.;1.;1.;1.;1.;2.;2.;2.;2.;2.]

(也许更好的方法是通过从 Fifo 继承来实现 MovingAverageQueue?)

4

7 回答 7

7

如果你不太关心性能,这里有一个非常简单的解决方案:

#light

let MovingAverage n s =
   Seq.windowed n s
   |> Seq.map Array.average

let avgs = MovingAverage 5000 (Seq.map float [|1..999999|])

for avg in avgs do
    printfn "%f" avg
    System.Console.ReadKey() |> ignore

这会从头开始重新计算每个“窗口”的平均值,因此如果窗口很大,则效果不佳。

无论如何,请查看 Seq.windowed:

http://research.microsoft.com/projects/cambridge/fsharp/manual/FSharp.Core/Microsoft.FSharp.Collections.Seq.html

因为在你的后兜里放这样的东西很方便。

于 2008-11-18T03:26:09.750 回答
4

如果您确实关心性能,那么您可以使用类似这样的方法有效地计算移动平均线(假设我们正在计算 3 天窗口内的移动平均线)

数字[n] 运行总数[n]
--------- ---------------
n[0] = 7 7 = 数字[0]
n[1] = 1 8 = RunningTotal[1-1] + Numbers[1]
n[2] = 2 10 = RunningTotal[2-1] + Numbers[2]
n[3] = 8 11 = RunningTotal[3-1] + Numbers[3] - Numbers[3-3]
n[4] = 4 14 = RunningTotal[4-1] + Numbers[4] - Numbers[4-3]
n[5] = 1 13 = RunningTotal[5-1] + Numbers[5] - Numbers[5-3]
n[6] = 9 14 = RunningTotal[6-1] + Numbers[6] - Numbers[6-3]
...
N RunningTotal[N] = RunningTotal[N-1] + Numbers[N] - Numbers[N-3]

这方面的困难部分是保留您之前的运行总数和 Number N-window。我想出了以下代码:

let movingAverage days l =
    seq {
        let queue = new Queue<_>(days : int)
        let divisor = decimal days

        let total = ref 0m
        for cur in l do
            queue.Enqueue(cur)
            total := !total + cur
            if queue.Count < days then
                yield (cur, 0m)
            else
                yield (cur, !total / divisor)
                total := !total - (queue.Dequeue())
    }

这个版本不像 Haskell 代码那样好看,但它应该避免与在每次运行时重新计算“窗口”相关的性能问题。它保持一个运行总数并将以前使用的数字保存在一个队列中,所以它应该非常快。

只是为了好玩,我写了一个简单的基准测试:

#light
open System
open System.Collections.Generic
open System.Diagnostics;

let windowAverage days (l : #seq<decimal>) = Seq.windowed days l |> Seq.map (Seq.average)

let princessAverage days l =
    seq {
        let queue = new Queue<_>(days : int)
        let divisor = decimal days

        let total = ref 0m
        for cur in l do
            queue.Enqueue(cur)
            total := !total + cur
            if queue.Count < days then
                yield (cur, 0m)
            else
                yield (cur, !total / divisor)
                total := !total - (queue.Dequeue())
    }

let testData =
    let rnd = new System.Random()
    seq { for a in 1 .. 1000000 -> decimal (rnd.Next(1000)) }

let benchmark msg f iterations =
    let rec loop = function
        | 0 -> ()
        | n -> f 3 testData |> ignore; loop (n - 1)

    let stopWatch = Stopwatch.StartNew()
    loop iterations
    stopWatch.Stop()
    printfn "%s: %f" msg stopWatch.Elapsed.TotalMilliseconds

let _ =
    let iterations = 10000000
    benchmark "princessAverage" princessAverage iterations
    benchmark "windowAverage" windowAverage iterations
    printfn "Done"

结果:

公主平均:1670.791800
窗口平均:2986.146900

我的版本快 1.79 倍。

于 2009-02-03T18:19:34.400 回答
2

如果您关心性能并喜欢优雅的代码,请尝试

module MovingAverage = 
    let selfZip n l =
        Seq.skip n l |> Seq.zip l 

    let runTotal i z =
        Seq.scan ( fun sum (s, e) -> sum - s + e ) i z

    let average n l:seq<'a> =
        Seq.skip n l
        |> selfZip n
        |> runTotal (l |> Seq.take n |> Seq.sum)
        |> Seq.map ( fun sum -> decimal sum / decimal n ) 

 let ma = MovingAverage.average 2 myseq

使用 FSUnit 我们可以测试它

 let myseq = seq { for i in 0..10 do yield i }

 Seq.nth 0 ma |> should equal 0.5
    Seq.nth 1 ma |> should equal 1.5
    Seq.nth 2 ma |> should equal 2.5
    Seq.nth 3 ma |> should equal 3.5

该算法的技巧是先将前 n 个数字相加,然后通过添加窗口头部和减去窗口尾部来保持运行总计。滑动窗口是通过对序列执行自压缩来实现的,但第二个参数是按窗口大小提前的 zip。

在管道结束时,我们只需将运行总数除以窗口大小。

注意扫描就像折叠一样,但将每个版本的状态生成一个序列。

一个更优雅的解决方案虽然可能会影响性能,但可以观察到,如果我们对序列进行零填充,我们就不需要计算初始总和。

namespace Utils

module MovingAverage = 
    let selfZip n l =
        Seq.skip n l |> Seq.zip l 

    let rec zeros = 
        seq { yield 0.0; yield! zeros} 

    // Create a running total given
    let runTotal z =
        Seq.scan (fun sum (s,e) -> sum - s + e ) 0.0 z

    let average n l =
        Seq.concat [(Seq.take n zeros); l]
        |> selfZip n
        |> runTotal
        |> Seq.map ( fun sum -> sum / float n ) 
        |> Seq.skip n

由于与两个序列的包装相关的第二次间接性可能会导致性能下降,但可能并不重要,具体取决于窗口的大小

于 2012-08-31T08:06:08.427 回答
1

这是此处提出的 Haskell 解决方案的 F# 版本(我希望已更正)。

编辑:现在是尾递归的,不是更快,但不会在 n = 50000 时爆炸。(请参阅非尾递归版本的编辑历史记录)

let LimitedAverage n ls = 
    let rec loop acc i n ls = 
        match i with
        | 0 -> acc //i counts down from n to 0, when we hit 0 we stop
        | _ -> match ls with
               | [] -> acc //if we hit empty list before end of n, we stop too
               | x::xs -> (loop (acc + (x / float n)) (i - 1) n xs) //divide this value by n, perform average on 'rest' of list
    loop 0. n n ls

LimitedAverage 50000 (List.map float [1..9999999])
//>val it : float = 25000.5

let rec MovingAverage3 n ls = 
    let rec acc loop i n ls = 
        match i with 
        | 0 -> List.rev acc //i counts down from n to 0, when we hit 0 we stop
        | _ -> match ls with
                | [] -> List.rev acc //if we hit empty list before end of n, we stop too
                | x::xs -> loop (LimitedAverage2 n ls :: acc) (i - 1) n xs // limited average on whole list, then moving average on tail
    loop [] (n + 1) n ls 

MovingAverage3 50000 (List.map float [1..9999999])
//>val it : float list = [25000.5; 25001.5; 25002.5; ...]
于 2008-11-17T13:54:08.173 回答
0

这是我的版本。

let sma list n =
    let len = List.length list
    let rec loop acc sum cnt =
        if cnt >= len then List.rev acc
        else if cnt < n-1 then loop (0.0::acc) (sum + List.nth list cnt) (cnt+1)
        else loop (((sum + List.nth list cnt)/(float n))::acc) (sum + (List.nth list cnt) - (List.nth list (cnt-n+1))) (cnt+1)
    loop [] 0.0 0

例子:

sma (List.map float [5..50]) 5
[0, 0, 0, 0, 7, 8, 9, ...]
于 2015-01-04T22:24:50.633 回答
0

来自http://www.fssnip.net/4S/title/Moving-Average

let movingAverage (period : int) (values : float seq) =
  Seq.zip values (Seq.skip period values)
  |> Seq.scan (fun last (prev, cur) -> last - prev + cur) (values |> Seq.take period |> Seq.sum)
  |> Seq.map (fun x -> x / float(period))
于 2021-09-28T10:10:56.033 回答
-2

据我所知,您的代码充满了let语句。我不熟悉 F#,但确实做过一些 Haskell。功能范式意味着不考虑“如何”,而是考虑“什么”:您认为是 Fifo,但实际上您应该只指定移动平均线的语义。

-- the limited average of a list
limitedaverage 0 _ = 0
limited verage n (x:xs) = (x/n) + ( limited average (n-1) xs )

-- a list, transformed into a sequence of moving averages of 
movingaverages n [] = []
movingaverages n (x:xs) = ( movingaverage n (x:xs) : movingaverages n xs )
于 2008-11-17T13:07:18.093 回答