சொல்லின் ஆன்மாவைத் தேடும் பயணம். வார்த்தைகளின் கணித உலகம், மொழி மாதிரிகள், மற்றும் நியூரல் நெட்வொர்க்குகள்.
Word Embeddings · Language Models · Neural Networks · Attention
Use Spacebar or Arrow Keys to navigate
கணினிகளால் எழுத்துக்களை நேரடியாகப் புரிந்துகொள்ள முடியாது. எனவே, உரையை எண்களாக (Numerical Sequences) மாற்றுவதே முதல் படியாகும்.
(உரையை எண்களின் வரிசையாக மாற்றுதல்)
# 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 வழங்கப்பட்டுள்ளது)")
வார்த்தைகளை பல பரிமாணங்களைக் கொண்ட டிஜிட்டல் DNA-வாக (Vectors) மாற்றுதல்.
விதி: *"ஒரு வார்த்தையின் குணத்தை அறிய, அது புழங்கும் மற்ற வார்த்தைகளைப் பார்."* (தாமஸ் மிக்கொலோவ், 2013)
விதி: *"ஒரு வார்த்தையின் குணத்தை அறிய, அது புழங்கும் மற்ற வார்த்தைகளைப் பார்."*
வாக்கியம்: "paul likes singing in french" (மைய வார்த்தை: singing)
(singing, paul), (singing, likes), (singing, in), (singing, french)
([paul, likes, in, french], singing)
(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}")
vector("அரசன்") - vector("ஆண்") + vector("பெண்") ≈ vector("அரசி")
(வார்த்தைகளின் கணித உறவை 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))
(வெக்டர்களுக்கு இடையேயான உறவை அளவிடுதல் - 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")
(எம்பெடிங் வெளியில் 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})")
↓ Scroll down for more in this chapter ↓
மார்கோவ் சங்கிலி (Markov Chain): அடுத்து என்ன நடக்கும் என்பதை, இப்போது என்ன நடக்கிறது என்பதை வைத்து *மட்டுமே* யூகிப்பது.
P(next word | current word)
எடுத்துக்காட்டு: "The cat sat on the [___]".
'the' என்ற ஒரு வார்த்தைக்குப் பிறகு 'mat', 'chair' எத்தனை முறை வந்தது எனப் புள்ளிவிவரம் பார்க்கும்.
ஒரு வார்த்தையிலிருந்து இன்னொரு வார்த்தைக்கு மாறுவதற்கான நிகழ்தகவுகளைப் (Probabilities) பதிவு செய்து வைக்கும் பிரம்மாண்ட அட்டவணை.
P(word₂ | word₁) = Count(word₁, word₂) / Count(word₁)
(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}' வரும்.")
(கற்ற நிகழ்தகவுகளைக் கொண்டு புதிய உரை உருவாக்குதல்)
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)}")
உரையில் வெளிப்படும் உணர்வு நேர்மறையானதா (Positive), எதிர்மறையானதா (Negative), அல்லது நடுநிலையானதா (Neutral) எனக் கண்டறிதல்.
(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 (நடுநிலை) 😐")
(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}")
(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!")
சவால்: "நதிக்குக் கரை (Bank)", "பணம் போடும் பேங்க் (Bank)" - வித்தியாசத்தை எப்படி அறிவது?
↓ Scroll down for more in this chapter ↓
RNN-இன் மேம்படுத்தப்பட்ட வடிவம். நீண்ட தூரத் தகவல்களைக் கடத்தக்கூடியது.
(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 செய்கிறது!")
(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)))
இந்த session-இல் கற்றதை நேரடியாகப் பயிற்சி செய்ய interactive notebook: