Mutable Vector field is not updated in F #

let gradientDescent (X : Matrix<double>) (y :Vector<double>) (theta : Vector<double>) alpha (num_iters : int) = let J_history = Vector<double>.Build.Dense(num_iters) let m = y.Count |> double theta.At(0, 0.0) let x = (X.Column(0).PointwiseMultiply(X*theta-y)) |> Vector.sum for i in 0 .. (num_iters-1) do let next_theta0 = theta.[0] - (alpha / m) * ((X.Column(0).PointwiseMultiply(X*theta-y)) |> Vector.sum) let next_theta1 = theta.[1] - (alpha / m) * ((X.Column(1).PointwiseMultiply(X*theta-y)) |> Vector.sum) theta.[0] = next_theta0 |> ignore theta.[1] = next_theta1 |> ignore J_history.[i] = computeCost X y theta |> ignore () (theta, J_history) 

Despite the fact that matrices and vectors are mutable, their dimension is fixed and cannot be changed after creation.

http://numerics.mathdotnet.com/Matrix.html

I have a theta which is a 2x1 size vector I'm trying to update theta. [0] and theta [1]. iteratively, but when I look at it after each iteration, it remains [0; 0]. I know that F # is immutable, but I quoted above from my website that Vectors and Matrix are mutable, so I'm not sure why this is not working.

I suspect this has something to do with Shadowing ... because I am declaring let next_theta0 in a for loop, but I'm not sure.

In addition, as a follow-up question. I feel that the way I did it is incredibly horrible. There is literally no reason for me to implement this in F #, when it would be much easier in C # (using this methodology), because it does not feel very "functional". Can anyone suggest ways to endorse this to make it more functional.

0
source share
1 answer

The destructive update statement in F # is written <- , therefore:

 theta.[0] <- next_theta0 

What you do in your code is theta.[0] comparison theta.[0] with next_theta0 , which is the operation that leads to bool , so you had to add an ignore call after it to avoid a compiler warning.

Here is a good general rule: when you see a compiler warning, don't just try to use tricks to calm the compiler. Instead, try to understand why the warning appears. Most likely, this indicates a legitimate problem.

And here is more F # -special rule: the use of ignore is the smell of code. ignore is a kind of hack, mainly used to interact with external code, when the external code returns something, but does not really expect the consumer to use this return value.

+1
source

Source: https://habr.com/ru/post/1244542/


All Articles