在本实验中,我需要从均值0和标准偏差为10的正态分布中采样150个x值,然后从x值中使用特征{1,x,x ^ 2}构造一个设计矩阵。
我们必须对参数进行采样,然后使用设计矩阵为回归数据创建y值。
问题是我的设计矩阵不是正方形,而Moore-Penrose Pseduoinverse需要平方矩阵,但鉴于实验室的早期设置,我不知道如何使它起作用?
这是我所做的
#Linear Regression Lab
import numpy as np
import math
data = np.random.normal(0, 10, 150)
design_matrix = np.zeros((150,3))
for i in range(150):
design_matrix[i][0] = 1
design_matrix[i][1] = data[i]
design_matrix[i][2] = pow(data[i], 2)
print("-------------------Design Matrix---------------------")
print("|--------1--------|-------x-------|--------x^2--------|")
print(design_matrix[:20])
#sampling paramters
theta_0 = np.random.uniform(low = -30, high = 20)
theta_1 = np.random.uniform(low = -30, high = 20)
theta_2 = np.random.uniform(low = -30, high = 20)
print(theta_0, theta_1, theta_2)
theta = np.array([theta_0, theta_1, theta_2])
theta = np.transpose(theta)
#moore penrose psuedo inverse
MPpi = np.linalg.pinv(design_matrix) ##problem here
y_values = np.linalg.inv(MPpi)
随时编辑此不完整的答案
在Repl上运行此代码后,出现以下错误消息
Traceback (most recent call last):
File "main.py", line 32, in <module>
y_values = np.linalg.inv(MPpi)
File "<__array_function__ internals>", line 5, in inv
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.8/site-packages/numpy/linalg/linalg.py", line 542, in inv
_assert_stacked_square(a)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.8/site-packages/numpy/linalg/linalg.py", line 213, in _assert_stacked_square
raise LinAlgError('Last 2 dimensions of the array mustbe square')
numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square
第一个错误是通过取MPpi
的倒数传播的>
通过查看文档,似乎pinv
切换了最后两个维度[例如,m
x n
矩阵变为n
x m
],因此我们需要在格式化矩阵之前计算伪逆]]
就Moore Penrose逆AKA pinv
而言,this article建议乘以MPpi*data
,这将产生x_0 {来自Ross MacAusland的符号},这是最适合最小二乘回归的方法。