Problem with training neural network to recognize chess openning

I am making neural network with recognize chess opening. For smaller sequence for example 8 moves usually i get correct opening name but for larger at least 10 characters i get wrong name. I think it is because accuracy is to low to correctly recognize opening

Epoch 50/50

36/36 ━━━━━━━━━━━━━━━━━━━━ 0s 6ms/step – accuracy: 0.7364 – loss: 0.6811 – val_accuracy: 0.0199 – val_loss: 20.6356

24/24 – 0s – 3ms/step – accuracy: 0.0199 – loss: 20.6356

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import re
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
#Function to divide the string into array
def divide_string_into_array(text):
lines = text.strip().split('n')
return lines
#Load data
data = pd.read_csv('openings.csv')
moves = data['Moves'].to_string(index=False)
moves = re.sub(r'd+.', '', moves)
arrayOfMoves = divide_string_into_array(moves)
arrayOfMoves = [move.strip() for move in arrayOfMoves]
#Prepare final data
finalData = []
for i in range(len(data)):
finalData.append({"evidence": arrayOfMoves[i], "label": data['Opening'].iloc[i]})
#Split evidence and labels
evidence = [row["evidence"] for row in finalData]
labels = [row["label"] for row in finalData]
#Tokenize the text data
tokenizer = Tokenizer()
tokenizer.fit_on_texts(evidence)
x_sequences = tokenizer.texts_to_sequences(evidence)
#Pad sequences to ensure uniform length
max_sequence_length = max(len(seq) for seq in x_sequences)
x_padded = pad_sequences(x_sequences, maxlen=max_sequence_length)
#Encode labels to numerical values
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(labels)
#Split data into training and testing sets
x_training, x_testing, y_training, y_testing = train_test_split(
x_padded, y_encoded, test_size=0.4
)
#Define the model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Embedding(input_dim=len(tokenizer.word_index) + 1, output_dim=128, input_length=max_sequence_length))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation="relu"))
model.add(tf.keras.layers.Dense(len(np.unique(y_encoded)), activation="softmax"))
#Compile the model
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
#Train the model
model.fit(x_training, y_training, epochs=50, validation_data=(x_testing, y_testing))
#Evaluate the model
model.evaluate(x_testing, y_testing, verbose=2)
#Function which predict
def predict_opening(moves, tokenizer, model, label_encoder, max_sequence_length):
moves = re.sub(r'd+.', '', moves)
moves = moves.strip()
sequence = tokenizer.texts_to_sequences([moves])
padded_sequence = pad_sequences(sequence, maxlen=max_sequence_length)
prediction = model.predict(padded_sequence)
predicted_label = label_encoder.inverse_transform([np.argmax(prediction)])
return predicted_label[0]
#Change new_moves to new chees move
new_moves = "d4 d5 c4 e5 dxe5 d4 Nf3 Nc6 Nbd2"
predicted_opening = predict_opening(new_moves, tokenizer, model, label_encoder, max_sequence_length)
print(f"The predicted opening for the moves '{new_moves}' is: {predicted_opening}")
</code>
<code>import re import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences #Function to divide the string into array def divide_string_into_array(text): lines = text.strip().split('n') return lines #Load data data = pd.read_csv('openings.csv') moves = data['Moves'].to_string(index=False) moves = re.sub(r'd+.', '', moves) arrayOfMoves = divide_string_into_array(moves) arrayOfMoves = [move.strip() for move in arrayOfMoves] #Prepare final data finalData = [] for i in range(len(data)): finalData.append({"evidence": arrayOfMoves[i], "label": data['Opening'].iloc[i]}) #Split evidence and labels evidence = [row["evidence"] for row in finalData] labels = [row["label"] for row in finalData] #Tokenize the text data tokenizer = Tokenizer() tokenizer.fit_on_texts(evidence) x_sequences = tokenizer.texts_to_sequences(evidence) #Pad sequences to ensure uniform length max_sequence_length = max(len(seq) for seq in x_sequences) x_padded = pad_sequences(x_sequences, maxlen=max_sequence_length) #Encode labels to numerical values label_encoder = LabelEncoder() y_encoded = label_encoder.fit_transform(labels) #Split data into training and testing sets x_training, x_testing, y_training, y_testing = train_test_split( x_padded, y_encoded, test_size=0.4 ) #Define the model model = tf.keras.models.Sequential() model.add(tf.keras.layers.Embedding(input_dim=len(tokenizer.word_index) + 1, output_dim=128, input_length=max_sequence_length)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128, activation="relu")) model.add(tf.keras.layers.Dense(len(np.unique(y_encoded)), activation="softmax")) #Compile the model model.compile( optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"] ) #Train the model model.fit(x_training, y_training, epochs=50, validation_data=(x_testing, y_testing)) #Evaluate the model model.evaluate(x_testing, y_testing, verbose=2) #Function which predict def predict_opening(moves, tokenizer, model, label_encoder, max_sequence_length): moves = re.sub(r'd+.', '', moves) moves = moves.strip() sequence = tokenizer.texts_to_sequences([moves]) padded_sequence = pad_sequences(sequence, maxlen=max_sequence_length) prediction = model.predict(padded_sequence) predicted_label = label_encoder.inverse_transform([np.argmax(prediction)]) return predicted_label[0] #Change new_moves to new chees move new_moves = "d4 d5 c4 e5 dxe5 d4 Nf3 Nc6 Nbd2" predicted_opening = predict_opening(new_moves, tokenizer, model, label_encoder, max_sequence_length) print(f"The predicted opening for the moves '{new_moves}' is: {predicted_opening}") </code>
import re
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

