செய்யறிவு-பகுதி 5:
எம்பெடிங்ஸ் & மொழி மாதிரிகள்


சொல்லின் ஆன்மாவைத் தேடும் பயணம். வார்த்தைகளின் கணித உலகம், மொழி மாதிரிகள், மற்றும் நியூரல் நெட்வொர்க்குகள்.

Word Embeddings · Language Models · Neural Networks · Attention

அகராதி மற்றும் டோக்கனைசேஷன் (Vocabulary & Tokenization)

இயந்திரங்களுக்கு மொழியைக் கற்றுக்கொடுப்பதன் முதல் படி

கணினிகளால் எழுத்துக்களை நேரடியாகப் புரிந்துகொள்ள முடியாது. எனவே, உரையை எண்களாக (Numerical Sequences) மாற்றுவதே முதல் படியாகும்.

  • Corpus (உரைத் தொகுப்பு): பயிற்சிக்காக நாம் பயன்படுத்தும் ஒட்டுமொத்த உரைகளின் தொகுப்பு.
  • Vocabulary (அகராதி): தரவில் உள்ள தனித்துவமான வார்த்தைகளின் பட்டியல்.
  • Tokenization: வாக்கியங்களைச் சிறு துண்டுகளாகப் பிரித்து, ஒவ்வொரு வார்த்தைக்கும் ஒரு பிரத்யேக எண்ணை (Integer ID) வழங்குதல்.
  • OOV (Out-Of-Vocabulary): பயிற்சியில் இல்லாத புதிய வார்த்தை வரும்போது, அதை <OOV> என்ற பொதுவான டோக்கனாக மாற்றுதல்.

💻 Code: TensorFlow Tokenizer-இன் செயல்பாடு

(உரையை எண்களின் வரிசையாக மாற்றுதல்)


# TensorFlow Tokenizer-ஐப் போலவே செயல்படும் எளிய Python குறியீடு
class SimpleTokenizer:
    def __init__(self, oov_token="<OOV>"):
        self.word_index = {}
        self.oov_token = oov_token
        self.word_index[self.oov_token] = 1 # OOV-க்கு எண் 1
        self.current_id = 2

    def fit_on_texts(self, texts):
        for text in texts:
            words = text.lower().replace('.', '').split()
            for word in words:
                if word not in self.word_index:
                    self.word_index[word] = self.current_id
                    self.current_id += 1

    def texts_to_sequences(self, texts):
        sequences = []
        for text in texts:
            words = text.lower().replace('.', '').split()
            seq = [self.word_index.get(word, self.word_index[self.oov_token]) for word in words]
            sequences.append(seq)
        return sequences

# உரைத் தொகுப்பு (Corpus)
corpus = ["Bob ate apples and pears", "Fred ate apples"]
tokenizer = SimpleTokenizer()
tokenizer.fit_on_texts(corpus)

print("📚 உருவாக்கப்பட்ட அகராதி (Word Index):")
print(tokenizer.word_index)

# புதிய வாக்கியத்தை எண்களாக மாற்றுதல்
new_sentences = ["Bob ate pears", "Fred ate bacon"]
sequences = tokenizer.texts_to_sequences(new_sentences)

print("\n🔢 எண்களாக மாற்றப்பட்ட வாக்கியங்கள் (Sequences):")
for i, seq in enumerate(sequences):
    print(f"'{new_sentences[i]}' -> {seq}")
print("(குறிப்பு: 'bacon' என்ற புதிய வார்த்தைக்கு OOV எண் 1 வழங்கப்பட்டுள்ளது)")
                        

எம்பெடிங்ஸ் (Embeddings)

வார்த்தைகளுக்கு ஓர் ஆன்மாவைக் கொடுத்தல்

வார்த்தைகளை பல பரிமாணங்களைக் கொண்ட டிஜிட்டல் DNA-வாக (Vectors) மாற்றுதல்.

  • வார்த்தைப் பிரபஞ்சத்தின் வரைபடம்: ஒரே மாதிரியான அர்த்தம் கொண்ட வார்த்தைகள் (உ-ம்: அரசன், இளவரசர்) காந்தம் போல அருகருகே அமர்ந்துகொள்ளும்.
  • கவிஞரின் பார்வை: BoW என்ற கணக்காளரைத் தாண்டி, எம்பெடிங் ஒரு கவிஞனைப் போல வார்த்தைகளின் உணர்வுகளையும், நுணுக்கங்களையும், பன்முகத் தொடர்புகளையும் பிரதிபலிக்கிறது.

Word2Vec

வார்த்தைகளுக்குப் பயிற்சி அளிக்கும் இரு வழிகள்

விதி: *"ஒரு வார்த்தையின் குணத்தை அறிய, அது புழங்கும் மற்ற வார்த்தைகளைப் பார்."* (தாமஸ் மிக்கொலோவ், 2013)

  • வழி 1: CBOW (Continuous Bag of Words): துப்பறிவாளன். சுற்றியுள்ள வார்த்தைகளை வைத்து மைய வார்த்தையைக் கணித்தல். (வேகமானது).
  • வழி 2: Skip-Gram: கதைசொல்லி. மைய வார்த்தையை வைத்து, சுற்றியுள்ள வார்த்தைகளைக் கணித்தல். (ஆழமானது, அரிதான வார்த்தைகளுக்குச் சிறந்தது).

Word2Vec: Skip-gram மற்றும் CBOW

பயிற்சி ஜோடிகளை (Training Pairs) உருவாக்குதல்

விதி: *"ஒரு வார்த்தையின் குணத்தை அறிய, அது புழங்கும் மற்ற வார்த்தைகளைப் பார்."*

வாக்கியம்: "paul likes singing in french" (மைய வார்த்தை: singing)

  • வழி 1: Skip-Gram (கதைசொல்லி): மைய வார்த்தையை வைத்து, சுற்றியுள்ள சூழல் வார்த்தைகளைக் தனித்தனியாகக் கணித்தல்.
    ஜோடிகள்: (singing, paul), (singing, likes), (singing, in), (singing, french)
    நன்மை: அரிதான வார்த்தைகளுக்கும் (Rare words) மிகச் சிறப்பாகச் செயல்படும்.

  • வழி 2: CBOW (துப்பறிவாளன்): சுற்றியுள்ள வார்த்தைகளின் சராசரியை வைத்து மைய வார்த்தையைக் கணித்தல்.
    ஜோடி: ([paul, likes, in, french], singing)
    நன்மை: மிக விரைவாகப் பயிற்சி பெறும்.

💻 Code: Skip-Gram ஜோடிகளை உருவாக்குதல்

(Target Word மற்றும் Context Window-ஐப் பிரித்தெடுத்தல்)


def create_skip_gram_pairs(sequence, window_size):
    pairs = []
    half_window = window_size // 2
    
    # ஒவ்வொரு வார்த்தையாக மைய வார்த்தையாக (Target) எடுத்தல்
    for i in range(len(sequence)):
        target_word = sequence[i]
        
        # இடது மற்றும் வலது எல்லைகளைக் கணக்கிடுதல் (left_incl, right_excl)
        left_incl = max(0, i - half_window)
        right_excl = min(len(sequence), i + half_window + 1)
        
        # சூழல் வார்த்தைகளுடன் (Context) ஜோடி சேர்த்தல்
        for j in range(left_incl, right_excl):
            if i != j: # தன்னோடு தானே ஜோடி சேர்வதைத் தவிர்க்க
                context_word = sequence[j]
                pairs.append((target_word, context_word))
                
    return pairs

# வாக்கியம் (Tokenize செய்யப்பட்டது போல் வைத்துக்கொள்வோம்)
sentence = ["paul", "likes", "singing", "in", "french"]
window = 5 # Target-ஐ சுற்றி 2 வலது, 2 இடது வார்த்தைகள்

print(f"📝 வாக்கியம்: {' '.join(sentence)}")
print(f"🪟 Window Size: {window}\n")

pairs = create_skip_gram_pairs(sentence, window)

print("🔗 உருவாக்கப்பட்ட Skip-Gram ஜோடிகள் (Target, Context):")
for pair in pairs:
    # 'singing' மைய வார்த்தையாக இருக்கும் ஜோடிகளை மட்டும் முன்னிலைப்படுத்துவோம்
    if pair[0] == "singing":
        print(f"   ⭐ {pair}")
    else:
        print(f"   {pair}")
                        

Word2Vec-இன் மாயாஜாலம்

கணிதச் சமன்பாட்டில் மொழியின் ஆன்மா

vector("அரசன்") - vector("ஆண்") + vector("பெண்") ≈ vector("அரசி")

  • தாக்கம்:
    1. Semantic Search: "Cheap Laptop" என்று தேடினால் "Budget Notebook" ஐக் கண்டுபிடிக்கும்.
    2. Cross-Lingual Embeddings: ஆங்கிலப் பிரபஞ்சத்தையும் பிரெஞ்சுப் பிரபஞ்சத்தையும் ஒப்பிட்டு மொழிபெயர்ப்பது.
    3. Item2Vec: பரிந்துரைகள் ("இதை வாங்கியவர்கள் அதையும் வாங்கினார்கள்").

💻 Code: Word2Vec Math

(வார்த்தைகளின் கணித உறவை Numpy மூலம் புரிந்துகொள்ளுதல்)


import numpy as np

# வார்த்தைகளுக்கான கற்பனை வெக்டர்கள் (Embeddings)
# பரிமாணங்கள்: [ராஜத்தன்மை (Royalty), ஆண்மை (Masculinity)]
vec_king   = np.array([0.9,  0.9])
vec_man    = np.array([0.0,  0.9])
vec_woman  = np.array([0.0, -0.9])

# Word2Vec மாயாஜாலம்: King - Man + Woman
vec_result = vec_king - vec_man + vec_woman

print("கணிக்கப்பட்ட வெக்டர்:", vec_result)

# vec_queen = [0.9, -0.9] (அரசி = ராஜத்தன்மை + பெண்மை)
vec_queen = np.array([0.9, -0.9])

# Cosine Similarity (இரண்டும் ஒன்றா எனப் பார்த்தல்)
similarity = np.dot(vec_result, vec_queen)
print("அரசியுடன் (Queen) பொருத்தம்:", round(similarity, 2))
                        

💻 Code: Cosine Similarity

(வெக்டர்களுக்கு இடையேயான உறவை அளவிடுதல் - Semantic Search-க்கான அடிப்படை)


import numpy as np
from numpy.linalg import norm

def cosine_similarity(vec1, vec2):
    """Cosine Similarity: -1 (எதிர் திசை) முதல் 1 (ஒரே திசை)"""
    return np.dot(vec1, vec2) / (norm(vec1) * norm(vec2))

# வார்த்தைகளுக்கான எம்பெடிங் வெக்டர்கள் (கற்பனையானவை)
vec_king   = np.array([0.9,  0.8,  0.1])
vec_queen  = np.array([0.9, -0.8,  0.1])
vec_man    = np.array([0.1,  0.8,  0.0])
vec_apple  = np.array([0.0,  0.0,  0.9])

# உறவுகளை அளவிடுதல்
print("உறவு அளவீடு (Cosine Similarity):")
print("-" * 40)
print(f"King  - Queen : {cosine_similarity(vec_king, vec_queen):.3f}")
print(f"King  - Man   : {cosine_similarity(vec_king, vec_man):.3f}")
print(f"King  - Apple : {cosine_similarity(vec_king, vec_apple):.3f}")

print("\nமுடிவு: King & Queen உயர்ந்த உறவு (0.9+)")
print("King & Apple சம்பந்தமே இல்லை (0.1)!")

# நிஜ உலகத்தில்: தேடுபொறிகளில் Semantic Search
print("\nபயன்: Recommendation Systems, Duplicate Detection")
                        

Word2Vec-இன் குறைபாடுகள்

  • OOV (Out-of-Vocabulary): பயிற்சியின் போது பார்க்காத புதிய வார்த்தை வந்தால் நிராகரித்துவிடும்.
  • Morphology (சொல் உருவமைப்பு): "run", "runner", "running" ஆகியவை ஒரே குடும்பம் எனப் புரியாது.
  • நிலைத்த தன்மை (Static): "bat" என்ற சொல்லுக்கு எப்போதுமே ஒரே வெக்டரைத் தரும். அது மட்டையா, வௌவாலா எனப் பிரித்தறியாது.

💻 Hands-On: ஒத்த வார்த்தைகளைக் கண்டுபிடி

(எம்பெடிங் வெளியில் Word Similarity & Analogies)


import numpy as np
from numpy.linalg import norm

# மினி எம்பெடிங் வெளி (4D vectors)
# பரிமாணங்கள்: [ராஜத்தன்மை, பாலினம்(M+/F-), விலங்கு, தொழில்நுட்பம்]
word_vectors = {
    "king":     np.array([0.9,  0.8, 0.0, 0.0]),
    "queen":    np.array([0.9, -0.8, 0.0, 0.0]),
    "prince":   np.array([0.7,  0.6, 0.0, 0.0]),
    "princess": np.array([0.7, -0.6, 0.0, 0.0]),
    "man":      np.array([0.1,  0.9, 0.0, 0.0]),
    "woman":    np.array([0.1, -0.9, 0.0, 0.0]),
    "dog":      np.array([0.0,  0.2, 0.9, 0.0]),
    "cat":      np.array([0.0, -0.2, 0.9, 0.0]),
    "computer": np.array([0.0,  0.0, 0.0, 0.9]),
}

def cosine_sim(v1, v2):
    return np.dot(v1, v2) / (norm(v1) * norm(v2))

def find_similar(word, top_n=3):
    vec = word_vectors[word]
    sims = [(w, cosine_sim(vec, v)) for w, v in word_vectors.items() if w != word]
    return sorted(sims, key=lambda x: x[1], reverse=True)[:top_n]

def word_analogy(a, b, c):
    result = word_vectors[b] - word_vectors[a] + word_vectors[c]
    sims = [(w, cosine_sim(result, v)) for w, v in word_vectors.items() if w not in [a, b, c]]
    return sorted(sims, key=lambda x: x[1], reverse=True)[0]

print("🔍 Word Similarity Explorer")
print("="*50)

for word in ["king", "dog"]:
    similar = find_similar(word, 3)
    print(f"\n'{word}' க்கு ஒத்த வார்த்தைகள்:")
    for w, score in similar:
        print(f"  {w:12} (similarity: {score:.2f})")

print("\n" + "="*50)
print("🧮 Word Analogies:")
print("\nking:queen :: man:?")
answer, score = word_analogy("king", "queen", "man")
print(f"  பதில்: {answer} (score: {score:.2f})")
                        

மொழி மாதிரிகள் (LM)

வாசகனிலிருந்து படைப்பாளியாக...

  • அறிமுகம்: மொழியை வாசிக்கக் கற்றுக் கொண்ட இயந்திரம், இப்போது பேசவும் எழுதவும் (Generate) தயாராகிறது.
  • அடிப்படைத் தத்துவம்: "அடுத்து என்ன வார்த்தை வரும்?" (Probability/நிகழ்தகவு).
  • மனித மூளை உள்ளுணர்வில் கணிப்பதைப் போல (உ-ம்: "வானம் நீல..." -> "நிறத்தில் இருக்கிறது"), AI கோடிக்கணக்கான தரவுகளைப் படித்து வார்த்தைகளுக்கு இடையேயான தொடர்பைக் கற்றுக்கொள்கிறது.

