A character level embedding for ASCII characters trained on Oxford English Dictionary.
This model uses a Transformer-based architecture to create embeddings that capture the contextual relationship between characters and their positions in words. It's trained using a contrastive learning approach where:
1import torch
2import numpy as np
3import torch.nn.functional as F
4from huggingface_hub import hf_hub_download
5
6# Example for downloading a single file
7local_path = hf_hub_download(repo_id="npc0/CharEmb", filename="char_embeddings_best.npy")
8
9# Load the pre-computed character embeddings
10char_embeddings = np.load(local_path, allow_pickle=True).item()
11
12# Convert to tensor for efficient operations
13char_embedding_tensor = {}
14for char, emb in char_embeddings.items():
15 char_embedding_tensor[char] = torch.tensor(emb, dtype=torch.float32)
1def get_character_embedding(char):
2 """Get the embedding for a single character."""
3 if char in char_embedding_tensor:
4 return char_embedding_tensor[char]
5 else:
6 print(f"Warning: Character '{char}' not found in embeddings")
7 return None
8
9# Example usage
10char = 'a'
11embedding = get_character_embedding(char)
12print(f"Embedding for '{char}': {embedding}")
13print(f"Embedding shape: {embedding.shape}") # Should be (8,)
1def decode_embedding(query_embedding, top_k=5):
2 """
3 Find the closest character(s) to a given embedding.
4
5 Args:
6 query_embedding: torch.Tensor of shape (8,)
7 top_k: Number of closest characters to return
8
9 Returns:
10 List of (character, similarity_score) tuples
11 """
12 # Normalize query embedding
13 query_embedding = F.normalize(query_embedding.unsqueeze(0), p=2, dim=-1)
14
15 similarities = []
16 for char, emb in char_embedding_tensor.items():
17 # Normalize character embedding
18 emb_norm = F.normalize(emb.unsqueeze(0), p=2, dim=-1)
19 # Compute cosine similarity
20 sim = F.cosine_similarity(query_embedding, emb_norm, dim=-1).item()
21 similarities.append((char, sim))
22
23 # Sort by similarity (descending)
24 similarities.sort(key=lambda x: x[1], reverse=True)
25
26 return similarities[:top_k]
27
28# Example usage
29test_char = 'e'
30test_embedding = get_character_embedding(test_char)
31
32if test_embedding is not None:
33 top_matches = decode_embedding(test_embedding, top_k=5)
34 print(f"\nTop 5 characters similar to '{test_char}':")
35 for char, sim in top_matches:
36 print(f" '{char}': {sim:.4f}")
1@misc{character_embedding_model,
2 title={Character Embedding Model with Blank-Filling},
3 author={Yuan Xu},
4 year={2025},
5 howpublished={\url{https://huggingface.co/your-username/character-embedding}}
6}