File size: 11,160 Bytes
20c99a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import os
import re
import numpy as np
from gensim.models import Word2Vec
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Embedding, GRU, Dropout
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Layer, MultiHeadAttention, LayerNormalization

# === PARAMETRE AÇIKLAMALARI VE AYARLARI ===
max_worker = os.cpu_count()                      # İşlemcideki toplam çekirdek sayısı
vector_size = 1000                               # Word2Vec modelinin her kelime için vektör boyutu
window_size = 500                                 # Word2Vec’te komşuluk penceresi boyutu
min_count = 1                                    # Word2Vec’te dikkate alınacak minimum kelime frekansı
context_length = 4096                             # Modelin giriş dizilerinin maksimum uzunluğu
sentence_length = 5                              # Üretilen cümlelerin maksimum uzunluğu

# Transformer Encoder Parametreleri
embed_dim = 128                                  # Girdilerin (kelimelerin) vektörel boyutu
num_heads = 80                                    # Multi-Head Attention mekanizmasındaki başlık sayısı
feed_forward_dim = 512                           # Feed-Forward Network içindeki ara katman boyutu
dropout_rate_transformer = 0.1                   # Transformer Encoder için Dropout oranı
epsilon = 1e-6                                   # LayerNormalization stabilitesi için kullanılan sabit

# LSTM ve GRU Katman Parametreleri
lstm_units = [16000, 16000, 16000, 16000, 8000, 4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096]   # Her LSTM katmanındaki nöron sayısı
gru_units = [2048, 2048, 2048, 2048, 1024, 1024, 512, 512, 512, 512, 512, 512, 512, 512, 256, 256, 256, 256, 128, 64, 32, 16, 8, 4, 2, 1]  # Her GRU katmanındaki nöron sayıları
dropout_rate_rnn = 0.2                           # LSTM ve GRU için ortak Dropout oranı
return_sequences = True                          # LSTM ve GRU'da tüm zaman adımlarını döndürme parametresi

# Embedding Katman Parametreleri
input_dim = 10000                                # Girişteki toplam kelime sayısı (vocab size)
output_dim = 1000                                # Her kelimenin vektörel boyutu
input_length = context_length                    # Girişteki maksimum dizi uzunluğu

# Dense Katman Parametreleri
dense_units = input_dim                          # Dense katmanındaki nöron sayısı (sınıf sayısı)
activation = "softmax"                           # Dense katmanı aktivasyon fonksiyonu

# Optimizasyon ve Eğitim Parametreleri
loss = "sparse_categorical_crossentropy"         # Kayıp fonksiyonu
optimizer = "adam"                               # Optimizasyon algoritması
metrics = ["accuracy"]                           # Eğitim sırasında izlenecek başarı ölçütleri
epochs = 60                                      # Eğitim döngüsü sayısı
batch_size = 64                                  # Her eğitim adımında işlenecek örnek sayısı

# === TransformerEncoder Sınıfı ===
class TransformerEncoder(Layer):
    def __init__(self, embed_dim, num_heads, feed_forward_dim, dropout_rate=0.1):
        super(TransformerEncoder, self).__init__()
        self.attention = MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)
        self.dropout1 = Dropout(dropout_rate)
        self.norm1 = LayerNormalization(epsilon=epsilon)
        self.dense1 = Dense(feed_forward_dim, activation="relu")
        self.dense2 = Dense(embed_dim)
        self.dropout2 = Dropout(dropout_rate)
        self.norm2 = LayerNormalization(epsilon=epsilon)
    
    def call(self, inputs, training=None):
        # Multi-Head Attention
        attention_output = self.attention(inputs, inputs)
        attention_output = self.dropout1(attention_output, training=training)
        out1 = self.norm1(inputs + attention_output)  # Residual Connection

        # Feed-Forward Network
        dense_output = self.dense1(out1)
        dense_output = self.dense2(dense_output)
        dense_output = self.dropout2(dense_output, training=training)
        return self.norm2(out1 + dense_output)  # Residual Connection

# === Model Eğitimi ===
def train_model(X, y, tokenizer):
    nn_model = Sequential([
        # Embedding katmanı
        Embedding(input_dim=input_dim, output_dim=output_dim, input_length=input_length),
        # LSTM Katmanları
        *[LSTM(units, return_sequences=True, dropout=dropout_rate_rnn) for units in lstm_units[:-1]],
        LSTM(lstm_units[-1], return_sequences=True, dropout=dropout_rate_rnn),
        # GRU Katmanları
        *[GRU(units, return_sequences=True, dropout=dropout_rate_rnn) for units in gru_units[:-1]],
        GRU(gru_units[-1], return_sequences=False, dropout=dropout_rate_rnn),
        # Dense Katmanı
        Dense(dense_units, activation=activation)
    ])

    nn_model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
    print("Model eğitiliyor...")
    nn_model.fit(X, y, epochs=epochs, batch_size=batch_size)
    return nn_model

# === Cümle Üretim Fonksiyonu ===
def generate_sentence(model, tokenizer, start_word, sentence_length, temperature=1.0):
    sentence = [start_word]
    for _ in range(sentence_length - 1):
        sequence = tokenizer.texts_to_sequences([' '.join(sentence)])
        sequence = pad_sequences(sequence, maxlen=context_length, padding='post')
        predicted_probs = model.predict(sequence)[0]
        
        predicted_probs = np.asarray(predicted_probs).astype('float64')
        predicted_probs = np.log(predicted_probs + 1e-10) / temperature
        predicted_probs = np.exp(predicted_probs) / np.sum(np.exp(predicted_probs))

        predicted_index = np.random.choice(len(predicted_probs), p=predicted_probs)
        next_word = tokenizer.index_word.get(predicted_index, '')

        if not next_word:
            break
        sentence.append(next_word)

    return ' '.join(sentence)

