我想使用 LSTM 技术在 python 中编写一个程序,可以预测下一个结果,或者说从两种颜色中选择一种颜色的概率,该程序应该使用 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 est_prob1.py 输入长度为 40 的球颜色序列(例如 rrggrrgrrgggrgrgrggrrggggrgrgrrgrgggrrgggg): rgggrrgrgrggrrgrgrgrggggrrrrggrrggrgrg 回溯(最近一次调用最后一次): 文件“C:\Users\Ashish\Desktop\pyt_pract est_prob1.py”,第 50 行,位于 打印(“预测:”,predict_next_color_lstm(ball_seq)) 文件“C:\ Users \ Ashish \ Desktop \ pyt_pract est_prob1.py”,第23行,在predict_next_color_lstm中 X = np.reshape(X, (X.shape[0], X.shape[1], 1)) IndexError:元组索引超出范围
错误消息“IndexError:元组索引超出范围”表明X数组的形状存在问题。具体来说,X 的尺寸似乎不是我们期望的那样。
错误的一个可能原因是
seq
的长度小于40,这会导致X数组为空。要解决此问题,您可以添加一项检查,以确保在创建 40 个结果的滚动窗口之前,seq
的长度至少为 40:
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 = []
if len(seq) >= 40:
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'
else:
return "Error: Number of outcomes provided is less than 40."
兄弟,这个模型适用于您使用它的颜色预测网站吗?