rana
rana

Reputation: 91

reshaping of an nparray returned "IndexError: tuple index out of range"

reshaping of an nparray returned "IndexError: tuple index out of range"

Following "https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/" I have made a dataframe from the csv file. Then taken those values into an nparray "dataset". Scaled the dataset then divided into train and test set. Made two columns (trainX, trainY) with the values and its 1 lagged vales. Then tried to reshape trainX.

dataset = passenger_data.values
dataset = dataset.astype('float32')
scale = MinMaxScaler(feature_range=(0,1))
dataset = scale.fit_transform(dataset)

train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]
train_size = int(len(dataset) * 0.70)
train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]

def create_coloumns(dataset, lag = 1):
    colX, colY = [], []
    for i in range(len(dataset) - lag):
        a = dataset[i,0]
        colX.append(a)
    for j in range(lag, len(dataset)):
        b = dataset[j,0]
        colY.append(b)
    return np.array(colX), np.array(colY)

trainX, trainY = create_coloumns(train, 1)
testX, testY = create_coloumns(test, 1)

trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-62-96b89321dd69> in <module>
      1 # trainX.shape
----> 2 trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
      3 # testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

IndexError: tuple index out of range

Upvotes: 1

Views: 10526

Answers (2)

Manumerous
Manumerous

Reputation: 527

If you really needed to use both shape[0] and shape[1], you could use np.atleast_2d() function to ensure that shape has two entries. This could for example be useful if you program a function that should work for both one- and two-dimensional arrays.

You could use it the following way:

a = np.array([1,2,3,4])
a = np.atleast_2d(a)
print(a.shape) # --> (1, 4)

Upvotes: 3

Antti A
Antti A

Reputation: 692

Unlike in Matlab, numpy arrays can be one-dimensional, so there is only one value from shape parameter.

a = np.array([1,2,3,4])
a.shape[0] # ok
a.shape[1] # error

Upvotes: 3

Related Questions