Bertug1911 commited on
Commit
cdad224
·
verified ·
1 Parent(s): 8a18b4d

Upload Br-T-1.5.py

Browse files
Files changed (1) hide show
  1. Br-T-1.5.py +135 -0
Br-T-1.5.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import numpy as np
4
+ from gensim.models import Word2Vec
5
+ from tensorflow.keras.models import Sequential
6
+ from tensorflow.keras.layers import Dense, LSTM, Embedding, GRU, Dropout
7
+ from tensorflow.keras.preprocessing.text import Tokenizer
8
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
9
+ from tensorflow.keras.layers import Layer, MultiHeadAttention, LayerNormalization
10
+
11
+ # === PARAMETRE AÇIKLAMALARI VE AYARLARI ===
12
+ max_worker = os.cpu_count() # İşlemcideki toplam çekirdek sayısı
13
+ vector_size = 1000 # Word2Vec modelinin her kelime için vektör boyutu
14
+ window_size = 50 # Word2Vec’te komşuluk penceresi boyutu
15
+ min_count = 1 # Word2Vec’te dikkate alınacak minimum kelime frekansı
16
+ context_length = 256 # Modelin giriş dizilerinin maksimum uzunluğu
17
+ sentence_length = 5 # Üretilen cümlelerin maksimum uzunluğu
18
+
19
+ # Transformer Encoder Parametreleri
20
+ embed_dim = 128 # Girdilerin (kelimelerin) vektörel boyutu
21
+ num_heads = 4 # Multi-Head Attention mekanizmasındaki başlık sayısı
22
+ feed_forward_dim = 512 # Feed-Forward Network içindeki ara katman boyutu
23
+ dropout_rate_transformer = 0.1 # Transformer Encoder için Dropout oranı
24
+ epsilon = 1e-6 # LayerNormalization stabilitesi için kullanılan sabit
25
+
26
+ # LSTM ve GRU Katman Parametreleri
27
+ lstm_units = [16000, 16000, 16000, 8000, 4096] # Her LSTM katmanındaki nöron sayısı
28
+ gru_units = [2048, 2048, 1024, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] # Her GRU katmanındaki nöron sayıları
29
+ dropout_rate_rnn = 0.1 # LSTM ve GRU için ortak Dropout oranı
30
+ return_sequences = True # LSTM ve GRU'da tüm zaman adımlarını döndürme parametresi
31
+
32
+ # Embedding Katman Parametreleri
33
+ input_dim = 10000 # Girişteki toplam kelime sayısı (vocab size)
34
+ output_dim = 1000 # Her kelimenin vektörel boyutu
35
+ input_length = context_length # Girişteki maksimum dizi uzunluğu
36
+
37
+ # Dense Katman Parametreleri
38
+ dense_units = input_dim # Dense katmanındaki nöron sayısı (sınıf sayısı)
39
+ activation = "softmax" # Dense katmanı aktivasyon fonksiyonu
40
+
41
+ # Optimizasyon ve Eğitim Parametreleri
42
+ loss = "sparse_categorical_crossentropy" # Kayıp fonksiyonu
43
+ optimizer = "adam" # Optimizasyon algoritması
44
+ metrics = ["accuracy"] # Eğitim sırasında izlenecek başarı ölçütleri
45
+ epochs = 20 # Eğitim döngüsü sayısı
46
+ batch_size = 32 # Her eğitim adımında işlenecek örnek sayısı
47
+
48
+ # === TransformerEncoder Sınıfı ===
49
+ class TransformerEncoder(Layer):
50
+ def __init__(self, embed_dim, num_heads, feed_forward_dim, dropout_rate=0.1):
51
+ super(TransformerEncoder, self).__init__()
52
+ self.attention = MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)
53
+ self.dropout1 = Dropout(dropout_rate)
54
+ self.norm1 = LayerNormalization(epsilon=epsilon)
55
+ self.dense1 = Dense(feed_forward_dim, activation="relu")
56
+ self.dense2 = Dense(embed_dim)
57
+ self.dropout2 = Dropout(dropout_rate)
58
+ self.norm2 = LayerNormalization(epsilon=epsilon)
59
+
60
+ def call(self, inputs, training=None):
61
+ # Multi-Head Attention
62
+ attention_output = self.attention(inputs, inputs)
63
+ attention_output = self.dropout1(attention_output, training=training)
64
+ out1 = self.norm1(inputs + attention_output) # Residual Connection
65
+
66
+ # Feed-Forward Network
67
+ dense_output = self.dense1(out1)
68
+ dense_output = self.dense2(dense_output)
69
+ dense_output = self.dropout2(dense_output, training=training)
70
+ return self.norm2(out1 + dense_output) # Residual Connection
71
+
72
+ # === Model Eğitimi ===
73
+ def train_model(X, y, tokenizer):
74
+ nn_model = Sequential([
75
+ # Embedding katmanı
76
+ Embedding(input_dim=input_dim, output_dim=output_dim, input_length=input_length),
77
+ # LSTM Katmanları
78
+ *[LSTM(units, return_sequences=True, dropout=dropout_rate_rnn) for units in lstm_units[:-1]],
79
+ LSTM(lstm_units[-1], return_sequences=True, dropout=dropout_rate_rnn),
80
+ # GRU Katmanları
81
+ *[GRU(units, return_sequences=True, dropout=dropout_rate_rnn) for units in gru_units[:-1]],
82
+ GRU(gru_units[-1], return_sequences=False, dropout=dropout_rate_rnn),
83
+ # Dense Katmanı
84
+ Dense(dense_units, activation=activation)
85
+ ])
86
+
87
+ nn_model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
88
+ print("Model eğitiliyor...")
89
+ nn_model.fit(X, y, epochs=epochs, batch_size=batch_size)
90
+ return nn_model
91
+
92
+ # === Cümle Üretim Fonksiyonu ===
93
+ def generate_sentence(model, tokenizer, start_word, sentence_length, temperature=1.0):
94
+ sentence = [start_word]
95
+ for _ in range(sentence_length - 1):
96
+ sequence = tokenizer.texts_to_sequences([' '.join(sentence)])
97
+ sequence = pad_sequences(sequence, maxlen=context_length, padding='post')
98
+ predicted_probs = model.predict(sequence)[0]
99
+
100
+ predicted_probs = np.asarray(predicted_probs).astype('float64')
101
+ predicted_probs = np.log(predicted_probs + 1e-10) / temperature
102
+ predicted_probs = np.exp(predicted_probs) / np.sum(np.exp(predicted_probs))
103
+
104
+ predicted_index = np.random.choice(len(predicted_probs), p=predicted_probs)
105
+ next_word = tokenizer.index_word.get(predicted_index, '')
106
+
107
+ if not next_word:
108
+ break
109
+ sentence.append(next_word)
110
+
111
+ return ' '.join(sentence)
112
+
113
+ # === Veri İşleme ve Model Eğitim ===
114
+ file_path = input("Veri setinin dosya yolunu giriniz: ")
115
+ try:
116
+ with open(file_path, "r", encoding="utf-8") as f:
117
+ dataset = f.readlines()
118
+ except FileNotFoundError:
119
+ print("Dosya bulunamadı!")
120
+ exit()
121
+
122
+ tokenized_sentences = [re.findall(r'\b\w+\b', sentence.lower()) for sentence in dataset]
123
+ word2vec_model = Word2Vec(tokenized_sentences, vector_size=vector_size, window=window_size, min_count=min_count, workers=max_worker)
124
+
125
+ tokenizer = Tokenizer()
126
+ tokenizer.fit_on_texts([' '.join(sentence) for sentence in tokenized_sentences])
127
+ sequences = tokenizer.texts_to_sequences([' '.join(sentence) for sentence in tokenized_sentences])
128
+ X = pad_sequences(sequences, maxlen=context_length, padding='post')
129
+ y = np.array([seq[-1] if len(seq) > 0 else 0 for seq in sequences])
130
+
131
+ model = train_model(X, y, tokenizer)
132
+
133
+ # === Kullanıcıdan Girdi Al ve Cümle Üret ===
134
+ start_word = input("Başlangıç kelimesi giriniz: ")
135
+ print("\nÜretilen Cümle:", generate_sentence(model, tokenizer, start_word, sentence_length, temperature=1.0))