错误元组索引超出矩阵预处理范围

Error tuple index out of range for matrix preprocess

我正在尝试 运行 用户定义的函数通过添加带有“1”的列来处理矩阵

  def updated_x (input_x):
        if input_x.shape[0] < input_x.shape[1]:
            input_x = np.transpose(input_x)
          
        ones = np.ones((len(input_x), 1), dtype=int)
        updated_x = np.concatenate((ones, input_x), axis=1)
        return updated_x 

我有以下输入值:

input2 = np.array([5,4,6])
input1 = np.array([[5,4,8,9],[5,5,5,6]])
input3 = np.array([[2,4],[1,2],[2,3],[4,12]])

for i in [input1, input2, input3]:
            print(updated_x(i), )

三个数组中有两个数组出错

[[ 1  2  4]
 [ 1  3  5]
 [ 1  6  7]
 [ 1  9 10]]

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-117-8fc2b754194b> in <module>
      1 for i in [input1, input2, input3]:
----> 2             print(updated_x(i), )

<ipython-input-115-41916a0377b0> in updated_x(input_x)
      4 
      5 def updated_x(input_x):
----> 6     if input_x.shape[0] < input_x.shape[1]:
      7         input_x = np.transpose(input_x)
      8 

IndexError: tuple index out of range

input2 的形状为 (3,)。尝试在函数调用之前重塑它:

input2 = input2.reshape(1,-1)

或者在函数体的开头添加一些校验码:

def updated_x (input_x):

    if len(input_x.shape)<2:
        input_x = input_x.reshape(1,-1)
    #..........
    #..........