如何用Python创建设计矩阵?

2024-06-02 08:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用NumPy为线性回归函数创建一个设计矩阵。以下是我目前掌握的代码:

import numpy as np

def linReg(n, parameter):
  X = np.arange(0, n, 1)*2/n
  Y = (X * parameter) + np.random.randn(1)

  return X, Y

我不能完全确定我的X设计矩阵变量是否正确。如何向其中添加一列1?我应该使用np.append吗


Tags: 函数代码importnumpyparameterdefasnp
2条回答

首先,使用numpy.ones
创建具有正确维度的向量 假设您的矩阵称为mat:

n,m = mat.shape # gives you the dimensions of your matrix
ones_vector = np.ones((n,1)) #create a vector of ones same y dimension as your matrix

现在可以使用numpy.hstackDoc)将向量附加到矩阵中

res_front = np.hstack((ones_vector,mat)) # add it to the front
res_back = np.hstack((mat,ones_vector)) # add it to the back

编辑:
因此,您的结果如下所示(简化):

print(mat)
[[ 0.2  0.3]
 [ 0.1  0.2]]

print(ones_vector)
[[ 1.]
 [ 1.]]

print(res_back)
[[ 0.2  0.3  1. ]
 [ 0.1  0.2  1. ]]

通过numpy.ones()创建一个形状类似于aones数组 然后使用vstack()将它们vertically堆叠起来

import numpy as np

def linReg(n, parameter):
  a = np.arange(0, n, 1)*2/n
  i = np.ones(a.shape)
  X = np.vstack((i, a))
  Y = (X * parameter) + np.random.randn(1)
  return X, Y

X看起来像这样

array([[1. , 1. , 1. , 1. ],
       [0. , 0.5, 1. , 1.5]])

和Y

array([[ 2.19576216,  2.19576216,  2.19576216,  2.19576216],
       [-0.80423784,  0.69576216,  2.19576216,  3.69576216]])

相关问题 更多 >