【问题标题】:IndexError: tuple index out of range to split features and labelIndexError:元组索引超出范围以拆分特征和标签
【发布时间】:2020-10-12 09:03:42
【问题描述】:

尝试从 DATASET 中拆分要素和标签时出现错误。代码如下:

print("Persiapan data")
#Split features and label from DATASET 
X = [] #features
Y = [] #labels
x_train,y_train=[],[]
for features,label in vektor_input:
    X.append(features)
    Y.append(label)
    
#Split X,Y to train and test
x_train,x_test,y_train,y_test = train_test_split(X, Y, train_size=0.7)

x_train = np.array(x_train)
x_train = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1]))
x_test = np.array(x_test)
x_test = np.reshape(x_test, (x_test.shape[0], 1, x_test.shape[1]))


print("Ukuran x_train :",len(x_train))
print("Ukuran x_test  :",len(x_test))

错误显示。我是 python 新手。请帮忙,我已尝试修复它,但出现了一些错误并卡住了。

IndexError Traceback (most recent call
 last) <ipython-input-12-cd5441347f88> in <module>
      12 
      13 x_train = np.array(x_train)
 ---> 14 x_train = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1]))
      15 x_test = np.array(x_test)
      16 x_test = np.reshape(x_test, (x_test.shape[0], 1, x_test.shape[1]))
  IndexError: tuple index out of range

【问题讨论】:

  • x_trainy_train 是数组,对吧?所以形状只有一维而不是 2。
  • 是的,就是数组。好的,我试试

标签: python numpy tensorflow keras recurrent-neural-network


【解决方案1】:

假设 np_array 是一维数组。

当使用 a 的 np_array.shape 时,您将得到输出为 -> ( 行数 , )
所以 np_array.shape[1] 给你错误“IndexError: tuple index out of range”

要解决这个问题,请根据需要使用整数值而不是 np_array.shape[1]。 (注意:输入和输出数组的元素总数应该相同)

例如:

num = 2 # change this according to required output 
x_train = np.reshape(x_train, (int(x_train.shape[0]/num), 1, num))

【讨论】:

  • 这确实有效,谢谢!但是如果我将 'the num = 2' 更改为 3 输出,我又遇到了错误。 ValueError:无法将大小为 52 的数组重新整形为形状 (17,1,3)。为什么?
  • 您正在处理的 x_train 的形状是什么? @futomo
  • 我的 x_train.shape (48,5200)
  • 在您的问题中输入 x_train 是一维数组,对吗?那么它的形状应该是(行数,)
  • 您必须根据输入形状和输出形状修改代码。参考:link
猜你喜欢
  • 2013-07-28
  • 2018-11-16
  • 2017-07-12
  • 2013-12-16
  • 2021-12-21
  • 2014-08-01
  • 2021-04-19
  • 1970-01-01
相关资源
最近更新 更多