[Python] How to make a Python program to predict the next outcome of a game (of picking a...

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I wanted to make a program in Python using the LSTM technique that can predict the next outcome or say probability of a picking a color out of two. The program should use AI and machine learning libraries, to read the pattern of the last 40 outcomes and hence predict the next outcome.

    I have made the following program in regard to it.

    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 the user to enter a 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))


    But I am getting the following error constantly when executing it:

    C:\Users\Ashish\miniconda3\python.exe C:\Users\Ashish\Desktop\pyt_pract\test_prob1.py
    Enter the ball color sequence of length 40 (e.g. rrggrrgrrgggrgrgrrggggrgrgrrgrgggrrgggg): rgggrrgrgrggrrgrgrgrgrggggrrrrggrrggrgrg
    Traceback (most recent call last):
    File "C:\Users\Ashish\Desktop\pyt_pract\test_prob1.py", line 50, in <module>
    print("Prediction : ", predict_next_color_lstm(ball_seq))
    File "C:\Users\Ashish\Desktop\pyt_pract\test_prob1.py", line 23, in predict_next_color_lstm
    X = np.reshape(X, (X.shape[0], X.shape[1], 1))
    IndexError: tuple index out of range

    Continue reading...

Compartilhe esta Página