Python:使用带有 IndexError 的 LSTM 序列:列表分配索引超出范围

问题描述 投票:0回答:0

我正在尝试从包含 25 个整数的列表中随机选择 6 个整数,以使用 LSTM 创建和测试序列。但是,我的代码只能执行一轮,然后显示错误:IndexError: list assignment index out of range。在此代码中,我使用的是 Python 3,下面使用另一个列表显示了相同的代码并且它有效。

我使用的代码是(最后我发布输出):

`

#Libraries
import random
from numpy import array
from numpy import argmax
from keras.models import Sequential
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense
import time

# starting stamptime 
start_time = time.time()

# generate a sequence of random numbers since list
def generate_sequence(length, n_features):
    return [random.choice([3, 6, 7, 8, 11, 12, 14, 15, 17, 18, 19, 20, 22, 25, 26, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38]) for _ in range(length)]

# one hot encode sequence
def one_hot_encode(sequence, n_features):
encoding = list()
    for value in sequence:
        vector = [0 for _ in range(n_features)]
        vector[value] = 1
        encoding.append(vector)
    return array(encoding)

# decode a one hot encoded string
def one_hot_decode(encoded_seq):
    return [argmax(vector) for vector in encoded_seq]

# generate one example for an lstm
def generate_example(length, n_features, out_index):
    # generate sequence
    sequence = generate_sequence(length, n_features)
    print('My Sequence: %s' % sequence)
    # one hot encode
    encoded = one_hot_encode(sequence, n_features)
    print('My Encoded: %s' % encoded)
    # one hot decoded
    decoded = one_hot_decode(encoded)
    print('My Decoded: %s' % decoded)
    # reshape sequence to be 3D
    X = encoded.reshape((1, length, n_features))
    # select output
    y = encoded[out_index].reshape(1, n_features)
    return X, y

# define model
length = 6
n_features = 25
out_index = 2
model = Sequential()
model.add(LSTM(25, input_shape=(length, n_features)))
model.add(Dense(n_features, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()

# fit model
for i in range(10000):
    X, y = generate_example(length, n_features, out_index)
    model.fit(X, y, epochs=1, verbose=2)

# evaluate model
correct = 0
for i in range(100):
    X, y = generate_example(length, n_features, out_index)
    yhat = model.predict(X)
    if one_hot_decode(yhat) == one_hot_decode(y):
        correct += 1
print('Accuracy: %f' % ((correct/100.0)*100.0))

# prediction on new data
X, y = generate_example(length, n_features, out_index)
yhat = model.predict(X)
print('Sequence: %s' % [one_hot_decode(x) for x in X])
print('Expected: %s' % one_hot_decode(y))
print('Predicted: %s' % one_hot_decode(yhat))
seconds = time.time() - start_time
print('Time Taken:', time.strftime("%H:%M:%S",time.gmtime(seconds)))
`

我得到的输出是:

`Model: "sequential_19"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 lstm_19 (LSTM)              (None, 25)                5100      
                                                                 
 dense_19 (Dense)            (None, 25)                650       
                                                                 
=================================================================
Total params: 5,750
Trainable params: 5,750
Non-trainable params: 0
_________________________________________________________________
My Sequence: [17, 3, 15, 20, 14, 19]
My Encoded: [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0]]
My Decoded: [17, 3, 15, 20, 14, 19]
1/1 - 1s - loss: 3.2120 - accuracy: 0.0000e+00 - 1s/epoch - 1s/step
My Sequence: [17, 12, 38, 30, 8, 14]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_8464\3943003283.py in <module>
     57 # fit model
     58 for i in range(10000):
---> 59     X, y = generate_example(length, n_features, out_index)
     60     model.fit(X, y, epochs=1, verbose=2)
     61 

~\AppData\Local\Temp\ipykernel_8464\3943003283.py in generate_example(length, n_features, out_index)
     34     print('My Sequence: %s' % sequence)
     35     # one hot encode
---> 36     encoded = one_hot_encode(sequence, n_features)
     37     print('My Encoded: %s' % encoded)
     38     # one hot decoded

~\AppData\Local\Temp\ipykernel_8464\3943003283.py in one_hot_encode(sequence, n_features)
     20     for value in sequence:
     21         vector = [0 for _ in range(n_features)]
---> 22         vector[value] = 1
     23         encoding.append(vector)
     24     return array(encoding)

IndexError: list assignment index out of range`

有人可以帮我吗?

问候, 亚历杭德罗·乌里韦

见上面的描述,那里有 Python 代码和输出。

在这种情况下代码不起作用,因为我对另一个列表使用了相同的代码并且它起作用了。请参阅下面的另一个代码工作示例和我达到的输出:

`#Libraries
import random
from numpy import array
from numpy import argmax
from keras.models import Sequential
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense
import time

# starting stamptime 
start_time = time.time()

# generate a sequence of random numbers in list
def generate_sequence(length, n_features):
    return [random.choice([4,4,1,4,3,4,1,4,4,4,-2,3,4,4,1,4]) for _ in range(length)]

# one hot encode sequence
def one_hot_encode(sequence, n_features):
    encoding = list()
    for value in sequence:
        vector = [0 for _ in range(n_features)]
        vector[value] = 1
        encoding.append(vector)
    return array(encoding)

# decode a one hot encoded string
def one_hot_decode(encoded_seq):
    return [argmax(vector) for vector in encoded_seq]

# generate one example for an lstm
def generate_example(length, n_features, out_index):
    # generate sequence
    sequence = generate_sequence(length, n_features)
    print('My Sequence: %s' % sequence)
    # one hot encode
    encoded = one_hot_encode(sequence, n_features)
    print('My Encoded: %s' % encoded)
    # one hot decoded
    decoded = one_hot_decode(encoded)
    print('My Decoded: %s' % decoded)
    # reshape sequence to be 3D
    X = encoded.reshape((1, length, n_features))
    # select output
    y = encoded[out_index].reshape(1, n_features)
    return X, y

# define model
length = 5
n_features = 16
out_index = 2
model = Sequential()
model.add(LSTM(25, input_shape=(length, n_features)))
model.add(Dense(n_features, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()

# fit model
for i in range(10000):
    X, y = generate_example(length, n_features, out_index)
    model.fit(X, y, epochs=1, verbose=2)

# evaluate model
correct = 0
for i in range(100):
    X, y = generate_example(length, n_features, out_index)
    yhat = model.predict(X)
    if one_hot_decode(yhat) == one_hot_decode(y):
        correct += 1
print('Accuracy: %f' % ((correct/100.0)*100.0))

# prediction on new data
X, y = generate_example(length, n_features, out_index)
yhat = model.predict(X)
print('Sequence: %s' % [one_hot_decode(x) for x in X])
print('Expected: %s' % one_hot_decode(y))
print('Predicted: %s' % one_hot_decode(yhat))
seconds = time.time() - start_time
print('Time Taken:', time.strftime("%H:%M:%S",time.gmtime(seconds)))
`

这是我达到的输出:

`Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 lstm (LSTM)                 (None, 25)                4200      
                                                                 
 dense (Dense)               (None, 16)                416       
                                                                 
=================================================================
Total params: 4,616
Trainable params: 4,616
Non-trainable params: 0
_________________________________________________________________
My Sequence: [4, 4, -2, 4, 4]
My Encoded: [[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]]
My Decoded: [4, 4, 14, 4, 4]
1/1 - 1s - loss: 2.7330 - accuracy: 0.0000e+00 - 1s/epoch - 1s/step
My Sequence: [4, 4, 4, 4, 4]
My Encoded: [[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]]
My Decoded: [4, 4, 4, 4, 4]
1/1 - 0s - loss: 2.8146 - accuracy: 0.0000e+00 - 3ms/epoch - 3ms/step
My Sequence: [4, 4, 4, 4, 1]
My Encoded: [[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
My Decoded: [4, 4, 4, 4, 1]
1/1 - 0s - loss: 2.8386 - accuracy: 0.0000e+00 - 4ms/epoch - 4ms/step
My Sequence: [4, 3, 4, 4, 4]
My Encoded: [[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]]
My Decoded: [4, 3, 4, 4, 4]
1/1 - 0s - loss: 2.8176 - accuracy: 0.0000e+00 - 4ms/epoch - 4ms/step`

等最后如下:

`Accuracy: 100.000000
My Sequence: [-2, 1, 4, 4, 4]
My Encoded: [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0]
 [0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]]
My Decoded: [14, 1, 4, 4, 4]
1/1 [==============================] - 0s 16ms/step
Sequence: [[14, 1, 4, 4, 4]]
Expected: [4]
Predicted: [4]
Time Taken: 00:07:46`
python-3.x arraylist lstm sequence
© www.soinside.com 2019 - 2024. All rights reserved.