I have this code for a python app to create language, code: import tkinter as tk from…
- User
I have this code for a python app to create language, code: import tkinter as tk from tkinter import filedialog from keras.models import Sequential from keras.layers import Embedding, LSTM, Dense from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical import numpy as np import os import pickle from keras.layers import Masking
Data loader and preprocessor function
def preprocess_data(file_paths): tokenizer = Tokenizer()
# Load and concatenate content from all selected dataset files all_text = "" for file_path in file_paths: with open(file_path, "r", encoding="utf-8") as file: text = file.read() all_text += text + "\n" # Ensure separation between files’ content sentences = all_text.split("\n") tokenizer.fit_on_texts(sentences) sequences = tokenizer.texts_to_sequences(sentences) # Check if we’re using a fixed sequence length if sequence_choice_var.get(): # Read the fixed sequence length from the respective entry field sequence_length = int(entry_fixed_length.get()) padded_sequences = pad_sequences(sequences, maxlen=sequence_length, padding="pre") else: # Minimal sequence length, could also eliminate the minimum length condition sequence_length = min(len(seq) for seq in sequences if len(seq) > 1) padded_sequences = sequences big_sequence = [token for seq in sequences for token in seq] input_sequences, output_words = [], [] # Assign a sequence length based on the shortest sentence # Note: for better training with variable lengths, consider using sentences directly and/or padding at the end of each batch sequence_length = min(len(seq) for seq in sequences if len(seq) > 1) for i in range(len(big_sequence) - sequence_length): input_sequences.append(big_sequence[i:i + sequence_length]) output_words.append(big_sequence[i + sequence_length]) # Remove pad_sequences call - handle varying sequence lengths directly in the model using masking or by padding at batch end vocab_size = len(tokenizer.word_index) + 1 output_words = np.array(output_words) output_words = to_categorical(output_words, num_classes=vocab_size) return np.array(input_sequences), output_words, vocab_size, tokenizerFunction to train and save the model
def train_model(): num_layers = int(entry_layers.get()) layer_size = int(entry_size.get()) model_name = entry_name.get() epochs = int(entry_epochs.get()) data_paths = root.filenames # Changed to accept multiple filenames
# Preprocess the data input_sequences, output_words, vocab_size, tokenizer = preprocess_data(data_paths) tokenizer_path = os.path.join('tokenizers', f'{model_name}_tokenizer.pickle') if not os.path.exists('tokenizers'): os.makedirs('tokenizers') with open(tokenizer_path, 'wb') as handle: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) print(f"Tokenizer saved at {tokenizer_path}") # Also save the sequence length if fixed if sequence_choice_var.get(): with open(tokenizer_path, "wb") as handle: pickle.dump((tokenizer, sequence_length), handle, protocol=pickle.HIGHEST_PROTOCOL) else: with open(tokenizer_path, "wb") as handle: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) model = Sequential() model.add(Embedding(input_dim=vocab_size, output_dim=layer_size)) if not sequence_choice_var.get(): # Add masking for variable length sequences only model.add(Masking(mask_value=0)) # Ignoring padded values (zeros) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(input_sequences, output_words, epochs=epochs) if not os.path.exists('models'): os.makedirs('models') model.save(os.path.join('models', f'{model_name}.h5')) print(f"Model {model_name} trained and saved successfully!") - Assistant
- User
Inside this function: def train_model(): num_layers = int(entry_layers.get()) layer_size = int(entry_size.get()) model_name = entry_name.get() epochs = int(entry_epochs.get()) data_paths = root.filenames # Changed to accept multiple filenames
# Preprocess the data input_sequences, output_words, vocab_size, tokenizer = preprocess_data(data_paths) with open(tokenizer_path, "wb") as handle: if sequence_choice_var.get(): # Also save sequence_length if fixed pickle.dump((tokenizer, sequence_length), handle, protocol=pickle.HIGHEST_PROTOCOL) else: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) print(f"Tokenizer saved at {tokenizer_path}") model = Sequential() model.add(Embedding(input_dim=vocab_size, output_dim=layer_size)) if not sequence_choice_var.get(): # Add masking for variable length sequences only model.add(Masking(mask_value=0)) # Ignoring padded values (zeros) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(input_sequences, output_words, epochs=epochs) if not os.path.exists('models'): os.makedirs('models') model.save(os.path.join('models', f'{model_name}.h5')) print(f"Model {model_name} trained and saved successfully!") Two variables are not defined: sequence_length and tokenizer_path - Assistant
- User
Can i make this app also support making transformer models ?
- Assistant
- User
Give me the code for this: num_heads_var.get(), dropout_var.get(), and input_sequences. You will need to define these appropriately and ensure that user input for these settings is collected and handled correctly.
- Assistant
- User
Nov give me the code for this variable and where to put it: model_type_var
- Assistant
To integrate the
model_type_varand a UI component that allows the user to choose between LSTM and Transformer models, you need to add a (or similar UI controls) in your application window. Below is how you could define and integrate the corresponding UI elements into your Tkinter app. - User
- Assistant
- User
I get this : c:\Users\Dell-PC\Desktop\Projets\Model-Creator\app-B1.py:100: SyntaxWarning: 'str' object is not callable; perhaps you missed a comma? model.compile(optimizer="adam"(), loss="categorical_crossentropy", metrics=["Accuracy"()]) c:\Users\Dell-PC\Desktop\Projets\Model-Creator\app-B1.py:100: SyntaxWarning: 'str' object is not callable; perhaps you missed a comma? model.compile(optimizer="adam"(), loss="categorical_crossentropy", metrics=["Accuracy"()])
- Assistant
The SyntaxWarning you are seeing is related to the incorrect use of parentheses after strings in the
model.compile()method call. Specifically,"adam"()and"Accuracy"()are causing the warning because the interpreter is treating"adam"and"Accuracy"as if they were functions and trying to call them due to the parentheses.Here's the corrected line without the extraneous parentheses, which should eliminate the SyntaxWarning:
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])In Keras, the
optimizerparameter is expecting a string or an optimizer instance, and themetricsparameter expects a list of strings or a list of metric instances. There is no need to add parentheses after the strings.Please update your
model.compile()call accordingly, and the warning should disappear. - User
I get this when trying to train a Transformer model: Traceback (most recent call last): File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 1921, in call return self.func(*args) File "c:\Users\Dell-PC\Desktop\Projets\Model-Creator\app-B1.py", line 96, in train_model model.add(transformer_layer) File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\trackable\base.py", line 204, in _method_wrapper result = method(self, *args, **kwargs) File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None File "C:\Users\Dell-PC\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\autograph\impl\api.py", line 459, in _call_unconverted return f(*args, **kwargs) TypeError: MultiHeadAttention.call() missing 1 required positional argument: 'value' - Assistant
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.