முதல் வரிசை தொடர் மாதிரி

"தங்கமீன்" போன்ற குறுகிய கால நினைவு

மார்கோவ் சங்கிலி (Markov Chain): அடுத்து என்ன நடக்கும் என்பதை, இப்போது என்ன நடக்கிறது என்பதை வைத்து *மட்டுமே* யூகிப்பது.

P(next word | current word)

எடுத்துக்காட்டு: "The cat sat on the [___]".
'the' என்ற ஒரு வார்த்தைக்குப் பிறகு 'mat', 'chair' எத்தனை முறை வந்தது எனப் புள்ளிவிவரம் பார்க்கும்.

  • மாபெரும் வரம்பு: முந்தைய ஒற்றை வார்த்தையை மட்டுமே பார்ப்பதால் வாக்கியத்தின் முழுச் சூழல் புரியாது. (உ-ம்: "விண்வெளி வீரர் பறந்து சென்று அமர்ந்தது ஒரு [மரம்]" என உளறும்).

ட்ரான்சிஷன் மேட்ரிக்ஸ் (Transition Matrix)

AI-இன் புதையல் வரைபடம்

ஒரு வார்த்தையிலிருந்து இன்னொரு வார்த்தைக்கு மாறுவதற்கான நிகழ்தகவுகளைப் (Probabilities) பதிவு செய்து வைக்கும் பிரம்மாண்ட அட்டவணை.

P(word₂ | word₁) = Count(word₁, word₂) / Count(word₁)

  • <start> → "எனது" (100% வாய்ப்பு)
  • "எனது" → "இசையை" (33% வாய்ப்பு - பகடையை உருட்டுதல்)
  • "இசையை" → "இயக்கு" (100% வாய்ப்பு)
  • "இயக்கு" → <end>

💻 Code: N-Grams & Markov

(NLTK ngrams கொண்டு Transition Matrix உருவாக்குதல்)


from nltk import ngrams, ConditionalFreqDist

text = "I love AI . I love Python . AI is great .".split()

# NLTK கொண்டு Bigrams (2-வார்த்தை ஜோடிகள்) உருவாக்குதல்
bigrams = list(ngrams(text, 2))
print("Bigrams:", bigrams[:4], "...\n")

# Conditional Frequency Distribution (Transition Matrix)
cfd = ConditionalFreqDist(bigrams)

print("Transition Matrix for 'AI':", dict(cfd['AI']))
print("Transition Matrix for 'love':", dict(cfd['love']))

# AI-இன் கணிப்பு (அடுத்த வார்த்தை என்ன?)
current_word = "I"
next_word = cfd[current_word].max()
print(f"\nPrediction: '{current_word}' என்ற வார்த்தைக்குப் பிறகு '{next_word}' வரும்.")
                        

💻 Hands-On: Markov Text Generation

(கற்ற நிகழ்தகவுகளைக் கொண்டு புதிய உரை உருவாக்குதல்)


import random
from collections import defaultdict

# பயிற்சி உரை
corpus = """
To be or not to be that is the question.
To live or not to live is also a question.
To learn is to grow and to grow is to be wise.
Knowledge is power and power is wisdom.
Wisdom leads to understanding and understanding leads to peace.
""".lower()

words = corpus.split()

# Transition நிகழ்தகவுகளை உருவாக்குதல்
transitions = defaultdict(list)
for i in range(len(words) - 1):
    transitions[words[i]].append(words[i+1])

print("'to' க்கான transitions:", transitions['to'][:5])
print("'is' க்கான transitions:", transitions['is'][:5])
print("\n" + "="*40)

# புதிய உரை உருவாக்குதல்!
def generate_text(start_word, length=10):
    current = start_word
    result = [current]
    for _ in range(length - 1):
        if current in transitions:
            current = random.choice(transitions[current])
            result.append(current)
        else:
            break
    return ' '.join(result)

