我试图使用线性回归系数生成对角矩阵。首先我生成了一个空矩阵。然后从回归模型中提取系数。下面是我的代码:
P = np.zeros((ncol, ncol), dtype = int)
intercep = np.zeros((1, ncol), dtype = int)
my_pls = PLSRegression(n_components = ncomp, scale=False)
model = my_pls.fit(x, y)
#extract pls coeffeicient:
coef = model.coef_
intercep = model.y_mean_ - (model.x_mean_.dot(coef))
P[(i-k):(i+k), i-k] = np.diag(coef[0:ncol])
但是运行代码后我得到了零矩阵。谁能告诉我如何从回归系数中得到对角矩阵?
不确定为什么需要声明P
你可以使用numpy.diag
x=[3,5,6,7]
numpy.diag(x)
输出:
array([[3, 0, 0, 0],
[0, 5, 0, 0],
[0, 0, 6, 0],
[0, 0, 0, 7]])
针对您的情况,尝试P=np.diag(coef)