以矩阵形式实现 OLS

Implementing OLS in matrix form

我在 a quantitative economics course 中实施此练习时遇到问题。

这是我的代码:

N = 50
M = 20

a = 0.1
b = 0.2 
c = 0.5
d = 1.0
σ = 0.1 

estimates = zeros(M, 5)

for i ∈ 1:M
    x₁ = Vector{BigFloat}(randn(N))
    x₂ = Vector{BigFloat}(randn(N))
    w = Vector{BigFloat}(randn(N))
    
    # Derive y vector (element wise operations)
    y = a*x₁ .+ b.*(x₁.^2) .+ c.*x₂ .+ d .+ σ.*w
    
    # Derive X matrix
    X = [x₁ x₁ x₂ fill(d, (N, 1)) w]
    
    # Implementation of the formula β = inv(XᵀX)Xᵀy
    estimates[i, :] = (X'*X)\X'*y
end

histogram(estimates, layout=5, labels=["a", "b", "c", "d", "σ"])

我得到一个 SingularException(5) 错误,因为矩阵 X'X 的行列式为 0 并且没有逆矩阵。我的问题是,我在这个练习中哪里出错了?我听说行列式可能为零的原因是浮点数不准确,所以我将随机变量 BigFloats 设置为无济于事。我知道我犯的错误不是很复杂,但我迷路了。谢谢!

你的X应该是

X = [x₁ x₁*x₁ x₂ fill(d, (N, 1))]

说明

看来您正在尝试测试 OLS 来估计模型的参数:

y = α₀ + α₁x₁ + α₁₁x₁² + α₂x₂ + ϵ

其中α₀是模型的截距,α₁α₁₁α₂是解释变量的参数,ϵ是期望值 0 和方差 σ² 的随机误差。因此 X 的结构必须符合您的情况。

输入 α₁ 两次 co-linearity 并出现错误。

您也不想“估计”ϵ 的参数,因为它代表随机性。