使用LSTM神经网络,元组索引超出范围。 Python,Keras with Tensorflow

时间:2017-04-20 10:36:49

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

目前正在使用带有Tensorflow后端的Keras解决问题。

我正在尝试用下面的代码创建一个神经网络(最小的例子,不包括我的真实数据),尽管它给出了错误:

"元组索引超出范围"对于以下行中input_shape的大小:

model.add(TimeDistributed(LSTM(32,return_sequences=True),input_shape=trainData.shape[1:]))

错误似乎在第964行的recurrent.py文件中:

self.input_dim = input_shape[2]

它试图访问input_shape [2]。我将形状传递给只有两个数字(数据的时间序列长度和通道数)。我传递的形状是(100000,2)。

我认为这一行试图获取我尚未传递给它的索引。

所以我的问题是我应该将我的输入形状用于我的神经网络配置?

我正在使用Keras版本2.0.3和Tensorflow版本1.0.1。

编辑:recurrent.py是Keras提供的文件(我认为)。我不想开始编辑它以防我真的破坏了什么。

# import the necessary packages
from sklearn.cross_validation import train_test_split
from keras.models import Sequential
from keras.layers import Activation
from keras.optimizers import SGD
from keras.layers import LSTM
from keras.layers.wrappers import TimeDistributed
from keras.utils import np_utils
import numpy as np
numClasses = 10
time_points = 100000
num_chans = 2

iq = np.empty((time_points,0,1), int)# creates empty numpy array.
labels = np.empty([0,1])

raw_data = np.random.rand(500,time_points,num_chans)
labels = np.random.randint(numClasses, size=(500, 1))
one_hot_labels = np_utils.to_categorical(labels, num_classes=None)

print(one_hot_labels.shape)

# partition the data into training and testing splits, using 75%
# of the data for training and the remaining 25% for testing
print("[INFO] constructing training/testing split...")
(trainData, testData, trainLabels, testLabels) = train_test_split(
raw_data, one_hot_labels, test_size=0.25, random_state=42)

trainLabels = trainLabels.reshape(375,10,1)
testLabels = testLabels.reshape(125,10,1)

print(trainData.shape)
print(testData.shape)
print(trainLabels.shape)
print(testLabels.shape)
print(len(trainData.shape))

# define the architecture of the network
model = Sequential()
# Long short term memory experiment
model.add(TimeDistributed(LSTM(32, return_sequences=True),input_shape=trainData.shape[1:]))
model.add(TimeDistributed(LSTM(10, return_sequences=True)))
model.add(Activation("softmax"))

print(trainData.shape)
print(trainLabels.shape)

## train the model using SGD
print("[INFO] compiling model...")
sgd = SGD(lr=0.01)
model.compile(loss="sparse_categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])
model.fit(trainData, trainLabels)

## show the accuracy on the testing set
print("[INFO] evaluating on testing set...")
(loss, accuracy) = model.evaluate(testData, testLabels, batch_size=128, verbose=1)
print("[INFO] loss={:.4f}, accuracy: {:.4f}%".format(loss, accuracy * 100))

2 个答案:

答案 0 :(得分:1)

尝试使用 input_shape=trainData.shape[0:],因为在 python 中元组索引将从 0 开始。

答案 1 :(得分:0)

当访问元组或python(和大多数编程语言)中的数组时,计数从0开始,而不是1.

因此,尝试访问input_shape[2]实际上是input_shape中的第三个​​项目。