可变向量字段未在F#中更新 [英] Mutable Vector field is not updating 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)
即使矩阵和向量是可变的,它们的维数也是固定的 并且创建后无法更改.
Even though matrices and vectors are mutable, their dimension is fixed and cannot be changed after creation.
http://numerics.mathdotnet.com/Matrix.html
我有theta,它是大小为2x1的向量 我正在尝试更新theta.[0]和theta.[1]迭代,但是当我在每次迭代后查看它时,它仍然是[0; 0].我知道F#是不可变的,但是我在上面从他们的网站上引用了Vectors和Matrix可变的信息,所以我不确定为什么它不起作用.
I have theta which is a vector of size 2x1 I'm trying to update theta.[0] and theta.[1] iteratively but when I look at it after each iteration it remains to be [0;0]. I know that F# is immutable but I quoted above from their website that Vectors and Matrix are mutable so I'm not sure why this isn't working.
我的直觉是它与Shadowing有关...因为我在for循环中声明了let next_theta0,但我不太确定
此外,作为后续问题.我觉得我实施此方法的方式非常糟糕.从字面上看,没有理由让我在F#中实现此功能,因为它在C#中会更容易(使用此方法),因为它感觉不太实用",谁能提出建议以使其更实用的方法.
Also, as a follow up question. I feel like the way I implemented this is incredibly terrible. There's literally no reason for me to have implemented this in F# when it would have been much easier in C# (using this methodology) because it doesn't feel very "functional" Could anyone suggest ways to approve on this to make it more functional.
推荐答案
F#中的破坏性更新运算符被编写为<-
,因此:
The destructive update operator in F# is written <-
, so:
theta.[0] <- next_theta0
您在代码中执行的操作是比较 theta.[0]
和next_theta0
,这是导致产生bool
的操作,这就是为什么必须添加
What you're doing in your code is comparing theta.[0]
with next_theta0
, which is an operation that results in a bool
, which is why you had to add an ignore
call after it, to avoid the compiler warning.
这是一个很好的通用规则:看到编译器警告时,不要只是尝试技巧来安抚编译器.而是尝试理解为什么出现警告.很有可能,这表明存在合法问题.
Here's a good general rule: when you see a compiler warning, don't just try tricks to appease the compiler. Instead, try to understand why the warning appears. Chances are, it points to a legitimate problem.
这是一个更特定于F#的规则:使用ignore
是一种代码味道. ignore
是一种hack,主要用于与外部代码交互,当外部代码返回某些内容,但并不真正希望消费者使用该返回值时.
And here's a more F#-specific rule: using ignore
is a code smell. ignore
is a sort of hack, mostly used for interaction with external code, when the external code returns something, but doesn't really expect the consumer to use that return value.
这篇关于可变向量字段未在F#中更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!