print("\n🎲 AI உருவாக்கிய வாக்கியங்கள்:")
for i in range(3):
    print(f"  {i+1}. {generate_text('to', 8)}")
                        

உணர்ச்சிப் பகுப்பாய்வு (Sentiment Analysis)

வரிகளுக்குப் பின்னால் இருக்கும் இதயத்துடிப்பு

உரையில் வெளிப்படும் உணர்வு நேர்மறையானதா (Positive), எதிர்மறையானதா (Negative), அல்லது நடுநிலையானதா (Neutral) எனக் கண்டறிதல்.

  • அளவீடுகள்:
  • அளவீடுகள்:
    • போலாரிட்டி (Polarity): -1 (கோபம்) முதல் +1 (மகிழ்ச்சி) வரை.
    • சப்ஜெக்டிவிட்டி (Subjectivity): 0 (உண்மை/Fact) முதல் 1 (கருத்து/Opinion) வரை.
  • LLM-களின் புரட்சி: நகைச்சுவை (Sarcasm), அங்கதம் (Irony) போன்ற சூழல் சார்ந்த நுணுக்கங்களை நவீன AI கச்சிதமாகப் புரிந்து கொள்கிறது.

💻 Code: Sentiment Analysis

(VaderSentiment லைப்ரரியைப் பயன்படுத்துதல்)


# நிஜ உலகத் திட்டங்களில் பயன்படும் VADER Sentiment Analyzer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

analyzer = SentimentIntensityAnalyzer()

text = "I love this NLP course, it is absolutely great!"

# ஒட்டுமொத்த உணர்ச்சியைக் கணக்கிடுதல்
scores = analyzer.polarity_scores(text)
print("Text:", text)
print("Scores:", scores)

# Compound score (-1 முதல் 1 வரை)
compound = scores['compound']

if compound >= 0.05:
    print("\nResult: Positive (நேர்மறை) 😊")
elif compound <= -0.05:
    print("\nResult: Negative (எதிர்மறை) 😠")
else:
    print("\nResult: Neutral (நடுநிலை) 😐")
                        

💻 Hands-On: உங்கள் சொந்த Sentiment Analyzer

(Lexicon அடிப்படையில் புதிதாக உருவாக்குதல்)


import re

# எளிய sentiment lexicon உருவாக்குதல்
positive_words = {
    'love': 3, 'amazing': 3, 'excellent': 3, 'good': 2,
    'great': 2, 'happy': 2, 'wonderful': 3, 'best': 3,
    'like': 1, 'nice': 1, 'enjoy': 2, 'fantastic': 3
}

negative_words = {
    'hate': -3, 'awful': -3, 'terrible': -3, 'bad': -2,
    'horrible': -3, 'worst': -3, 'boring': -2, 'poor': -2,
    'sad': -2, 'disappointing': -2, 'ugly': -2, 'difficult': -1
}

intensifiers = {'very': 1.5, 'really': 1.5, 'extremely': 2, 'absolutely': 2}
negations = {'not', "n't", 'never', 'no'}

def analyze_sentiment(text):
    words = re.findall(r'\b\w+\b', text.lower())
    score = 0
    details = []
    negate = False
    intensity = 1

    for word in words:
        if word in negations:
            negate = True
            continue
        if word in intensifiers:
            intensity = intensifiers[word]
            continue

        word_score = positive_words.get(word, 0) + negative_words.get(word, 0)
        if word_score != 0:
            if negate:
                word_score = -word_score * 0.5
            word_score *= intensity
            details.append((word, word_score))
            score += word_score
            negate = False
            intensity = 1

    return score, details

sentences = [
    "I love this amazing product!",
    "This is really terrible and awful",
    "The movie was not bad actually",
    "I'm very happy with this excellent service"
]