# === Veri İşleme ve Model Eğitim ===
file_path = input("Veri setinin dosya yolunu giriniz: ")
try:
    with open(file_path, "r", encoding="utf-8") as f:
        dataset = f.readlines()
except FileNotFoundError:
    print("Dosya bulunamadı!")
    exit()

tokenized_sentences = [re.findall(r'\b\w+\b', sentence.lower()) for sentence in dataset]
word2vec_model = Word2Vec(tokenized_sentences, vector_size=vector_size, window=window_size, min_count=min_count, workers=max_worker)

tokenizer = Tokenizer()
tokenizer.fit_on_texts([' '.join(sentence) for sentence in tokenized_sentences])
sequences = tokenizer.texts_to_sequences([' '.join(sentence) for sentence in tokenized_sentences])
X = pad_sequences(sequences, maxlen=context_length, padding='post')
y = np.array([seq[-1] if len(seq) > 0 else 0 for seq in sequences])

model = train_model(X, y, tokenizer)

# === Kullanıcıdan Girdi Al ve Cümle Üret ===
start_word = input("Başlangıç kelimesi giriniz: ")
print("\nÜretilen Cümle:", generate_sentence(model, tokenizer, start_word, sentence_length, temperature=1.0))





import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from torch.utils.data import DataLoader, Dataset

# 📌 Örnek bir veri kümesi (Pozitif ve Negatif cümleler)
data = [
    ("Bu harika bir gün", 1),
    ("Bugün çok mutluyum", 1),
    ("Kötü bir deneyim yaşadım", 0),
    ("Berbat bir gündü", 0),
    ("Güzel bir film izledim", 1),
    ("Bugün hiç iyi hissetmiyorum", 0)
]

# 📌 Basit bir kelime sözlüğü
word_to_index = {"<PAD>": 0, "<UNK>": 1}
for sentence, _ in data:
    for word in sentence.split():
        if word not in word_to_index:
            word_to_index[word] = len(word_to_index)

VOCAB_SIZE = len(word_to_index)  # Kelime sayısı

# 📌 Cümleleri sayısal verilere çevirme fonksiyonu
def tokenize(sentence):
    return [word_to_index.get(word, word_to_index["<UNK>"]) for word in sentence.split()]

# 📌 Dataset Sınıfı (Veriyi Tensor'a Çevirme)
class TextDataset(Dataset):
    def __init__(self, data):
        self.data = [(torch.tensor(tokenize(sentence), dtype=torch.long), label) for sentence, label in data]

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):
        return self.data[idx][0], torch.tensor(self.data[idx][1], dtype=torch.float)

# 📌 Veri Setini ve DataLoader'ı Oluştur
dataset = TextDataset(data)
dataloader = DataLoader(dataset, batch_size=2, shuffle=True, collate_fn=lambda x: (torch.nn.utils.rnn.pad_sequence([s[0] for s in x], batch_first=True), torch.tensor([s[1] for s in x])))

# 📌 Düşünce Motoru Modeli (Transformer + LSTM + GRU)
class DusunceMotoru(nn.Module):
    def __init__(self, vocab_size, embed_dim, num_heads, num_layers, hidden_dim, output_dim):
        super(DusunceMotoru, self).__init__()

        self.embedding = nn.Embedding(vocab_size, embed_dim)  # Kelime gömme

        self.transformer = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads),
            num_layers=num_layers
        )

        self.lstm = nn.LSTM(embed_dim, hidden_dim, num_layers, batch_first=True)
        self.gru = nn.GRU(hidden_dim, hidden_dim, num_layers, batch_first=True)

        self.fc = nn.Linear(hidden_dim, output_dim)  # Son Karar Ağı

    def forward(self, x):
        x = self.embedding(x)  # Gömülü katman
        x = self.transformer(x)  # Transformer
        x, _ = self.lstm(x)  # LSTM
        x, _ = self.gru(x)  # GRU
        x = self.fc(x[:, -1, :])  # Çıktı katmanı
        return torch.sigmoid(x)  # 0-1 arasında değer döndür

# 📌 Modeli Oluştur
model = DusunceMotoru(VOCAB_SIZE, embed_dim=128, num_heads=8, num_layers=2, hidden_dim=256, output_dim=1)

# 📌 Optimizasyon ve Kayıp Fonksiyonu
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_fn = nn.BCELoss()  # Binary Cross Entropy Loss (0 ve 1 için)

# 📌 Modeli Eğitme
EPOCHS = 100
for epoch in range(EPOCHS):
    total_loss = 0
    for inputs, labels in dataloader:
        optimizer.zero_grad()
        outputs = model(inputs).squeeze()
        loss = loss_fn(outputs, labels)
        loss.backward()
        optimizer.step()
        total_loss += loss.item()

    print(f"Epoch {epoch+1}/{EPOCHS}, Loss: {total_loss:.4f}")

# 📌 Modeli Test Etme (Tahmin)
def tahmin_yap(sentence):
    model.eval()
    tokens = tokenize(sentence)
    input_tensor = torch.tensor([tokens], dtype=torch.long)
    with torch.no_grad():
        output = model(input_tensor)
    return "Pozitif" if output.item() > 0.5 else "Negatif"

# 📌 Örnek Test
test_sentence = start_word
düşünme_sonucu = f"Cümle: {test_sentence} -> Tahmin: {tahmin_yap(test_sentence)}"
print("\nÜretilen Cümle:", generate_sentence(model, tokenizer, düşünme_sonucu, sentence_length, temperature=1.0))