Certainly! Below is a Python script tailored for Google Colab that generates a vocabulary of subwords from a given dataset.txt file. The algorithm begins with all ASCII characters (0-255) and iteratively builds a vocabulary by identifying and adding the most frequent substrings, ensuring that each subword does not exceed a specified maximum length. The final vocabulary is sorted by frequency and then alphabetically before being saved to vocab.txt.
Key Features:
- ASCII Initialization: Starts with all possible ASCII characters.
- Frequency-Based Subword Extraction: Identifies the most frequent substrings to add to the vocabulary.
- Control Parameters: Allows setting
VOCAB_SIZE and MAX_WORD_LENGTH.
- Verbose Logging: Includes print statements for step-by-step debugging and tracing.
How It Works:
- Initialization: Load the dataset and initialize the vocabulary with all ASCII characters.
- Frequency Counting: Count the frequency of all possible substrings in the dataset.
- Subword Selection: Select the most frequent substrings that fit within the
MAX_WORD_LENGTH.
- Vocabulary Expansion: Add selected substrings to the vocabulary until the desired
VOCAB_SIZE is reached.
- Sorting and Saving: Sort the final vocabulary by frequency and alphabetically, then save it to
vocab.txt.
# Vocabulary Generator Script for Google Colab
# Define control parameters
VOCAB_SIZE = 1000 # Desired vocabulary size
MAX_WORD_LENGTH = 10 # Maximum length of a subword
def load_dataset(file_path):
print(f"Loading dataset from {file_path}...")
with open(file_path, 'r', encoding='utf-8') as f:
data = f.read()
print(f"Dataset loaded. Length: {len(data)} characters.")
return data
def initialize_vocab():
print("Initializing vocabulary with all ASCII characters (0-255)...")
vocab = {chr(i) for i in range(256)}
print(f"Initial vocabulary size: {len(vocab)}")
return vocab
def count_substrings(data, min_len=2, max_len=MAX_WORD_LENGTH):
print(f"Counting substrings with length between {min_len} and {max_len}...")
substring_freq = {}
data_length = len(data)
for i in range(data_length):
for l in range(min_len, max_len + 1):
if i + l <= data_length:
substr = data[i:i+l]
if substr in substring_freq:
substring_freq[substr] += 1
else:
substring_freq[substr] = 1
print(f"Found {len(substring_freq)} unique substrings.")
return substring_freq
def select_top_substrings(substring_freq, vocab, max_word_length, top_n):
print(f"Selecting top {top_n} substrings not exceeding length {max_word_length}...")
# Filter substrings that are not in vocab and do not exceed max length
filtered = {k: v for k, v in substring_freq.items() if k not in vocab and len(k) <= max_word_length}
# Sort by frequency descending
sorted_substrings = sorted(filtered.items(), key=lambda item: item[1], reverse=True)
# Select top_n
top_substrings = sorted_substrings[:top_n]
print(f"Selected {len(top_substrings)} substrings.")
return top_substrings
def build_vocabulary(data, vocab_size, max_word_length):
vocab = initialize_vocab()
substring_freq = count_substrings(data)
# Continue adding substrings until vocab size is reached
while len(vocab) < vocab_size:
remaining = vocab_size - len(vocab)
print(f"Vocabulary size: {len(vocab)} / {vocab_size}. Adding {remaining} more subwords.")
top_substrings = select_top_substrings(substring_freq, vocab, max_word_length, remaining)
if not top_substrings:
print("No more substrings to add. Stopping.")
break
for substr, freq in top_substrings:
vocab.add(substr)
print(f"Added substring: '{substr}' with frequency {freq}.")
return vocab
def sort_vocabulary(vocab, substring_freq):
print("Sorting vocabulary by frequency and then alphabetically...")
# Assign frequency 1 to ASCII characters as fallback
vocab_freq = {word: substring_freq.get(word, 1) for word in vocab}
# Sort by frequency descending, then alphabetically
sorted_vocab = sorted(vocab_freq.items(), key=lambda item: (-item[1], item[0]))
print("Sorting completed.")
return [word for word, freq in sorted_vocab]
def save_vocab(vocab_sorted, file_path):
print(f"Saving vocabulary to {file_path}...")
with open(file_path, 'w', encoding='utf-8') as f:
for word in vocab_sorted:
f.write(word + '\n')
print("Vocabulary saved successfully.")
def main():
dataset_path = "dataset.txt"
vocab_path = "vocab.txt"
data = load_dataset(dataset_path)
vocab = build_vocabulary(data, VOCAB_SIZE, MAX_WORD_LENGTH)
substring_freq = count_substrings(data)
vocab_sorted = sort_vocabulary(vocab, substring_freq)
save_vocab(vocab_sorted, vocab_path)
print("Vocabulary generation completed.")
# Run the main function
if __name__ == "__main__":
main()
Usage Instructions:
-
Upload dataset.txt to Google Colab:
- In your Google Colab environment, click on the folder icon on the left sidebar.
- Click the upload button and select your
dataset.txt file.
-
Set Control Parameters:
- You can adjust
VOCAB_SIZE and MAX_WORD_LENGTH at the beginning of the script according to your requirements.
-
Run the Script:
- Execute the cell containing the script. The script will process the dataset and generate
vocab.txt in the same directory.
-
Download vocab.txt:
- After execution, you can download the
vocab.txt file by clicking the three dots next to it in the Colab file explorer and selecting "Download".
Example Output:
Loading dataset from dataset.txt...
Dataset loaded. Length: 50000 characters.
Initializing vocabulary with all ASCII characters (0-255)...
Initial vocabulary size: 256
Counting substrings with length between 2 and 10...
Found 495000 unique substrings.
Vocabulary size: 256 / 1000. Adding 744 more subwords.
Selecting top 744 substrings not exceeding length 10...
Selected 744 substrings.
Added substring: 'the' with frequency 5000.
Added substring: 'and' with frequency 4500.
...
Saving vocabulary to vocab.txt...
Vocabulary saved successfully.
Vocabulary generation completed.
This script provides a foundational approach to vocabulary generation based on substring frequencies. Depending on the specifics of your dataset and requirements, you might want to further refine the substring selection and merging logic.