Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,7 @@ import csv
|
|
| 4 |
import numpy as np
|
| 5 |
import tensorflow as tf
|
| 6 |
import gradio as gr
|
| 7 |
-
from tensorflow.keras.models import Sequential
|
| 8 |
from tensorflow.keras.layers import LSTM, Dense, Embedding
|
| 9 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 10 |
from tensorflow.keras.preprocessing.text import Tokenizer
|
|
@@ -13,12 +13,15 @@ from tensorflow.keras.preprocessing.text import Tokenizer
|
|
| 13 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 14 |
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# Mapping choices to numerical values
|
| 17 |
choices = {'rock': 0, 'paper': 1, 'scissors': 2}
|
| 18 |
rev_choices = {0: 'rock', 1: 'paper', 2: 'scissors'}
|
| 19 |
|
| 20 |
# Ensure CSV exists
|
| 21 |
-
csv_filename = "game_moves.csv"
|
| 22 |
if not os.path.exists(csv_filename):
|
| 23 |
with open(csv_filename, mode='w', newline='') as file:
|
| 24 |
writer = csv.writer(file)
|
|
@@ -26,12 +29,12 @@ if not os.path.exists(csv_filename):
|
|
| 26 |
|
| 27 |
def get_computer_choice(model, past_moves):
|
| 28 |
""" Predicts player's next move and counteracts it. """
|
| 29 |
-
if len(past_moves) <
|
| 30 |
return random.choice(["rock", "paper", "scissors"])
|
| 31 |
|
| 32 |
# Prepare input data for prediction
|
| 33 |
-
sequence = [choices[move] for move in past_moves[-
|
| 34 |
-
sequence = pad_sequences([sequence], maxlen=
|
| 35 |
|
| 36 |
prediction = model.predict(sequence, verbose=0)
|
| 37 |
predicted_choice = rev_choices[np.argmax(prediction)]
|
|
@@ -69,30 +72,37 @@ def load_data():
|
|
| 69 |
|
| 70 |
def train_lstm_model(data):
|
| 71 |
""" Trains an LSTM model to predict the player's next move. """
|
| 72 |
-
if len(data) <
|
| 73 |
return None # Not enough data for meaningful training
|
| 74 |
|
| 75 |
tokenizer = Tokenizer(num_words=3)
|
| 76 |
tokenizer.fit_on_texts(data)
|
| 77 |
sequences = tokenizer.texts_to_sequences(data)
|
| 78 |
|
| 79 |
-
X = pad_sequences(sequences, maxlen=
|
| 80 |
y = np.array([choices[move] for move in data[1:]])
|
| 81 |
-
|
| 82 |
model = Sequential([
|
| 83 |
-
Embedding(input_dim=3, output_dim=10, input_length=
|
| 84 |
-
LSTM(
|
| 85 |
Dense(3, activation="softmax")
|
| 86 |
])
|
| 87 |
model.compile(loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
|
| 88 |
-
|
| 89 |
if len(X) > 1:
|
| 90 |
-
model.fit(X[:-1], y, epochs=
|
|
|
|
|
|
|
| 91 |
return model
|
| 92 |
|
| 93 |
-
# Load past moves
|
| 94 |
past_moves = load_data()
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
def play_game(player_choice):
|
| 98 |
""" Handles the game logic and returns the result. """
|
|
@@ -113,8 +123,8 @@ def play_game(player_choice):
|
|
| 113 |
save_move(player_choice, computer_choice, result)
|
| 114 |
past_moves.append(player_choice)
|
| 115 |
|
| 116 |
-
# Retrain the model
|
| 117 |
-
if len(past_moves) >=
|
| 118 |
model = train_lstm_model(past_moves)
|
| 119 |
|
| 120 |
return f"Computer chose: {computer_choice}\n{result}"
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
import tensorflow as tf
|
| 6 |
import gradio as gr
|
| 7 |
+
from tensorflow.keras.models import Sequential, load_model
|
| 8 |
from tensorflow.keras.layers import LSTM, Dense, Embedding
|
| 9 |
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 10 |
from tensorflow.keras.preprocessing.text import Tokenizer
|
|
|
|
| 13 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 14 |
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
|
| 15 |
|
| 16 |
+
# File paths
|
| 17 |
+
csv_filename = "game_moves.csv"
|
| 18 |
+
model_filename = "lstm_model.h5"
|
| 19 |
+
|
| 20 |
# Mapping choices to numerical values
|
| 21 |
choices = {'rock': 0, 'paper': 1, 'scissors': 2}
|
| 22 |
rev_choices = {0: 'rock', 1: 'paper', 2: 'scissors'}
|
| 23 |
|
| 24 |
# Ensure CSV exists
|
|
|
|
| 25 |
if not os.path.exists(csv_filename):
|
| 26 |
with open(csv_filename, mode='w', newline='') as file:
|
| 27 |
writer = csv.writer(file)
|
|
|
|
| 29 |
|
| 30 |
def get_computer_choice(model, past_moves):
|
| 31 |
""" Predicts player's next move and counteracts it. """
|
| 32 |
+
if len(past_moves) < 5: # Adjusted sequence length to 5
|
| 33 |
return random.choice(["rock", "paper", "scissors"])
|
| 34 |
|
| 35 |
# Prepare input data for prediction
|
| 36 |
+
sequence = [choices[move] for move in past_moves[-5:]]
|
| 37 |
+
sequence = pad_sequences([sequence], maxlen=5)
|
| 38 |
|
| 39 |
prediction = model.predict(sequence, verbose=0)
|
| 40 |
predicted_choice = rev_choices[np.argmax(prediction)]
|
|
|
|
| 72 |
|
| 73 |
def train_lstm_model(data):
|
| 74 |
""" Trains an LSTM model to predict the player's next move. """
|
| 75 |
+
if len(data) < 6: # Adjusted for longer training sequences
|
| 76 |
return None # Not enough data for meaningful training
|
| 77 |
|
| 78 |
tokenizer = Tokenizer(num_words=3)
|
| 79 |
tokenizer.fit_on_texts(data)
|
| 80 |
sequences = tokenizer.texts_to_sequences(data)
|
| 81 |
|
| 82 |
+
X = pad_sequences(sequences, maxlen=5) # Using longer sequences
|
| 83 |
y = np.array([choices[move] for move in data[1:]])
|
| 84 |
+
|
| 85 |
model = Sequential([
|
| 86 |
+
Embedding(input_dim=3, output_dim=10, input_length=5),
|
| 87 |
+
LSTM(30, return_sequences=False), # Increased LSTM units for better learning
|
| 88 |
Dense(3, activation="softmax")
|
| 89 |
])
|
| 90 |
model.compile(loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
|
| 91 |
+
|
| 92 |
if len(X) > 1:
|
| 93 |
+
model.fit(X[:-1], y, epochs=15, verbose=0) # Increased epochs for better training
|
| 94 |
+
model.save(model_filename) # Save trained model
|
| 95 |
+
|
| 96 |
return model
|
| 97 |
|
| 98 |
+
# Load past moves
|
| 99 |
past_moves = load_data()
|
| 100 |
+
|
| 101 |
+
# Load existing model if available
|
| 102 |
+
if os.path.exists(model_filename):
|
| 103 |
+
model = load_model(model_filename)
|
| 104 |
+
else:
|
| 105 |
+
model = train_lstm_model(past_moves) if len(past_moves) >= 6 else None
|
| 106 |
|
| 107 |
def play_game(player_choice):
|
| 108 |
""" Handles the game logic and returns the result. """
|
|
|
|
| 123 |
save_move(player_choice, computer_choice, result)
|
| 124 |
past_moves.append(player_choice)
|
| 125 |
|
| 126 |
+
# Retrain the model only when enough new data is available
|
| 127 |
+
if len(past_moves) >= 6:
|
| 128 |
model = train_lstm_model(past_moves)
|
| 129 |
|
| 130 |
return f"Computer chose: {computer_choice}\n{result}"
|