print("🎭 Custom Sentiment Analyzer\n" + "="*50)
for sent in sentences:
    score, details = analyze_sentiment(sent)
    emoji = "😊" if score > 0 else "😠" if score < 0 else "😐"
    print(f"\n'{sent}'")
    print(f"  வார்த்தைகள்: {details}")
    print(f"  மொத்த Score: {score:.1f} {emoji}")
                        

💻 Hands-On: Document Similarity Search

(TF-IDF + Cosine Similarity கொண்டு ஒத்த ஆவணங்களைக் கண்டுபிடித்தல்)


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np

# ஆவணத் தொகுப்பு
documents = [
    "Python is a great programming language for data science",
    "Machine learning algorithms can predict future outcomes",
    "Data science uses Python and machine learning techniques",
    "JavaScript is popular for web development",
    "Neural networks are a type of machine learning model",
    "Web applications often use JavaScript frameworks"
]

# தேடல் கேள்வி
query = "What programming language is best for machine learning?"

# ஆவணங்களையும் கேள்வியையும் vectorize செய்தல்
vectorizer = TfidfVectorizer(stop_words='english')
doc_vectors = vectorizer.fit_transform(documents)
query_vector = vectorizer.transform([query])

# Cosine similarity கணக்கிடுதல்
similarities = cosine_similarity(query_vector, doc_vectors)[0]

print("🔍 Semantic Document Search")
print("="*55)
print(f"கேள்வி: '{query}'\n")
print("ஆவண வரிசைப்படுத்தல்:\n")

ranked_idx = np.argsort(similarities)[::-1]

for rank, idx in enumerate(ranked_idx, 1):
    score = similarities[idx]
    bar = "█" * int(score * 25)
    print(f"  #{rank} (score: {score:.3f}) {bar}")
    print(f"     '{documents[idx][:45]}...'\n")

print("💡 TF-IDF + Cosine = எளிய Semantic Search!")
                        

ரெக்கரண்ட் நியூரல் நெட்வொர்க்குகள் (RNN)

வரிசை மற்றும் குறுகிய கால நினைவு

சவால்: "நதிக்குக் கரை (Bank)", "பணம் போடும் பேங்க் (Bank)" - வித்தியாசத்தை எப்படி அறிவது?

  • RNN-இன் தீர்வு: முந்தைய வார்த்தையின் நினைவை "Hidden State" என்ற ரகசிய நோட்டுப் புத்தகத்தில் வைத்துக்கொண்டே அடுத்த வார்த்தையைப் படிக்கும்.
  • குறைபாடுகள் (வில்லன்கள்):
    • மறதி நோய் (Vanishing Gradient): நீண்ட வாக்கியங்களில் ஆரம்பத் தகவலை மறந்துவிடும்.
    • வேகக் குறைவு: ஒன்றன்பின் ஒன்றாகப் படிப்பதால் இணை செயலாக்கம் (Parallel processing) செய்ய முடியாது.

லாங் ஷார்ட்-டெர்ம் மெமரி (LSTM)

மறதி நோய்க்கு ஒரு முற்றுப்புள்ளி

RNN-இன் மேம்படுத்தப்பட்ட வடிவம். நீண்ட தூரத் தகவல்களைக் கடத்தக்கூடியது.

  • மூன்று கதவுகள் (Gates):
    1. மறக்கும் கதவு: தேவையற்ற பழைய நினைவுகளை அழிப்பது.
    2. உள்ளீட்டுக் கதவு: புதிய முக்கியத் தகவலை எழுதுவது.
    3. வெளியீட்டுக் கதவு: சரியான பதிலை வெளியேற்றுவது.
  • Cell State: தகவல்களை நேரியல் கூட்டல் (Linear Addition) வழியே கடத்துகிறது. இதனால் Gradient Vanishing நடப்பதில்லை!

💻 Hands-On: RNN Forward Pass

(RNN எவ்வாறு sequential data-வை செயலாக்குகிறது என்பதை உருவகப்படுத்துதல்)


import numpy as np

# எளிய RNN forward pass simulation
np.random.seed(42)

