import pandas as pd import numpy as np from sklearn.modelselection import traintestsplit…
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, GRU, Bidirectional, Conv1D, GlobalMaxPooling1D, Dense, Dropout from tensorflow.keras.utils import to_categorical from sklearn.metrics import classification_report from tensorflow.keras.callbacks import EarlyStopping from imblearn.over_sampling import SMOTE
Veriyi yükle
xt = pd.read_excel('/content/drive/My Drive/TCK_hakaret_tespiti/29072027_teknofest.xlsx') xt = xt.dropna() # NaN değerleri kaldır xt['mesaj'] = xt['mesaj'].astype(str) # Mesajları string olarak ayarla
Örnek bir veri kontrolü
print(xt.head())
Metinleri cümleler halinde tokenize et
sentences = [row.split() for row in xt['mesaj']]
Maksimum dizi uzunluğunu belirle
max_length = max([len(sentence) for sentence in sentences])
GloVe Embedding'lerini Yükleme
def get_coefs(word, *arr): return word, np.array(arr, dtype='float32')
GloVe dosyasının yolunu belirtin
embedding_dim = 300 embeddings_index = dict(get_coefs(*o.strip().split()) for o in open('/content/drive/My Drive/RNNs_homofobia/vectors.txt'))
Kelime indeksleme
tokenizer = {word: i + 1 for i, word in enumerate(set(word for sentence in sentences for word in sentence))} max_words = len(tokenizer) + 1
Embedding matrisi oluşturma
embedding_matrix = np.zeros((max_words, embedding_dim)) for word, i in tokenizer.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector
Kelimeleri indekslere çevir
def word_to_index(word): return tokenizer.get(word, 0)
Veriyi hazırlama
X = [[word_to_index(word) for word in sentence] for sentence in sentences] X = pad_sequences(X, maxlen=max_length, padding='post')
Etiketleri encode et
le = LabelEncoder() y = le.fit_transform(xt['label']) y = to_categorical(y)
Eğitim ve test verisine ayır
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.34, random_state=42)
SMOTE ile oversampling uygulama (dengesiz veriyi dengeleme)
smote = SMOTE(random_state=42) X_train_resampled, y_train_resampled = smote.fit_resample(X_train, np.argmax(y_train, axis=1))
Yeni sınıf dağılımını kontrol et
print(pd.Series(np.argmax(y_train_resampled, axis=1)).value_counts())
Modeli tanımla ve eğit
def build_and_evaluate_model(model_name, model): print(f"\nModel: {model_name}") early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True) model.fit(X_train_resampled, y_train_resampled, epochs=10, batch_size=32, validation_split=0.1, verbose=1, callbacks=[early_stopping]) y_pred_prob = model.predict(X_test) y_pred = np.argmax(y_pred_prob, axis=1) y_true = np.argmax(y_test, axis=1) target_names = [str(label) for label in le.classes_] print(classification_report(y_true, y_pred, target_names=target_names))
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.