列表索引超出范围:Python,Tensorflow RNN

时间:2017-09-28 11:56:38

标签: python indexing tensorflow

列表索引超出范围时出错。我认为这是因为我预测下一个数字。我跟随这篇文章https://chunml.github.io/ChunML.github.io/project/Creating-Text-Generator-Using-Recurrent-Neural-Network/作为预测列表中下一个数字的基础,但我正在努力调整这些想法。

data = ['1','0','0','1','4','2','6','1','1','0','0','1','4','2']
chars = list(set(data))

VOCAB_SIZE= len(chars)
number_of_sequences= 1
SEQ_LENGTH=2
#Prepare training data

ix_to_char={ix:char for ix, char in enumerate(chars)}
char_to_ix={char:ix for ix, char in enumerate(chars)}

X= np.zeros((len(data)/SEQ_LENGTH, SEQ_LENGTH, VOCAB_SIZE))
y= np.zeros((len(data)/SEQ_LENGTH, SEQ_LENGTH, VOCAB_SIZE))

for i in range(len(data)/SEQ_LENGTH):
    X_sequence = data[i*SEQ_LENGTH:(i+1)*SEQ_LENGTH]
    X_sequence_ix=[char_to_ix[value] for value in X_sequence]
    input_sequence= np.zeros((SEQ_LENGTH, VOCAB_SIZE))

    for j in range(0,SEQ_LENGTH):
        input_sequence[j][X_sequence_ix[j]]=1
    X[i]=input_sequence

    y_sequence = data[i*(SEQ_LENGTH+1):(i+1)*(SEQ_LENGTH+1)]
    y_sequence_ix = [char_to_ix[value] for value in y_sequence]
    target_sequence= np.zeros((SEQ_LENGTH, VOCAB_SIZE))

    for j in range(0,SEQ_LENGTH):
        target_sequence[j][y_sequence_ix[j]]=1 #LIST INDEX OUT OF RANGE

    y[i]=target_sequence

欢迎任何帮助!

1 个答案:

答案 0 :(得分:0)

在for循环中使用if语句循环,以防止代码将列表编入索引范围之外。

使用如下条件:

for i in range(len(data)/SEQ_LENGTH): if ((i+1)*SEQ_LENGTH) < len(data): X_sequence = data[i*SEQ_LENGTH:(i+1)*SEQ_LENGTH]