#Function to divide the string into array
def divide_string_into_array(text):
    lines = text.strip().split('n')
    return lines

#Load data
data = pd.read_csv('openings.csv')
moves = data['Moves'].to_string(index=False)
moves = re.sub(r'd+.', '', moves)
arrayOfMoves = divide_string_into_array(moves)
arrayOfMoves = [move.strip() for move in arrayOfMoves]

#Prepare final data
finalData = []
for i in range(len(data)):
    finalData.append({"evidence": arrayOfMoves[i], "label": data['Opening'].iloc[i]})

#Split evidence and labels
evidence = [row["evidence"] for row in finalData]
labels = [row["label"] for row in finalData]

#Tokenize the text data
tokenizer = Tokenizer()
tokenizer.fit_on_texts(evidence)
x_sequences = tokenizer.texts_to_sequences(evidence)

#Pad sequences to ensure uniform length
max_sequence_length = max(len(seq) for seq in x_sequences)
x_padded = pad_sequences(x_sequences, maxlen=max_sequence_length)

#Encode labels to numerical values
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(labels)

#Split data into training and testing sets
x_training, x_testing, y_training, y_testing = train_test_split(
    x_padded, y_encoded, test_size=0.4
)

#Define the model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Embedding(input_dim=len(tokenizer.word_index) + 1, output_dim=128, input_length=max_sequence_length))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation="relu"))
model.add(tf.keras.layers.Dense(len(np.unique(y_encoded)), activation="softmax"))

#Compile the model
model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

#Train the model
model.fit(x_training, y_training, epochs=50, validation_data=(x_testing, y_testing))

#Evaluate the model
model.evaluate(x_testing, y_testing, verbose=2)

#Function which predict
def predict_opening(moves, tokenizer, model, label_encoder, max_sequence_length):
    moves = re.sub(r'd+.', '', moves)
    moves = moves.strip()
    sequence = tokenizer.texts_to_sequences([moves])
    padded_sequence = pad_sequences(sequence, maxlen=max_sequence_length)
    prediction = model.predict(padded_sequence)
    predicted_label = label_encoder.inverse_transform([np.argmax(prediction)])
    return predicted_label[0]


#Change new_moves to new chees move
new_moves = "d4 d5 c4 e5 dxe5 d4 Nf3 Nc6 Nbd2"
predicted_opening = predict_opening(new_moves, tokenizer, model, label_encoder, max_sequence_length)
print(f"The predicted opening for the moves '{new_moves}' is: {predicted_opening}")

I tried to change layers, change number of neurons in layers

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật