我想用Python使用LSTM技术制作一个程序,可以预测下一个结果,或者说从两个颜色中挑选一个颜色的概率,程序应该使用AI和ML库,来读取最后40个结果的模式,从而预测下一个结果。
那么我就做了如下的一个方案。
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np
def predict_next_color_lstm(outcomes):
if len(outcomes) < 40:
return "Error: Number of outcomes provided is less than 40."
# Convert string input to integer sequence
seq = [0 if x == 'r' else 1 for x in outcomes]
# Create rolling window of 40 outcomes
X = []
y = []
for i in range(len(seq) - 40):
X.append(seq[i:i + 40])
y.append(seq[i + 40])
X = np.array(X)
y = np.array(y)
# Reshape X to fit LSTM input shape
X = np.reshape(X, (X.shape[0], X.shape[1], 1))
# Create LSTM model
model = Sequential()
model.add(LSTM(50, input_shape=(40, 1)))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam')
# Train the model
model.fit(X, y, epochs=50, batch_size=32)
# Predict the next outcome
last_40 = seq[-40:]
pred = model.predict(np.array([last_40]))
return 'r' if pred < 0.5 else 'g'
def get_input():
# ask user to enter ball color sequence of length 40
ball_seq = input("Enter the ball color sequence of length 40 (e.g. rrggrrgrrgggrgrgrrggggrgrgrrgrgggrrgggg): ")
return ball_seq
# _main_
ball_seq = get_input()
print("Prediction : ", predict_next_color_lstm(ball_seq))
但是我在执行它时经常得到以下错误:
C:\Users\Ashish\miniconda3\python.exe C:\Users\Ashish\Desktop\pyt_pract\test_prob1.py输入长度为40的球色序列(e.例如:rgggrrgrgrggrrgrrgrgrgrggggrrrrggrrggrgrg Traceback(最近一次通话):文件“C:\Users\Ashish\Desktop\pyt_pract\test_prob1.py”,第50行,打印(“预测:“,predict_next_color_lstm(ball_seq))文件“C:\Users\Ashish\Desktop\pyt_pract\test_prob1.在predict_next_color_lstm中的第23行,“py”,X = np。整形(X,(X.shape[0],X.shape[1],1))IndexError:元组索引超出范围
1条答案
按热度按时间v64noz0r1#
错误消息“IndexError:tuple index out of range”表示X数组的形状有问题。具体地说,X的维数似乎不是我们所期望的那样。
错误的一个可能原因是
seq
的长度小于40,这会导致一个空的X数组。要解决这个问题,您可以添加一个检查,以确保在创建40个结果的滚动窗口之前,seq
的长度至少为40: