【发布时间】:2021-10-30 18:16:55
【问题描述】:
我是一名学生,正在开始线性回归。我们一直采用手动回归公式: (X.T * X) **-1 * X.T * y 我们也有一个简单数组的例子:
from numpy.linalg import inv
import numpy as np
from matplotlib import pyplot as plt
X = np.array([[1, 50], [1, 60], [1, 70], [1, 100]]) # it MUST have this 1... a trivial variable... i don't understand for what
y = np.array([[10], [30], [40], [50]])
w = inv((X.T).dot(X)).dot(X.T).dot(y)
print(f'w_1 = {round(w[0][0], 2)},\nw_2 = {round(w[1][0], 3)}')
X_min = X[:, 1].min()
X_max = X[:, 1].max()
X_support = np.linspace(X_min, X_max, num=100)
Y_model = w[0][0] + w[1][0] * X_support
plt.scatter(x=X[:, 1], y=Y, color='g', alpha=0.8)
plt.plot(X_support, Y_model)
plt.show()
现在我想使用波士顿数据集对乘法变量做同样的事情。 我需要创建一个与 LinearRegression() “相同”的类。它必须有 .fit() 方法和 .predict 方法。当数组有超过 1 列时如何采取行动的解释为零......所以我很困惑。
这是我最初所做的:
from numpy.linalg import inv
import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import load_boston
class CustomLinearReg:
def __init__(self):
pass
def fit(X, y):
return inv((X.T).dot(X)).dot(X.T).dot(y)
def predict(X):
pass
boston_dataset = load_boston()
X = boston_dataset.data
y = boston_dataset.target
reg = CustomLinearReg.fit(X, y)
reg
但它只返回 1 个系数,我不确定它是否正确......我也不明白从哪里得到第二个。 在那之后,我认为我需要那个“1” - 微不足道的变量并且这样做了:
boston_dataset = load_boston()
X = boston_dataset.data.tolist()
for n1, x in enumerate(X):
for n2, y in enumerate(x):
X[n1][n2] = [1, y]
X = np.array(X)
y = boston_dataset.target
reg = CustomLinearReg.fit(X, y)
reg
但它会返回
ValueError: shapes (2,13,506) and (506,13,2) not aligned: 506 (dim 2) != 13 (dim 1)
我尝试了更多,比如在一个循环中一个一个地计算每个系数......但失败了。
请帮我解决这个问题。
我需要一个用于 .fit(X,y) 的类返回成对的系数,然后是 .predict() 方法,该方法在 .fit() 之后生成模型。
【问题讨论】:
-
你为什么要写这些行:
for n1, x in enumerate(X): for n2, y in enumerate(x): X[n1][n2] = [1, y] -
使数字数组像 [1, 2, 3, 4, 5] 看起来像 [[1, 1], [1, 2], [1, 3], [1, 4 ], [1, 5]]。添加微不足道的变量。
-
你知道这一行吗:
inv((X.T).dot(X)).dot(X.T).dot(y)当 x.shape 为506,13,2时,你正在尝试多个 3d 矩阵 -
好的,您需要将数据集拆分为 x_train 和 y_train