emotion-classifier-api / fix_tokenizer_script.py
ketir's picture
Upload fix_tokenizer_script.py
a7a8f0c verified
Raw History Blame Contribute Delete
4.81 kB
import joblib
import tensorflow as tf
import numpy as np
def fix_tokenizer_issue():
"""
Script untuk memperbaiki masalah tokenizer OOV
"""
# Load tokenizer dan model
try:
tokenizer = joblib.load("tokenizer_raw.pkl")
model = tf.keras.models.load_model("best_bilstm_model.h5")
print("πŸ“Š Tokenizer Info:")
print(f"Vocabulary size: {len(tokenizer.word_index)}")
print(f"Model input shape: {model.input_shape}")
# Check embedding layer
embedding_layer = model.layers[1] # Assuming embedding is second layer
print(f"Embedding input dim: {embedding_layer.input_dim}")
# Test dengan beberapa kata
test_words = ["saya", "marah", "sekali", "anjing", "bahagia"]
print("\nπŸ” Testing words:")
for word in test_words:
seq = tokenizer.texts_to_sequences([word])
print(f"'{word}' -> {seq}")
if seq[0]: # If sequence is not empty
max_index = max(seq[0])
if max_index >= embedding_layer.input_dim: # Fix: compare with embedding layer
print(f" ⚠️ Index {max_index} exceeds embedding vocab size ({embedding_layer.input_dim})!")
else:
print(f" βœ… Index {max_index} is valid")
# Solution: Filter tokenizer
print("\nπŸ”§ Applying fix...")
# Get model's actual vocabulary size from embedding layer
actual_vocab_size = embedding_layer.input_dim
# Create filtered word_index
filtered_word_index = {}
for word, idx in tokenizer.word_index.items():
if idx < actual_vocab_size:
filtered_word_index[word] = idx
# Update tokenizer
tokenizer.word_index = filtered_word_index
print(f"βœ… Fixed! New vocabulary size: {len(tokenizer.word_index)}")
print(f"Model embedding vocab size: {actual_vocab_size}")
# Save fixed tokenizer
joblib.dump(tokenizer, "tokenizer_raw_fixed.pkl")
print("πŸ’Ύ Saved as tokenizer_raw_fixed.pkl")
# Test the fix
print("\nπŸ§ͺ Testing fix:")
for word in test_words:
seq = tokenizer.texts_to_sequences([word])
print(f"'{word}' -> {seq}")
if seq[0]:
max_index = max(seq[0])
if max_index >= actual_vocab_size:
print(f" ❌ Still has issue: {max_index} >= {actual_vocab_size}")
else:
print(f" βœ… Fixed: {max_index} < {actual_vocab_size}")
return True
except FileNotFoundError as e:
print(f"❌ File not found: {e}")
print("Pastikan file 'tokenizer_raw.pkl' dan 'best_bilstm_model.h5' ada di directory yang sama")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
def create_safe_tokenizer_function():
"""
Membuat fungsi helper untuk safe tokenization
"""
code = '''
def safe_texts_to_sequences(tokenizer, texts, max_vocab_size=None):
"""
Safe version of texts_to_sequences yang menghindari OOV error
"""
if max_vocab_size is None:
max_vocab_size = len(tokenizer.word_index) + 1
sequences = tokenizer.texts_to_sequences(texts)
# Filter out indices that exceed vocabulary
filtered_sequences = []
for seq in sequences:
filtered_seq = [idx for idx in seq if idx < max_vocab_size]
filtered_sequences.append(filtered_seq)
return filtered_sequences
# Usage example:
# sequences = safe_texts_to_sequences(tokenizer, [text], embedding_layer.input_dim)
'''
with open("safe_tokenizer_helper.py", "w") as f:
f.write(code)
print("πŸ’Ύ Created safe_tokenizer_helper.py")
if __name__ == "__main__":
print("πŸš€ Starting tokenizer fix process...\n")
success = fix_tokenizer_issue()
if success:
print("\nβœ… Tokenizer fix completed successfully!")
print("πŸ“ Files created:")
print(" - tokenizer_raw_fixed.pkl")
create_safe_tokenizer_function()
print(" - safe_tokenizer_helper.py")
print("\nπŸ“‹ Next steps:")
print("1. Replace 'tokenizer_raw.pkl' dengan 'tokenizer_raw_fixed.pkl' di app.py")
print("2. Atau gunakan safe_texts_to_sequences() function untuk handling OOV")
print("3. Deploy ulang Hugging Face Space")
else:
print("\n❌ Fix process failed. Check the error messages above.")