# Weights initialize (சிறிய random values)
hidden_size = 4
input_size = 3
Wxh = np.random.randn(hidden_size, input_size) * 0.1
Whh = np.random.randn(hidden_size, hidden_size) * 0.1
bh = np.zeros(hidden_size)

def tanh(x):
    return np.tanh(x)

# Input sequence: "I love AI" (3 வார்த்தைகள் எளிய vectors-ஆக)
sequence = [
    np.array([1, 0, 0]),  # "I"
    np.array([0, 1, 0]),  # "love"
    np.array([0, 0, 1])   # "AI"
]
words = ["I", "love", "AI"]

# RNN வழியே sequence செயலாக்கம்
h = np.zeros(hidden_size)

print("🔄 RNN Sequence செயலாக்கம்:")
print("="*45)
for i, (x, word) in enumerate(zip(sequence, words)):
    # RNN சூத்திரம்: h_t = tanh(Wxh·x_t + Whh·h_{t-1} + b)
    h_new = tanh(np.dot(Wxh, x) + np.dot(Whh, h) + bh)
    print(f"\nபடி {i+1}: '{word}' செயலாக்கம்")
    print(f"  Input vector: {x}")
    print(f"  முந்தைய h:   [{', '.join(f'{v:.2f}' for v in h)}]")
    print(f"  புதிய hidden: [{', '.join(f'{v:.2f}' for v in h_new)}]")
    h = h_new

print("\n" + "="*45)
print("✅ இறுதி hidden state முழு sequence-ஐயும் encode செய்கிறது!")
                        

💻 Hands-On: LSTM Gates Simulation

(LSTM gates எவ்வாறு தகவல் ஓட்டத்தைக் கட்டுப்படுத்துகின்றன)


import numpy as np

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def tanh(x):
    return np.tanh(x)

print("🧠 LSTM Gate Simulation")
print("="*50)

# உருவகப்படுத்தப்பட்ட inputs
x_t = np.array([0.5, -0.2, 0.8])  # தற்போதைய input
h_prev = np.array([0.1, 0.3])     # முந்தைய hidden state
c_prev = np.array([0.4, -0.1])   # முந்தைய cell state

# Gate outputs (சாதாரணமாக weights-இலிருந்து கணக்கிடப்படும்)
forget_gate = sigmoid(np.array([0.2, 0.9]))  # என்ன மறக்க வேண்டும்
input_gate = sigmoid(np.array([0.8, 0.3]))   # என்ன எழுத வேண்டும்
candidate = tanh(np.array([0.5, -0.4]))      # புதிய candidate values
output_gate = sigmoid(np.array([0.7, 0.6]))  # என்ன வெளியிட வேண்டும்

print(f"\n📥 முந்தைய Cell State: {c_prev}")
print(f"\n🚪 Gate Activations:")
print(f"   Forget Gate: {np.round(forget_gate, 2)} (0=மறக்க, 1=வைக்க)")
print(f"   Input Gate:  {np.round(input_gate, 2)} (0=புறக்கணி, 1=எழுது)")
print(f"   Output Gate: {np.round(output_gate, 2)} (0=மறை, 1=வெளியிடு)")

# LSTM cell state update
c_new = forget_gate * c_prev + input_gate * candidate
h_new = output_gate * tanh(c_new)

print(f"\n📤 புதிய Cell State: {np.round(c_new, 3)}")
print(f"📤 புதிய Hidden State: {np.round(h_new, 3)}")
print(f"\n💡 Cell state நீண்டகால நினைவகத்தைப் பாதுகாக்கிறது!")
print("   Forget gate {:.0%} முந்தைய தகவலை வைத்துள்ளது".format(np.mean(forget_gate)))
                        

🚀 Hands-On Practice

Google Colab Notebook

இந்த session-இல் கற்றதை நேரடியாகப் பயிற்சி செய்ய interactive notebook:

Interactive NLP Exercises

Open in Google Colab

💡 RNN in Action!