{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Kütüphaneler eklenmesi" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "from datasets import load_dataset\n", "import pandas as pd \n", "from pymongo import MongoClient\n", "from transformers import BertTokenizer, BertForMaskedLM, DPRContextEncoderTokenizer,DPRContextEncoder;\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Parquet dosyalarının dataframe olarak yüklenmesi(okuma yapabilmek için)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "# Parquet dosyalarını DataFrame olarak yükleyin\n", "train_df1 = pd.read_parquet('C:\\\\gitProjects\\\\yeni\\\\wikipedia-tr\\\\data\\\\train-00000-of-00002-ed6b025df7a1f653.parquet')\n", "train_df2 = pd.read_parquet('C:\\\\gitProjects\\\\yeni\\\\wikipedia-tr\\\\data\\\\train-00001-of-00002-0aa63953f8b51c17.parquet')\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# İki DataFrame'i birleştirin\n", "merged_train = pd.concat([train_df1, train_df2], ignore_index=True)\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "# Örneğin %80 train, %20 test olarak ayırın\n", "train_data = merged_train.sample(frac=0.8, random_state=42)\n", "test_data = merged_train.drop(train_data.index)\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "# Dosya yolları\n", "train_dir = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\train_Egitim'\n", "test_dir = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\test_Egitim'\n", "train_file_path = os.path.join(train_dir, 'merged_train.parquet')\n", "test_file_path = os.path.join(test_dir, 'merged_test.parquet')\n", "\n", "# Dizinlerin var olup olmadığını kontrol etme, gerekirse oluşturma\n", "os.makedirs(train_dir, exist_ok=True)\n", "os.makedirs(test_dir, exist_ok=True)\n", "\n", "# Veriyi .parquet formatında kaydetme\n", "train_data.to_parquet(train_file_path)\n", "test_data.to_parquet(test_file_path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dataframe deki bilgileri görme " ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " id url \\\n", "515773 3525037 https://tr.wikipedia.org/wiki/P%C5%9F%C4%B1qo%... \n", "517811 3532700 https://tr.wikipedia.org/wiki/Craterolophinae \n", "436350 3203545 https://tr.wikipedia.org/wiki/Notocrabro \n", "223281 1765445 https://tr.wikipedia.org/wiki/Ibrahim%20Sissoko \n", "100272 575462 https://tr.wikipedia.org/wiki/Salah%20Cedid \n", "\n", " title text \n", "515773 Pşıqo Ahecaqo Pşıqo Ahecaqo (), Çerkes siyasetçi, askeri kom... \n", "517811 Craterolophinae Craterolophinae, Depastridae familyasına bağlı... \n", "436350 Notocrabro Notocrabro Crabronina oymağına bağlı bir cinst... \n", "223281 Ibrahim Sissoko İbrahim Sissoko (d. 30 Kasım 1991), Fildişi Sa... \n", "100272 Salah Cedid Salah Cedid (1926-1993) (Arapça: صلاح جديد) Su... \n", " id url title \\\n", "5 35 https://tr.wikipedia.org/wiki/Karl%20Marx Karl Marx \n", "13 48 https://tr.wikipedia.org/wiki/Ruhi%20Su Ruhi Su \n", "15 53 https://tr.wikipedia.org/wiki/Bilgisayar Bilgisayar \n", "18 59 https://tr.wikipedia.org/wiki/Edebiyat Edebiyat \n", "19 64 https://tr.wikipedia.org/wiki/M%C3%BChendislik Mühendislik \n", "\n", " text \n", "5 Karl Marx (; 5 Mayıs 1818, Trier – 14 Mart 188... \n", "13 Mehmet Ruhi Su (1 Ocak 1912, Van - 20 Eylül 19... \n", "15 Bilgisayar, aritmetik veya mantıksal işlem diz... \n", "18 Edebiyat, yazın veya literatür; olay, düşünce,... \n", "19 Mühendis, insanların her türlü ihtiyacını karş... \n" ] } ], "source": [ "print(train_data.head())\n", "print(test_data.head())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "MongoDb'ye bağlama ve bilgi çekme " ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Veriler başarıyla Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'EgitimDatabase'), 'train') MongoDb koleksiyonuna indirildi.\n", " Veriler başarıyla Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'EgitimDatabase'), 'test') MongoDb koleksiyonuna indirildi.\n" ] } ], "source": [ "import pandas as pd\n", "from pymongo import MongoClient\n", "\n", "def get_mongodb(database_name='EgitimDatabase', train_collection_name='train', test_collection_name='test', host='localhost', port=27017):\n", " \"\"\"\n", " MongoDB connection and collection selection for train and test collections.\n", " \"\"\"\n", " client = MongoClient(f'mongodb://{host}:{port}/')\n", " \n", " # Veritabanını seçin\n", " db = client[database_name]\n", " \n", " # Train ve test koleksiyonlarını seçin\n", " train_collection = db[train_collection_name]\n", " test_collection = db[test_collection_name]\n", " \n", " return train_collection, test_collection\n", "\n", "# Function to load dataset into MongoDB\n", "def dataset_read(train_file_path,test_file_path):\n", " data_train = pd.read_parquet(train_file_path, columns=['id', 'url', 'title', 'text'])\n", " data_test = pd.read_parquet(test_file_path, columns=['id', 'url', 'title', 'text'])\n", " data_dict_train = data_train.to_dict(\"records\")\n", " data_dict_test = data_test.to_dict(\"records\")\n", "\n", "\n", "\n", " # Get the MongoDB collections\n", " train_collection, test_collection = get_mongodb(database_name='EgitimDatabase')\n", "\n", " \n", "\n", " # Insert data into MongoDB\n", " train_collection.insert_many(data_dict_train)\n", " test_collection.insert_many(data_dict_test)\n", "\n", "\n", " print(f\" Veriler başarıyla {train_collection} MongoDb koleksiyonuna indirildi.\")\n", " print(f\" Veriler başarıyla {test_collection} MongoDb koleksiyonuna indirildi.\")\n", " return train_collection,test_collection\n", "\n", "# Train ve test datasetlerini MongoDB'ye yüklemek için fonksiyonu çağır\n", "train_file_path = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\train_Egitim\\\\merged_train.parquet'\n", "test_file_path = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\test_Egitim\\\\merged_test.parquet'\n", "\n", "train_collection, test_collection = dataset_read(train_file_path, test_file_path)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "from pymongo import MongoClient,errors\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from sentence_transformers import SentenceTransformer\n", "\n", "# MongoDB bağlantı ve koleksiyon seçimi için fonksiyon\n", "def get_mongodb(database_name='EgitimDatabase', train_collection_name='train', test_collection_name='test', host='localhost', port=27017):\n", " client = MongoClient(f'mongodb://{host}:{port}/')\n", " db = client[database_name]\n", " train_collection = db[train_collection_name]\n", " test_collection = db[test_collection_name]\n", " return train_collection, test_collection\n", "\n", "# Dataset'i MongoDB'ye yükleme fonksiyonu\n", "def dataset_read(train_file_path, test_file_path):\n", " try:\n", " # MongoDB koleksiyonlarını al\n", " train_collection, test_collection = get_mongodb()\n", "\n", " # Eğer koleksiyonlar zaten doluysa, veri yüklemesi yapma\n", " if train_collection.estimated_document_count() > 0 or test_collection.estimated_document_count() > 0:\n", " print(\"Veriler zaten yüklendi, işlem yapılmadı.\")\n", " return train_collection, test_collection\n", "\n", " # Datasetleri oku\n", " data_train = pd.read_parquet(train_file_path, columns=['id', 'url', 'title', 'text'])\n", " data_test = pd.read_parquet(test_file_path, columns=['id', 'url', 'title', 'text'])\n", "\n", " # Verileri MongoDB'ye yükle\n", " train_collection.insert_many(data_train.to_dict(\"records\"))\n", " test_collection.insert_many(data_test.to_dict(\"records\"))\n", "\n", " print(f\"Veriler başarıyla {train_collection.name} koleksiyonuna yüklendi.\")\n", " print(f\"Veriler başarıyla {test_collection.name} koleksiyonuna yüklendi.\")\n", " \n", " except errors.PyMongoError as e:\n", " print(f\"Veri yükleme sırasında hata oluştu: {e}\")\n", "\n", " return train_collection, test_collection\n", "\n", "\n", "\n", "# Database sınıfı: Veritabanı bağlantıları ve verileri çekme işlevleri\n", "class Database:\n", " @staticmethod\n", " def get_mongodb():\n", " return get_mongodb()\n", "\n", " @staticmethod\n", " def get_titles_and_texts():\n", " # MongoDB bağlantısı ve koleksiyonları al\n", " train_collection, _ = Database.get_mongodb()\n", "\n", " # Sorgu: Hem \"title\" hem de \"text\" alanı mevcut olan belgeler\n", " query = {\"title\": {\"$exists\": True}, \"text\": {\"$exists\": True}}\n", "\n", " # Belirtilen alanları seçiyoruz: \"title\", \"text\"\n", " cursor = train_collection.find(query, {\"title\": 1, \"text\": 1, \"_id\": 0})\n", "\n", " # Başlık ve metinleri doğru bir şekilde birleştiriyoruz\n", " documents = [{\"title\": doc['title'], \"text\": doc['text']} for doc in cursor]\n", " document_count = len(documents)\n", " return documents, document_count\n", "\n", "# Train ve test datasetlerini MongoDB'ye yüklemek için fonksiyonu çağır\n", "train_file_path = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\train_Egitim\\\\merged_train.parquet'\n", "test_file_path = 'C:\\\\gitProjects\\\\yeni\\\\datasets\\\\test_Egitim\\\\merged_test.parquet'\n", "\n", "train_collection, test_collection = dataset_read(train_file_path, test_file_path)\n", "\n", "# Veritabanından başlıklar ve metinler alınır\n", "documents, document_count = Database.get_titles_and_texts()\n", "\n", "# Sonuçların belirlenmesi\n", "print(f\"Başlık ve metin çiftleri: {documents}\")\n", "print(f\"Toplam çift sayısı: {document_count}\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "MongoDb üzerinden title ve text verilerinin çekilmesi " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"\"\"@staticmethod\n", " def get_input_titles():\n", " collection = Database.get_mongodb(collection_name='train')\n", " query = {\"title\": {\"$exists\": True}}\n", " cursor = collection.find(query, {\"title\": 1, \"_id\": 0})\n", " title_from_db = [doc['title'] for doc in cursor]\n", "\n", " return title_from_db\"\"\"\n", "\n", "\"\"\"@staticmethod\n", " def get_input_texts():\n", " collection = Database.get_mongodb(collection_name='train')\n", " query = {\"texts\": {\"$exists\": True}}\n", " cursor = collection.find(query, {\"texts\": 1, \"_id\": 0})\n", " texts_from_db = [doc['texts'] for doc in cursor]\n", " return texts_from_db\"\"\"\n", " \n", " #bin tane veri çekerek csv dosyası olarak kaydetme \n", " \n", " \n", "\"\"\"@staticmethod\n", " def get_titles_and_texts(batch_size=1000):\n", "\n", " \n", " titles = Database.get_input_titles(batch_size=batch_size)\n", " texts = Database.get_input_texts(batch_size=batch_size )\n", " \n", "\n", "\n", " def test_queries():\n", "\n", " collection = Database.get_mongodb(collection_name='train')\n", " # Başlık sorgusu\n", " titles_cursor = collection.find({\"title\": {\"$exists\": True}}, {\"title\": 1, \"_id\": 0})\n", " titles = [doc['title'] for doc in titles_cursor]\n", " \n", "\n", " # Metin sorgusu\n", " texts_cursor = collection.find({\"text\": {\"$exists\": True}}, {\"text\": 1, \"_id\": 0})\n", " texts = [doc['text'] for doc in texts_cursor]\n", " \n", " # Başlık ve metinlerin eşleşmesini sağlamak için zip kullanarak birleştiriyoruz\n", " documents = [{\"title\": title, \"text\": text} for title, text in zip(titles, texts)]\n", " document_count = len(documents)\n", " return documents, document_count\n", "\n", "Database.test_queries()\n", "\n", "# Veritabanından başlıklar ve metinler alınır\n", "documents, document_count = Database.get_titles_and_texts(batch_size=1000)\n", "\n", "# Sonuçların belirlenmesi\n", "print(f\"Başlık ve metin çiftleri: {documents}\")\n", "print(f\"Toplam çift sayısı: {document_count}\")\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Output'u vereceğimiz title ve textin kodu" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 **Pşıqo Ahecaqo** Pşıqo Ahecaqo (), Çerkes siy...\n", "1 **Craterolophinae** Craterolophinae, Depastrid...\n", "2 **Notocrabro** Notocrabro Crabronina oymağına ...\n", "3 **Ibrahim Sissoko** İbrahim Sissoko (d. 30 Kas...\n", "4 **Salah Cedid** Salah Cedid (1926-1993) (Arapç...\n", "Name: combined, dtype: object\n", "Veriler combined_output.csv dosyasına başarıyla kaydedildi.\n" ] } ], "source": [ "from pymongo import MongoClient\n", "import pandas as pd\n", "from tqdm.auto import tqdm, trange\n", "\n", "# Database bağlantıları ve verileri çekme işlevleri\n", "class Database:\n", " @staticmethod\n", " def get_mongodb(database_name='EgitimDatabase', train_collection_name='train', test_collection_name='test', host='localhost', port=27017):\n", " client = MongoClient(f'mongodb://{host}:{port}/')\n", " db = client[database_name]\n", " train_collection = db[train_collection_name]\n", " test_collection = db[test_collection_name]\n", " return train_collection, test_collection\n", "\n", " def export_to_csv(batch_size=1000, output_file='combined_output.csv'):\n", " train_collection, _ = Database.get_mongodb()\n", " cursor = train_collection.find({}, {\"title\": 1, \"text\": 1, \"_id\": 0})\n", " cursor = cursor.batch_size(batch_size) # Fix: Call batch_size on the cursor object\n", "\n", " # Verileri DataFrame'e dönüştürme\n", " df= pd.DataFrame(list(cursor))\n", " \n", " # title ve text sütunlarını birleştirme\n", " df['combined'] = df.apply(lambda row: f'**{row[\"title\"]}** {row[\"text\"]}', axis=1)\n", " \n", " #title,text and combined sütunlarını ayrı ayrı tutma\n", " #df2['title_only'] = df2['title']\n", " #df2['text_only'] = df2['text']\n", " #df['combined']= output_file\n", "\n", " # Sonuçları kontrol etme\n", " combined_text= df['combined'] \n", " # Print the combined column directly\n", " \n", " print(combined_text.head())\n", "\n", " # Birleşmiş verileri CSV'ye kaydetme\n", " \n", " df.to_csv(output_file, index=False)\n", " \n", " print(f\"Veriler combined_output.csv dosyasına başarıyla kaydedildi.\")\n", " \n", "\n", "# CSV dosyasını okuma ve birleştirme işlemi\n", "Database.export_to_csv()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "TF-IDF HESAPLAMA" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Token vektörlerinin ortalamasını alarak metin düzeyinde özet oluşturacak şekilde k-means ve tf-ıdf algoritmalarını kullanarak keyword oluşturmak " ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tokens: ['[CLS]', 'Biy', '##ografi', 'İsim', 'P', '##şı', '##q', '##o', 'ismi', 'Ah', '##ec', '##a', '##q', '##o', 'soy', 'ismi', '##dir', '.', 'Çerkes', '##lerin', '\"', '-', 'q', '##o', '\"', 'son', '##eki', 'ile', 'biten', 'hem', 'soya', '##d', '##ları', 'hem', 'de', 'lak', '##ap', '##ları', 'vardı', '.', 'Bu', 'ek', 'Türkçe', 'ad', '##lardaki', '\"', '-', 'oğlu', '\"', 'eki', '##yle', 'eş', 'anlamlı', '##dır', '.', 'P', '##şı', '##q', '##o', 'Türkçe', '\"', 'Beyoğlu', '\"', 'anlamına', 'gelen', 'bir', 'lak', '##ap', '##tır', '.', 'Erken', 'dönem', 'Çerkes', '##ler', 'tarihleri', '##ni', 'yazma', '##dıkları', 've', 'tüm', 'bilgiler', 'Rus', 'kaynaklarından', 'geldiği', 'için', 'Ah', '##ec', '##a', '##q', '##o', 'hakkında', 'pek', 'bir', 'şey', 'kayded', '##ilme', '##di', '.', '177', '##7', \"'\", 'de', 'Çerkes', '##ya', \"'\", 'nın', 'B', '##je', '##duğ', 'bölgesinde', 'doğdu', '.', 'Asker', '##î', 'eğitim', 'ile', 'büyüt', '##üldü', '.', 'Rus', '-', 'Çerkes', 'Savaşı', '##na', 'Katılım', '##ı', 'Birkaç', 'kaynak', ',', 'Ah', '##ec', '##a', '##q', '##o', \"'\", 'nun', 'tüm', 'Çerkes', '##ya', \"'\", 'da', 'saygı', 'duyulan', 'bir', 'kişi', 'olduğunu', 'belirtir', '.', 'En', 'az', '6', '.', '000', 'at', '##lı', '##dan', 'oluşan', 'kalıcı', 'bir', 'ordusu', 'vardı', 've', 'çatışmalar', 'sırasında', 'müfre', '##ze', '##si', '12', '.', '000', 'at', '##lı', '##ya', 'ulaşıyor', '##du', '.', 'Rus', 'birlikleri', '##ne', 'karşı', 'kazandığı', 'zafer', '##lerle', 'ünlü', '##y', '##dü', '.', 'Askeri', 'becerisi', '##nin', 'yanı', 'sıra', 'yetenekli', 'bir', 'devlet', 'adamı', '##ydı', '.', 'Ölüm', '18', '##37', 'yılında', 'Rus', 'tarafına', 'geçti', 've', 'bir', 'yıl', 'sonra', 'hastalık', '##tan', 'öldü', '.', 'Kaynak', '##ça', 'Çerkes', 'soylu', '##lar', '177', '##7', 'doğumlu', '##lar', '18', '##38', 'yılında', 'ölen', '##ler', 'Kafkas', 'Savaşı', \"'\", 'nda', 'kişiler', '[SEP]']\n", "Positive Average Embedding Shape: torch.Size([353])\n", "Positive Average Embedding: tensor([3.1219e-01, 1.1118e-02, 1.3312e-02, 8.7684e-02, 6.0835e-01, 4.2102e-01,\n", " 3.7467e-01, 2.5975e-01, 6.8351e-02, 1.1375e-01, 6.9892e-02, 3.4909e-01,\n", " 4.2718e-02, 6.9431e-01, 8.2034e-02, 4.9043e-01, 4.0028e-02, 2.4516e-02,\n", " 4.0203e-01, 1.7956e-01, 2.7692e-01, 4.2539e-01, 3.9989e-01, 1.1785e-01,\n", " 1.2440e-01, 1.7583e-01, 4.7179e-01, 3.4876e-01, 4.3870e-01, 3.8414e-01,\n", " 3.6902e-01, 2.5584e-01, 2.0225e-01, 1.4411e-01, 2.9933e-01, 3.6910e-01,\n", " 2.3893e-01, 6.0434e-01, 1.5669e-01, 3.6258e-01, 4.5186e-01, 3.8370e-01,\n", " 4.9858e-01, 1.1362e-02, 2.1302e-01, 3.4201e-01, 7.4201e-01, 7.6336e-02,\n", " 2.6290e-01, 2.3984e-01, 4.8434e-01, 4.7557e-01, 2.2432e-01, 3.5924e-01,\n", " 5.3896e-02, 1.0477e-01, 3.8852e-01, 2.9142e-01, 3.6626e-01, 7.9898e-02,\n", " 2.2686e-01, 2.3253e-02, 3.2550e+00, 1.1168e-01, 4.2853e-01, 7.7213e-02,\n", " 3.1671e-01, 5.6494e-01, 2.0392e-01, 5.1432e-02, 2.2806e-01, 4.0886e-01,\n", " 2.2627e-02, 2.4151e-01, 5.5605e-01, 2.1589e-01, 8.9567e-02, 4.1183e-01,\n", " 3.7691e-01, 6.1995e-02, 5.1504e-01, 4.9226e-01, 1.0083e-01, 1.9789e-01,\n", " 6.5205e-01, 3.4597e-02, 9.5440e-02, 6.5158e-01, 1.9009e-01, 1.1314e-01,\n", " 1.0752e-01, 4.7765e-01, 2.5196e-01, 1.3468e-01, 4.2977e-01, 2.7336e-01,\n", " 4.7672e-02, 2.3097e-01, 1.5998e-01, 3.8424e-01, 2.9264e-02, 7.9061e-02,\n", " 2.8095e-01, 2.0505e-01, 8.8469e-02, 1.6993e-01, 2.5519e-01, 5.7010e-01,\n", " 6.1551e-03, 7.0113e-02, 1.1820e-01, 5.2899e-01, 1.3287e-01, 1.0696e+00,\n", " 3.1219e-01, 1.1373e-01, 2.6080e-01, 6.1457e-03, 5.5064e-02, 5.2089e-01,\n", " 1.3195e-01, 4.0164e-01, 8.4919e-01, 1.8478e-02, 1.6000e-01, 3.3307e-01,\n", " 2.8522e-01, 1.7133e-01, 2.4794e-02, 1.7487e-01, 1.0915e-01, 2.5974e-01,\n", " 1.8174e-02, 8.9919e-02, 1.6508e+00, 4.9391e-01, 7.9321e-02, 3.2023e-02,\n", " 3.1216e-01, 3.5055e-01, 2.4602e-01, 4.0553e-01, 1.3428e-02, 4.7906e-01,\n", " 2.2494e-01, 3.5909e-01, 1.2861e-01, 9.8253e-02, 2.3110e-01, 3.1276e-01,\n", " 6.4092e-02, 2.7386e-01, 6.7687e-02, 3.0518e-02, 3.8880e-01, 2.8110e-01,\n", " 5.7723e-02, 4.2425e-01, 6.5768e-01, 8.4208e-02, 3.2153e-01, 5.6956e-01,\n", " 1.2256e-01, 4.2261e-01, 7.9419e-02, 1.5746e-01, 1.8869e-01, 4.1413e-01,\n", " 3.7192e-01, 5.4023e-02, 1.1605e-01, 4.2643e-01, 1.6004e-01, 2.1577e-01,\n", " 6.6576e-03, 4.4046e-01, 2.4404e-01, 8.1931e-02, 2.2825e-01, 8.8104e-02,\n", " 4.0676e-01, 1.6295e-01, 5.8565e-01, 3.9977e-01, 5.0630e-02, 6.7476e-02,\n", " 3.4367e-01, 1.8640e-01, 3.3172e-01, 2.6630e-02, 1.6500e-02, 2.6911e-01,\n", " 3.4227e-02, 9.7154e-01, 8.5149e-01, 1.0421e-01, 6.2897e-01, 1.8700e-02,\n", " 1.6866e-01, 3.2686e-01, 6.5600e-01, 2.9388e-02, 3.8548e-02, 1.5922e-01,\n", " 5.6203e-01, 3.1285e-01, 3.8763e-01, 1.6276e-01, 1.2610e-01, 3.5952e-01,\n", " 1.3288e-01, 6.0504e-01, 2.9626e-01, 2.7285e-03, 3.7191e-01, 4.7557e-01,\n", " 9.2435e-02, 2.3198e-01, 1.8715e-01, 2.5481e-01, 3.2795e-01, 4.5814e-01,\n", " 1.9183e-01, 2.7146e-01, 1.9477e-01, 5.7984e-03, 3.0490e-01, 9.8830e-03,\n", " 6.9638e-01, 9.4965e-02, 8.8206e-02, 2.3173e-01, 1.2170e-01, 4.5793e-01,\n", " 1.4489e-01, 2.2540e-01, 5.2360e-01, 2.7475e-01, 5.3707e-01, 9.3503e-02,\n", " 1.5903e-01, 3.4478e-01, 3.9456e-01, 1.7182e-01, 5.6727e-03, 2.7554e-01,\n", " 2.0691e-01, 1.6439e-01, 6.4637e-01, 1.3178e-01, 1.9076e-01, 2.2997e-01,\n", " 9.9676e-04, 2.3884e-01, 5.3464e-01, 2.7388e-01, 2.3122e-01, 3.2136e-01,\n", " 6.1094e-02, 1.6784e-01, 5.6459e-01, 4.4070e-01, 3.1866e-01, 4.1410e-01,\n", " 3.0922e-01, 5.3698e-01, 8.8994e-02, 4.1334e-01, 2.5389e-01, 6.0110e-01,\n", " 3.8342e-01, 3.5175e-02, 2.5660e-01, 8.5744e-01, 3.0483e-03, 3.4735e-01,\n", " 3.8450e-01, 3.9665e-01, 2.2100e-01, 6.5109e-02, 1.9003e-01, 7.4262e-02,\n", " 2.9763e-01, 1.4098e-01, 1.1544e-01, 3.2446e-01, 1.4054e-02, 1.6943e-01,\n", " 1.1417e-01, 3.3420e-01, 4.2107e-02, 4.9406e-01, 5.4846e-02, 2.4392e-01,\n", " 2.4391e-01, 2.1046e-01, 3.5563e-01, 1.6479e-01, 3.2559e-01, 4.0702e-01,\n", " 9.6086e-01, 1.3305e-01, 7.5751e-02, 2.7087e-01, 9.1068e-02, 4.7289e-01,\n", " 1.0613e-01, 1.3504e-01, 2.7304e-01, 1.1986e-01, 4.7432e-01, 3.9729e-01,\n", " 1.3385e-02, 1.6185e-01, 5.8601e-01, 5.8034e-01, 6.7479e-03, 2.1235e-01,\n", " 6.9211e-02, 1.1795e-01, 4.8630e-01, 3.5354e-01, 4.4272e-01, 2.5360e-01,\n", " 2.7441e-01, 4.9623e-01, 2.1623e-01, 8.4283e-02, 1.1040e-01, 3.7749e-02,\n", " 3.9097e-01, 2.7157e-02, 3.7090e-01, 3.6961e-01, 2.6829e-01, 1.7171e-01,\n", " 1.7970e-02, 1.2158e-01, 1.8717e-01, 3.5600e-01, 1.5203e-03, 2.1490e-01,\n", " 2.2720e-01, 1.4914e-02, 3.7205e-01, 3.4950e-01, 3.4466e-02, 5.8733e-01,\n", " 1.2950e-01, 2.3771e-01, 3.9440e-01, 1.0506e-01, 5.9232e-01])\n", "TF-IDF Keywords: [array([['rus', 'ahecaqo', 'türkçe', 'pşıqo', '1777', 'çerkes', '000',\n", " 'çerkesya', 'ölenler', 'ünlüydü', 'ölüm', 'yazmadıkları',\n", " 'ulaşıyordu', 'tarihlerini', 'çerkeslerin', 'çerkesler',\n", " 'çatışmalar', 'zaferlerle', 'öldü', 'soneki', 'soy', 'soyadları',\n", " 'soylular', 'sıra', 'savaşı', 'sim', 'saygı', 'ordusu', 'oluşan',\n", " 'olduğunu', 'müfrezesi', 'lakaptır', 'savaşına', 'qo', 'oğlu',\n", " 'kazandığı', 'kaynakça', 'kaynaklarından', 'kaynak',\n", " 'kaydedilmedi', 'katılımı', 'kalıcı', 'kafkas', 'ismidir',\n", " 'ismi', 'hastalıktan', 'hakkında', 'geçti', 'lakapları',\n", " 'kişiler', 'kişi', 'eş', 'geldiği', 'gelen', 'eğitim', 'dönem',\n", " 'erken', 'ekiyle', 'ek', 'devlet', 'büyütüldü', 'bölgesinde',\n", " 'bjeduğ', 'biyografi', 'duyulan', 'doğumlular', 'doğdu',\n", " 'beyoğlu', 'bilgiler', 'birliklerine', 'belirtir', 'askerî',\n", " 'becerisinin', 'atlıya', 'atlıdan', 'anlamlıdır', 'anlamına',\n", " 'askeri', 'adlardaki', '1838', 'adamıydı', '1837', '12']],\n", " dtype=object)]\n", "BERT Embeddings:\n", "Text 1 embedding shape: torch.Size([233, 768])\n" ] }, { "ename": "ValueError", "evalue": "setting an array element with a sequence.", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;31mTypeError\u001b[0m: float() argument must be a string or a real number, not 'csr_matrix'", "\nThe above exception was the direct cause of the following exception:\n", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[31], line 151\u001b[0m\n\u001b[0;32m 146\u001b[0m \u001b[38;5;124;03m\"\"\"# Liste halindeki TF-IDF değerlerini yazdırma\u001b[39;00m\n\u001b[0;32m 147\u001b[0m \u001b[38;5;124;03mprint(\"TF-IDF List:\")\u001b[39;00m\n\u001b[0;32m 148\u001b[0m \u001b[38;5;124;03mfor row in tfidf_list:\u001b[39;00m\n\u001b[0;32m 149\u001b[0m \u001b[38;5;124;03m print(row)\"\"\"\u001b[39;00m\n\u001b[0;32m 150\u001b[0m \u001b[38;5;66;03m# Anahtar kelimeler ve metin arasındaki cosine similarity hesaplama\u001b[39;00m\n\u001b[1;32m--> 151\u001b[0m similarity_score \u001b[38;5;241m=\u001b[39m \u001b[43mcosine_similarity\u001b[49m\u001b[43m(\u001b[49m\u001b[43m[\u001b[49m\u001b[43mkeywords_vector\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m[\u001b[49m\u001b[43mdocument_vector\u001b[49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 153\u001b[0m \u001b[38;5;66;03m# Her bir kelime için TF-IDF değerlerini yazdırma\u001b[39;00m\n\u001b[0;32m 154\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m doc_idx, doc \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(tfidf_scores):\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\utils\\_param_validation.py:213\u001b[0m, in \u001b[0;36mvalidate_params..decorator..wrapper\u001b[1;34m(*args, **kwargs)\u001b[0m\n\u001b[0;32m 207\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m 208\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m config_context(\n\u001b[0;32m 209\u001b[0m skip_parameter_validation\u001b[38;5;241m=\u001b[39m(\n\u001b[0;32m 210\u001b[0m prefer_skip_nested_validation \u001b[38;5;129;01mor\u001b[39;00m global_skip_validation\n\u001b[0;32m 211\u001b[0m )\n\u001b[0;32m 212\u001b[0m ):\n\u001b[1;32m--> 213\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m func(\u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[0;32m 214\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m InvalidParameterError \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m 215\u001b[0m \u001b[38;5;66;03m# When the function is just a wrapper around an estimator, we allow\u001b[39;00m\n\u001b[0;32m 216\u001b[0m \u001b[38;5;66;03m# the function to delegate validation to the estimator, but we replace\u001b[39;00m\n\u001b[0;32m 217\u001b[0m \u001b[38;5;66;03m# the name of the estimator by the name of the function in the error\u001b[39;00m\n\u001b[0;32m 218\u001b[0m \u001b[38;5;66;03m# message to avoid confusion.\u001b[39;00m\n\u001b[0;32m 219\u001b[0m msg \u001b[38;5;241m=\u001b[39m re\u001b[38;5;241m.\u001b[39msub(\n\u001b[0;32m 220\u001b[0m \u001b[38;5;124mr\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mparameter of \u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124mw+ must be\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 221\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mparameter of \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mfunc\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__qualname__\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m must be\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 222\u001b[0m \u001b[38;5;28mstr\u001b[39m(e),\n\u001b[0;32m 223\u001b[0m )\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\metrics\\pairwise.py:1679\u001b[0m, in \u001b[0;36mcosine_similarity\u001b[1;34m(X, Y, dense_output)\u001b[0m\n\u001b[0;32m 1635\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Compute cosine similarity between samples in X and Y.\u001b[39;00m\n\u001b[0;32m 1636\u001b[0m \n\u001b[0;32m 1637\u001b[0m \u001b[38;5;124;03mCosine similarity, or the cosine kernel, computes similarity as the\u001b[39;00m\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 1675\u001b[0m \u001b[38;5;124;03m [0.57..., 0.81...]])\u001b[39;00m\n\u001b[0;32m 1676\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m 1677\u001b[0m \u001b[38;5;66;03m# to avoid recursive import\u001b[39;00m\n\u001b[1;32m-> 1679\u001b[0m X, Y \u001b[38;5;241m=\u001b[39m \u001b[43mcheck_pairwise_arrays\u001b[49m\u001b[43m(\u001b[49m\u001b[43mX\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mY\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 1681\u001b[0m X_normalized \u001b[38;5;241m=\u001b[39m normalize(X, copy\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[0;32m 1682\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m X \u001b[38;5;129;01mis\u001b[39;00m Y:\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\metrics\\pairwise.py:185\u001b[0m, in \u001b[0;36mcheck_pairwise_arrays\u001b[1;34m(X, Y, precomputed, dtype, accept_sparse, force_all_finite, ensure_2d, copy)\u001b[0m\n\u001b[0;32m 175\u001b[0m X \u001b[38;5;241m=\u001b[39m Y \u001b[38;5;241m=\u001b[39m check_array(\n\u001b[0;32m 176\u001b[0m X,\n\u001b[0;32m 177\u001b[0m accept_sparse\u001b[38;5;241m=\u001b[39maccept_sparse,\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 182\u001b[0m ensure_2d\u001b[38;5;241m=\u001b[39mensure_2d,\n\u001b[0;32m 183\u001b[0m )\n\u001b[0;32m 184\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m--> 185\u001b[0m X \u001b[38;5;241m=\u001b[39m \u001b[43mcheck_array\u001b[49m\u001b[43m(\u001b[49m\n\u001b[0;32m 186\u001b[0m \u001b[43m \u001b[49m\u001b[43mX\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 187\u001b[0m \u001b[43m \u001b[49m\u001b[43maccept_sparse\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43maccept_sparse\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 188\u001b[0m \u001b[43m \u001b[49m\u001b[43mdtype\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdtype\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 189\u001b[0m \u001b[43m \u001b[49m\u001b[43mcopy\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcopy\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 190\u001b[0m \u001b[43m \u001b[49m\u001b[43mforce_all_finite\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mforce_all_finite\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 191\u001b[0m \u001b[43m \u001b[49m\u001b[43mestimator\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mestimator\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 192\u001b[0m \u001b[43m \u001b[49m\u001b[43mensure_2d\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mensure_2d\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 193\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 194\u001b[0m Y \u001b[38;5;241m=\u001b[39m check_array(\n\u001b[0;32m 195\u001b[0m Y,\n\u001b[0;32m 196\u001b[0m accept_sparse\u001b[38;5;241m=\u001b[39maccept_sparse,\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 201\u001b[0m ensure_2d\u001b[38;5;241m=\u001b[39mensure_2d,\n\u001b[0;32m 202\u001b[0m )\n\u001b[0;32m 204\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m precomputed:\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\utils\\validation.py:1012\u001b[0m, in \u001b[0;36mcheck_array\u001b[1;34m(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name)\u001b[0m\n\u001b[0;32m 1010\u001b[0m array \u001b[38;5;241m=\u001b[39m xp\u001b[38;5;241m.\u001b[39mastype(array, dtype, copy\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\n\u001b[0;32m 1011\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m-> 1012\u001b[0m array \u001b[38;5;241m=\u001b[39m \u001b[43m_asarray_with_order\u001b[49m\u001b[43m(\u001b[49m\u001b[43marray\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43morder\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43morder\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mdtype\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdtype\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mxp\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mxp\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 1013\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m ComplexWarning \u001b[38;5;28;01mas\u001b[39;00m complex_warning:\n\u001b[0;32m 1014\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[0;32m 1015\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mComplex data not supported\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;132;01m{}\u001b[39;00m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;241m.\u001b[39mformat(array)\n\u001b[0;32m 1016\u001b[0m ) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mcomplex_warning\u001b[39;00m\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\utils\\_array_api.py:751\u001b[0m, in \u001b[0;36m_asarray_with_order\u001b[1;34m(array, dtype, order, copy, xp, device)\u001b[0m\n\u001b[0;32m 749\u001b[0m array \u001b[38;5;241m=\u001b[39m numpy\u001b[38;5;241m.\u001b[39marray(array, order\u001b[38;5;241m=\u001b[39morder, dtype\u001b[38;5;241m=\u001b[39mdtype)\n\u001b[0;32m 750\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m--> 751\u001b[0m array \u001b[38;5;241m=\u001b[39m \u001b[43mnumpy\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43masarray\u001b[49m\u001b[43m(\u001b[49m\u001b[43marray\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43morder\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43morder\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mdtype\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdtype\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 753\u001b[0m \u001b[38;5;66;03m# At this point array is a NumPy ndarray. We convert it to an array\u001b[39;00m\n\u001b[0;32m 754\u001b[0m \u001b[38;5;66;03m# container that is consistent with the input's namespace.\u001b[39;00m\n\u001b[0;32m 755\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m xp\u001b[38;5;241m.\u001b[39masarray(array)\n", "\u001b[1;31mValueError\u001b[0m: setting an array element with a sequence." ] } ], "source": [ "#-------------------------tf-ıdf hesaplama\n", "import re\n", "import numpy as np\n", "import pandas as pd\n", "from nltk.stem import WordNetLemmatizer\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from nltk.corpus import stopwords as nltk_stopwords\n", "from transformers import BertTokenizer, BertModel\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "import torch\n", "import torch.nn.functional as F\n", "\n", "# BERT Tokenizer ve Model'i yükleyin\n", "tokenizer = BertTokenizer.from_pretrained('dbmdz/bert-base-turkish-cased')\n", "model = BertModel.from_pretrained('dbmdz/bert-base-turkish-cased')\n", "\n", "\n", "#-------------------------- burada turkish_stop_words'ü alıyoruz\n", "def load_stop_words(file_path):\n", " \"\"\"Stop words'leri dosyadan okuyarak bir liste oluşturur.\"\"\"\n", " with open(file_path, 'r', encoding='utf-8') as file:\n", " stop_words = [line.strip() for line in file if line.strip()]\n", " return stop_words\n", "\n", "# Türkçe stop words dosyasını yükleyin\n", "stop_words_list = load_stop_words('turkish_stop_words.txt')\n", "\n", "#gömülen kelimeleri k-means ile kümeleyebiliriz , benzerlik oranını hesaplamak için farklı algoritmalardan yararlanabiliriz.\n", "def get_bert_embeddings(text):\n", " inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True)\n", " with torch.no_grad():\n", " outputs = model(**inputs)\n", " # Son katmandaki gömme (embedding) çıktısını alın\n", " return inputs['input_ids'],outputs.last_hidden_state\n", "\n", "#--------------------------- textleri tokenize eden fonksiyon \n", "def get_token_embeddings(text):\n", " inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True)\n", " with torch.no_grad():\n", " outputs = model(**inputs)\n", " embeddings = outputs.last_hidden_state\n", " return embeddings\n", "\n", "#------------------------------------ token verilerinin ortalaması (eşik değer için)\n", "def average_embeddings(embeddings):\n", " # Token vektörlerinin ortalamasını alarak metin düzeyinde özet oluştur\n", " return torch.mean(embeddings, dim=1).squeeze()\n", "\n", "#keywordsler çıkarmak için kullanacağım fonksiyon \n", "def extract_keywords_tfidf(corpus,stop_words_list):\n", " \"\"\"TF-IDF ile anahtar kelimeleri çıkarır, stop words listesi ile birlikte kullanır.\"\"\"\n", " vectorizer = TfidfVectorizer(stop_words=stop_words_list)\n", " X = vectorizer.fit_transform(corpus)\n", " feature_names = vectorizer.get_feature_names_out()\n", " #scores = np.asarray(X.sum(axis=0)).flatten()\n", " sorted_keywords = [feature_names[i] for i in X.sum(axis=0).argsort()[0, ::-1]]\n", " #keywords = {feature_names[i]: scores[i] for i in range(len(feature_names))}\n", " #sorted_keywords = sorted(keywords.items(), key=lambda x: x[1], reverse=True)\n", " return sorted_keywords\n", "\n", "#tokenleri kelimelere dönüştürür ve listeler \n", "def decode_tokens(input_ids):\n", " # Token ID'lerini kelimelere dönüştür\n", " tokens = tokenizer.convert_ids_to_tokens(input_ids.squeeze().tolist())\n", " return tokens\n", "\n", "# Örnek metinler (buranın yerine combined_text kullanılacak)\n", "texts = [\"\"\"Biyografi\n", "İsim \n", "Pşıqo ismi Ahecaqo soy ismidir. Çerkeslerin \"-qo\" soneki ile biten hem soyadları hem de lakapları vardı. Bu ek Türkçe adlardaki \"-oğlu\" ekiyle eş anlamlıdır. Pşıqo Türkçe \"Beyoğlu\" anlamına gelen bir lakaptır.\n", "\n", "Erken dönem \n", "Çerkesler tarihlerini yazmadıkları ve tüm bilgiler Rus kaynaklarından geldiği için Ahecaqo hakkında pek bir şey kaydedilmedi. 1777'de Çerkesya'nın Bjeduğ bölgesinde doğdu. Askerî eğitim ile büyütüldü.\n", "\n", "Rus-Çerkes Savaşına Katılımı \n", "Birkaç kaynak, Ahecaqo'nun tüm Çerkesya'da saygı duyulan bir kişi olduğunu belirtir. En az 6.000 atlıdan oluşan kalıcı bir ordusu vardı ve çatışmalar sırasında müfrezesi 12.000 atlıya ulaşıyordu. Rus birliklerine karşı kazandığı zaferlerle ünlüydü. Askeri becerisinin yanı sıra yetenekli bir devlet adamıydı.\n", "\n", "Ölüm \n", "1837 yılında Rus tarafına geçti ve bir yıl sonra hastalıktan öldü.\n", "\n", "Kaynakça \n", "\n", "Çerkes soylular\n", "1777 doğumlular\n", "1838 yılında ölenler\n", "Kafkas Savaşı'nda kişiler \"\"\"]\n", " \n", " \n", "\n", "#token ıd leri ve bert gömme vektörleri\n", "for text in texts:\n", " input_ids,embeddings= get_bert_embeddings(text)\n", " \n", " # BERT gömme vektörlerini elde et\n", " #embeddings = [get_bert_embeddings(text) for text in texts]\n", "\n", " # Tokenları ve ortalama vektörleri al\n", " tokens = decode_tokens(input_ids)\n", " avg_embedding = average_embeddings(embeddings)\n", " #ortalama embedding değerlerinden sadece 0'dan büyük olanları alma\n", " positive_avg_embedding= avg_embedding[avg_embedding>0]\n", " # Eğer pozitif embedding değerleri varsa, çıktıyı yazdır\n", "\n", "if len(positive_avg_embedding) > 0:\n", " print(f\"Tokens: {tokens}\")\n", " print(f\"Positive Average Embedding Shape: {positive_avg_embedding.shape}\")\n", " print(f\"Positive Average Embedding: {positive_avg_embedding}\")\n", "else:\n", " print(\"No positive embedding values found.\")\n", "\n", " \n", "# TF-IDF anahtar kelimelerini çıkar\n", "keywords = extract_keywords_tfidf(texts,stop_words_list)\n", "print(\"TF-IDF Keywords:\", keywords)\n", "\n", "# Gösterim\n", "print(\"BERT Embeddings:\")\n", "for i, emb in enumerate(embeddings):\n", " print(f\"Text {i+1} embedding shape: {emb.shape}\")\n", "\n", "keywords_str = \" \".join([str(keyword) for keyword in keywords])\n", "\n", "\n", "#metinleri birleştirip tf-ıdf matrisini oluşturma\n", "# TF-IDF vektörleştirici oluşturma\n", "tfidf_vectorizer = TfidfVectorizer(stop_words=stop_words_list)\n", "corpus = [text, keywords_str]\n", "tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)\n", "\n", "# Anahtar kelimeler vektörünü ve diğer metin vektörünü ayırma\n", "keywords_vector = tfidf_matrix[1]\n", "document_vector = tfidf_matrix[0]\n", "keywords_vector_dense = keywords_vector.toarray()\n", "document_vector_dense = document_vector.toarray()\n", "\n", "# Kelimeleri ve TF-IDF değerlerini alma\n", "feature_names = tfidf_vectorizer.get_feature_names_out()\n", "tfidf_scores = tfidf_matrix.toarray()\n", "similarity_score = cosine_similarity(keywords_vector_dense, document_vector_dense)\n", "\n", "# TF-IDF matrisini dense formata çevirme\n", "dense_matrix = tfidf_matrix.todense()\n", "# Dense matrisi liste haline getirme\n", "tfidf_list = dense_matrix.tolist()\n", "\n", "\"\"\"# Liste halindeki TF-IDF değerlerini yazdırma\n", "print(\"TF-IDF List:\")\n", "for row in tfidf_list:\n", " print(row)\"\"\"\n", "# Anahtar kelimeler ve metin arasındaki cosine similarity hesaplama\n", "similarity_score = cosine_similarity([keywords_vector], [document_vector])\n", "\n", "# Her bir kelime için TF-IDF değerlerini yazdırma\n", "for doc_idx, doc in enumerate(tfidf_scores):\n", " print(f\"Document {doc_idx + 1}:\")\n", " for word_idx, score in enumerate(doc):\n", " print(f\"Word: {feature_names[word_idx]}, TF-IDF: {score:.4f}\")\n", " print(\"\\n\")\n", "\n", "# Sonucu yazdırma\n", "print(f\"Keywords ile metin arasındaki benzerlik: {similarity_score[0][0]}\")\n", "\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tokens: ['[CLS]', 'Biy', '##ografi', 'İsim', 'P', '##şı', '##q', '##o', 'ismi', 'Ah', '##ec', '##a', '##q', '##o', 'soy', 'ismi', '##dir', '.', 'Çerkes', '##lerin', '\"', '-', 'q', '##o', '\"', 'son', '##eki', 'ile', 'biten', 'hem', 'soya', '##d', '##ları', 'hem', 'de', 'lak', '##ap', '##ları', 'vardı', '.', 'Bu', 'ek', 'Türkçe', 'ad', '##lardaki', '\"', '-', 'oğlu', '\"', 'eki', '##yle', 'eş', 'anlamlı', '##dır', '.', 'P', '##şı', '##q', '##o', 'Türkçe', '\"', 'Beyoğlu', '\"', 'anlamına', 'gelen', 'bir', 'lak', '##ap', '##tır', '.', 'Erken', 'dönem', 'Çerkes', '##ler', 'tarihleri', '##ni', 'yazma', '##dıkları', 've', 'tüm', 'bilgiler', 'Rus', 'kaynaklarından', 'geldiği', 'için', 'Ah', '##ec', '##a', '##q', '##o', 'hakkında', 'pek', 'bir', 'şey', 'kayded', '##ilme', '##di', '.', '177', '##7', \"'\", 'de', 'Çerkes', '##ya', \"'\", 'nın', 'B', '##je', '##duğ', 'bölgesinde', 'doğdu', '.', 'Asker', '##î', 'eğitim', 'ile', 'büyüt', '##üldü', '.', 'Rus', '-', 'Çerkes', 'Savaşı', '##na', 'Katılım', '##ı', 'Birkaç', 'kaynak', ',', 'Ah', '##ec', '##a', '##q', '##o', \"'\", 'nun', 'tüm', 'Çerkes', '##ya', \"'\", 'da', 'saygı', 'duyulan', 'bir', 'kişi', 'olduğunu', 'belirtir', '.', 'En', 'az', '6', '.', '000', 'at', '##lı', '##dan', 'oluşan', 'kalıcı', 'bir', 'ordusu', 'vardı', 've', 'çatışmalar', 'sırasında', 'müfre', '##ze', '##si', '12', '.', '000', 'at', '##lı', '##ya', 'ulaşıyor', '##du', '.', 'Rus', 'birlikleri', '##ne', 'karşı', 'kazandığı', 'zafer', '##lerle', 'ünlü', '##y', '##dü', '.', 'Askeri', 'becerisi', '##nin', 'yanı', 'sıra', 'yetenekli', 'bir', 'devlet', 'adamı', '##ydı', '.', 'Ölüm', '18', '##37', 'yılında', 'Rus', 'tarafına', 'geçti', 've', 'bir', 'yıl', 'sonra', 'hastalık', '##tan', 'öldü', '.', 'Kaynak', '##ça', 'Çerkes', 'soylu', '##lar', '177', '##7', 'doğumlu', '##lar', '18', '##38', 'yılında', 'ölen', '##ler', 'Kafkas', 'Savaşı', \"'\", 'nda', 'kişiler', '[SEP]']\n", "Positive Average Embedding Shape: torch.Size([353])\n", "Positive Average Embedding: tensor([3.1219e-01, 1.1118e-02, 1.3312e-02, 8.7684e-02, 6.0835e-01, 4.2102e-01,\n", " 3.7467e-01, 2.5975e-01, 6.8351e-02, 1.1375e-01, 6.9892e-02, 3.4909e-01,\n", " 4.2718e-02, 6.9431e-01, 8.2034e-02, 4.9043e-01, 4.0028e-02, 2.4516e-02,\n", " 4.0203e-01, 1.7956e-01, 2.7692e-01, 4.2539e-01, 3.9989e-01, 1.1785e-01,\n", " 1.2440e-01, 1.7583e-01, 4.7179e-01, 3.4876e-01, 4.3870e-01, 3.8414e-01,\n", " 3.6902e-01, 2.5584e-01, 2.0225e-01, 1.4411e-01, 2.9933e-01, 3.6910e-01,\n", " 2.3893e-01, 6.0434e-01, 1.5669e-01, 3.6258e-01, 4.5186e-01, 3.8370e-01,\n", " 4.9858e-01, 1.1362e-02, 2.1302e-01, 3.4201e-01, 7.4201e-01, 7.6336e-02,\n", " 2.6290e-01, 2.3984e-01, 4.8434e-01, 4.7557e-01, 2.2432e-01, 3.5924e-01,\n", " 5.3896e-02, 1.0477e-01, 3.8852e-01, 2.9142e-01, 3.6626e-01, 7.9898e-02,\n", " 2.2686e-01, 2.3253e-02, 3.2550e+00, 1.1168e-01, 4.2853e-01, 7.7213e-02,\n", " 3.1671e-01, 5.6494e-01, 2.0392e-01, 5.1432e-02, 2.2806e-01, 4.0886e-01,\n", " 2.2627e-02, 2.4151e-01, 5.5605e-01, 2.1589e-01, 8.9567e-02, 4.1183e-01,\n", " 3.7691e-01, 6.1995e-02, 5.1504e-01, 4.9226e-01, 1.0083e-01, 1.9789e-01,\n", " 6.5205e-01, 3.4597e-02, 9.5440e-02, 6.5158e-01, 1.9009e-01, 1.1314e-01,\n", " 1.0752e-01, 4.7765e-01, 2.5196e-01, 1.3468e-01, 4.2977e-01, 2.7336e-01,\n", " 4.7672e-02, 2.3097e-01, 1.5998e-01, 3.8424e-01, 2.9264e-02, 7.9061e-02,\n", " 2.8095e-01, 2.0505e-01, 8.8469e-02, 1.6993e-01, 2.5519e-01, 5.7010e-01,\n", " 6.1551e-03, 7.0113e-02, 1.1820e-01, 5.2899e-01, 1.3287e-01, 1.0696e+00,\n", " 3.1219e-01, 1.1373e-01, 2.6080e-01, 6.1457e-03, 5.5064e-02, 5.2089e-01,\n", " 1.3195e-01, 4.0164e-01, 8.4919e-01, 1.8478e-02, 1.6000e-01, 3.3307e-01,\n", " 2.8522e-01, 1.7133e-01, 2.4794e-02, 1.7487e-01, 1.0915e-01, 2.5974e-01,\n", " 1.8174e-02, 8.9919e-02, 1.6508e+00, 4.9391e-01, 7.9321e-02, 3.2023e-02,\n", " 3.1216e-01, 3.5055e-01, 2.4602e-01, 4.0553e-01, 1.3428e-02, 4.7906e-01,\n", " 2.2494e-01, 3.5909e-01, 1.2861e-01, 9.8253e-02, 2.3110e-01, 3.1276e-01,\n", " 6.4092e-02, 2.7386e-01, 6.7687e-02, 3.0518e-02, 3.8880e-01, 2.8110e-01,\n", " 5.7723e-02, 4.2425e-01, 6.5768e-01, 8.4208e-02, 3.2153e-01, 5.6956e-01,\n", " 1.2256e-01, 4.2261e-01, 7.9419e-02, 1.5746e-01, 1.8869e-01, 4.1413e-01,\n", " 3.7192e-01, 5.4023e-02, 1.1605e-01, 4.2643e-01, 1.6004e-01, 2.1577e-01,\n", " 6.6576e-03, 4.4046e-01, 2.4404e-01, 8.1931e-02, 2.2825e-01, 8.8104e-02,\n", " 4.0676e-01, 1.6295e-01, 5.8565e-01, 3.9977e-01, 5.0630e-02, 6.7476e-02,\n", " 3.4367e-01, 1.8640e-01, 3.3172e-01, 2.6630e-02, 1.6500e-02, 2.6911e-01,\n", " 3.4227e-02, 9.7154e-01, 8.5149e-01, 1.0421e-01, 6.2897e-01, 1.8700e-02,\n", " 1.6866e-01, 3.2686e-01, 6.5600e-01, 2.9388e-02, 3.8548e-02, 1.5922e-01,\n", " 5.6203e-01, 3.1285e-01, 3.8763e-01, 1.6276e-01, 1.2610e-01, 3.5952e-01,\n", " 1.3288e-01, 6.0504e-01, 2.9626e-01, 2.7285e-03, 3.7191e-01, 4.7557e-01,\n", " 9.2435e-02, 2.3198e-01, 1.8715e-01, 2.5481e-01, 3.2795e-01, 4.5814e-01,\n", " 1.9183e-01, 2.7146e-01, 1.9477e-01, 5.7984e-03, 3.0490e-01, 9.8830e-03,\n", " 6.9638e-01, 9.4965e-02, 8.8206e-02, 2.3173e-01, 1.2170e-01, 4.5793e-01,\n", " 1.4489e-01, 2.2540e-01, 5.2360e-01, 2.7475e-01, 5.3707e-01, 9.3503e-02,\n", " 1.5903e-01, 3.4478e-01, 3.9456e-01, 1.7182e-01, 5.6727e-03, 2.7554e-01,\n", " 2.0691e-01, 1.6439e-01, 6.4637e-01, 1.3178e-01, 1.9076e-01, 2.2997e-01,\n", " 9.9676e-04, 2.3884e-01, 5.3464e-01, 2.7388e-01, 2.3122e-01, 3.2136e-01,\n", " 6.1094e-02, 1.6784e-01, 5.6459e-01, 4.4070e-01, 3.1866e-01, 4.1410e-01,\n", " 3.0922e-01, 5.3698e-01, 8.8994e-02, 4.1334e-01, 2.5389e-01, 6.0110e-01,\n", " 3.8342e-01, 3.5175e-02, 2.5660e-01, 8.5744e-01, 3.0483e-03, 3.4735e-01,\n", " 3.8450e-01, 3.9665e-01, 2.2100e-01, 6.5109e-02, 1.9003e-01, 7.4262e-02,\n", " 2.9763e-01, 1.4098e-01, 1.1544e-01, 3.2446e-01, 1.4054e-02, 1.6943e-01,\n", " 1.1417e-01, 3.3420e-01, 4.2107e-02, 4.9406e-01, 5.4846e-02, 2.4392e-01,\n", " 2.4391e-01, 2.1046e-01, 3.5563e-01, 1.6479e-01, 3.2559e-01, 4.0702e-01,\n", " 9.6086e-01, 1.3305e-01, 7.5751e-02, 2.7087e-01, 9.1068e-02, 4.7289e-01,\n", " 1.0613e-01, 1.3504e-01, 2.7304e-01, 1.1986e-01, 4.7432e-01, 3.9729e-01,\n", " 1.3385e-02, 1.6185e-01, 5.8601e-01, 5.8034e-01, 6.7479e-03, 2.1235e-01,\n", " 6.9211e-02, 1.1795e-01, 4.8630e-01, 3.5354e-01, 4.4272e-01, 2.5360e-01,\n", " 2.7441e-01, 4.9623e-01, 2.1623e-01, 8.4283e-02, 1.1040e-01, 3.7749e-02,\n", " 3.9097e-01, 2.7157e-02, 3.7090e-01, 3.6961e-01, 2.6829e-01, 1.7171e-01,\n", " 1.7970e-02, 1.2158e-01, 1.8717e-01, 3.5600e-01, 1.5203e-03, 2.1490e-01,\n", " 2.2720e-01, 1.4914e-02, 3.7205e-01, 3.4950e-01, 3.4466e-02, 5.8733e-01,\n", " 1.2950e-01, 2.3771e-01, 3.9440e-01, 1.0506e-01, 5.9232e-01])\n", "TF-IDF Keywords: [array([['rus', 'ahecaqo', 'türkçe', 'pşıqo', '1777', 'çerkes', '000',\n", " 'çerkesya', 'ölenler', 'ünlüydü', 'ölüm', 'yazmadıkları',\n", " 'ulaşıyordu', 'tarihlerini', 'çerkeslerin', 'çerkesler',\n", " 'çatışmalar', 'zaferlerle', 'öldü', 'soneki', 'soy', 'soyadları',\n", " 'soylular', 'sıra', 'savaşı', 'sim', 'saygı', 'ordusu', 'oluşan',\n", " 'olduğunu', 'müfrezesi', 'lakaptır', 'savaşına', 'qo', 'oğlu',\n", " 'kazandığı', 'kaynakça', 'kaynaklarından', 'kaynak',\n", " 'kaydedilmedi', 'katılımı', 'kalıcı', 'kafkas', 'ismidir',\n", " 'ismi', 'hastalıktan', 'hakkında', 'geçti', 'lakapları',\n", " 'kişiler', 'kişi', 'eş', 'geldiği', 'gelen', 'eğitim', 'dönem',\n", " 'erken', 'ekiyle', 'ek', 'devlet', 'büyütüldü', 'bölgesinde',\n", " 'bjeduğ', 'biyografi', 'duyulan', 'doğumlular', 'doğdu',\n", " 'beyoğlu', 'bilgiler', 'birliklerine', 'belirtir', 'askerî',\n", " 'becerisinin', 'atlıya', 'atlıdan', 'anlamlıdır', 'anlamına',\n", " 'askeri', 'adlardaki', '1838', 'adamıydı', '1837', '12']],\n", " dtype=object)]\n" ] }, { "ename": "TypeError", "evalue": "sequence item 0: expected str instance, numpy.ndarray found", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[32], line 96\u001b[0m\n\u001b[0;32m 94\u001b[0m \u001b[38;5;66;03m# TF-IDF matrisini oluşturma\u001b[39;00m\n\u001b[0;32m 95\u001b[0m tfidf_vectorizer \u001b[38;5;241m=\u001b[39m TfidfVectorizer(stop_words\u001b[38;5;241m=\u001b[39mstop_words_list)\n\u001b[1;32m---> 96\u001b[0m corpus \u001b[38;5;241m=\u001b[39m [\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43m \u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mjoin\u001b[49m\u001b[43m(\u001b[49m\u001b[43mkeywords\u001b[49m\u001b[43m)\u001b[49m] \u001b[38;5;66;03m# Anahtar kelimeleri string olarak birleştir\u001b[39;00m\n\u001b[0;32m 97\u001b[0m tfidf_matrix \u001b[38;5;241m=\u001b[39m tfidf_vectorizer\u001b[38;5;241m.\u001b[39mfit_transform(corpus \u001b[38;5;241m+\u001b[39m texts)\n\u001b[0;32m 99\u001b[0m \u001b[38;5;66;03m# Anahtar kelimeler vektörünü ve diğer metin vektörünü ayırma\u001b[39;00m\n", "\u001b[1;31mTypeError\u001b[0m: sequence item 0: expected str instance, numpy.ndarray found" ] } ], "source": [ "import re\n", "import numpy as np\n", "import pandas as pd\n", "from nltk.stem import WordNetLemmatizer\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from nltk.corpus import stopwords as nltk_stopwords\n", "from transformers import BertTokenizer, BertModel\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "import torch\n", "import torch.nn.functional as F\n", "\n", "# BERT Tokenizer ve Model'i yükleyin\n", "tokenizer = BertTokenizer.from_pretrained('dbmdz/bert-base-turkish-cased')\n", "model = BertModel.from_pretrained('dbmdz/bert-base-turkish-cased')\n", "\n", "#-------------------------- burada turkish_stop_words'ü alıyoruz\n", "def load_stop_words(file_path):\n", " \"\"\"Stop words'leri dosyadan okuyarak bir liste oluşturur.\"\"\"\n", " with open(file_path, 'r', encoding='utf-8') as file:\n", " stop_words = [line.strip() for line in file if line.strip()]\n", " return stop_words\n", "\n", "# Türkçe stop words dosyasını yükleyin\n", "stop_words_list = load_stop_words('turkish_stop_words.txt')\n", "\n", "# Gömülü kelimeleri k-means ile kümeleyebiliriz , benzerlik oranını hesaplamak için farklı algoritmalardan yararlanabiliriz.\n", "def get_bert_embeddings(text):\n", " inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True)\n", " with torch.no_grad():\n", " outputs = model(**inputs)\n", " # Son katmandaki gömme (embedding) çıktısını alın\n", " return inputs['input_ids'], outputs.last_hidden_state\n", "\n", "#------------------------------------ token verilerinin ortalaması (eşik değer için)\n", "def average_embeddings(embeddings):\n", " # Token vektörlerinin ortalamasını alarak metin düzeyinde özet oluştur\n", " return torch.mean(embeddings, dim=1).squeeze()\n", "\n", "# Keywords çıkarma fonksiyonu\n", "def extract_keywords_tfidf(corpus, stop_words_list):\n", " \"\"\"TF-IDF ile anahtar kelimeleri çıkarır, stop words listesi ile birlikte kullanır.\"\"\"\n", " vectorizer = TfidfVectorizer(stop_words=stop_words_list)\n", " X = vectorizer.fit_transform(corpus)\n", " feature_names = vectorizer.get_feature_names_out()\n", " sorted_keywords = [feature_names[i] for i in X.sum(axis=0).argsort()[0, ::-1]]\n", " return sorted_keywords\n", "\n", "# Tokenları kelimelere dönüştürür ve listeler \n", "def decode_tokens(input_ids):\n", " tokens = tokenizer.convert_ids_to_tokens(input_ids.squeeze().tolist())\n", " return tokens\n", "\n", "# Örnek metinler (buranın yerine combined_text kullanılacak)\n", "texts = [\"\"\"Biyografi\n", "İsim \n", "Pşıqo ismi Ahecaqo soy ismidir. Çerkeslerin \"-qo\" soneki ile biten hem soyadları hem de lakapları vardı. Bu ek Türkçe adlardaki \"-oğlu\" ekiyle eş anlamlıdır. Pşıqo Türkçe \"Beyoğlu\" anlamına gelen bir lakaptır.\n", "\n", "Erken dönem \n", "Çerkesler tarihlerini yazmadıkları ve tüm bilgiler Rus kaynaklarından geldiği için Ahecaqo hakkında pek bir şey kaydedilmedi. 1777'de Çerkesya'nın Bjeduğ bölgesinde doğdu. Askerî eğitim ile büyütüldü.\n", "\n", "Rus-Çerkes Savaşına Katılımı \n", "Birkaç kaynak, Ahecaqo'nun tüm Çerkesya'da saygı duyulan bir kişi olduğunu belirtir. En az 6.000 atlıdan oluşan kalıcı bir ordusu vardı ve çatışmalar sırasında müfrezesi 12.000 atlıya ulaşıyordu. Rus birliklerine karşı kazandığı zaferlerle ünlüydü. Askeri becerisinin yanı sıra yetenekli bir devlet adamıydı.\n", "\n", "Ölüm \n", "1837 yılında Rus tarafına geçti ve bir yıl sonra hastalıktan öldü.\n", "\n", "Kaynakça \n", "\n", "Çerkes soylular\n", "1777 doğumlular\n", "1838 yılında ölenler\n", "Kafkas Savaşı'nda kişiler \"\"\"]\n", "\n", "# Token id'leri ve BERT gömme vektörleri\n", "for text in texts:\n", " input_ids, embeddings = get_bert_embeddings(text)\n", " tokens = decode_tokens(input_ids)\n", " avg_embedding = average_embeddings(embeddings)\n", "\n", " # Ortalama embedding değerlerinden sadece 0'dan büyük olanları alma\n", " positive_avg_embedding = avg_embedding[avg_embedding > 0]\n", "\n", " if len(positive_avg_embedding) > 0:\n", " print(f\"Tokens: {tokens}\")\n", " print(f\"Positive Average Embedding Shape: {positive_avg_embedding.shape}\")\n", " print(f\"Positive Average Embedding: {positive_avg_embedding}\")\n", " else:\n", " print(\"No positive embedding values found.\")\n", "\n", "# TF-IDF anahtar kelimelerini çıkar\n", "keywords = extract_keywords_tfidf(texts, stop_words_list)\n", "print(\"TF-IDF Keywords:\", keywords)\n", "\n", "# TF-IDF matrisini oluşturma\n", "tfidf_vectorizer = TfidfVectorizer(stop_words=stop_words_list)\n", "corpus = [\" \".join(keywords)] # Anahtar kelimeleri string olarak birleştir\n", "tfidf_matrix = tfidf_vectorizer.fit_transform(corpus + texts)\n", "\n", "# Anahtar kelimeler vektörünü ve diğer metin vektörünü ayırma\n", "keywords_vector = tfidf_matrix[0]\n", "document_vectors = tfidf_matrix[1:]\n", "\n", "# Kelimeleri ve TF-IDF değerlerini alma\n", "feature_names = tfidf_vectorizer.get_feature_names_out()\n", "tfidf_scores = tfidf_matrix.toarray()\n", "\n", "# Cosine similarity hesaplama\n", "similarity_scores = cosine_similarity(keywords_vector, document_vectors)\n", "\n", "# Her bir kelime için TF-IDF değerlerini yazdırma\n", "for doc_idx, doc in enumerate(tfidf_scores[1:], start=1):\n", " print(f\"Document {doc_idx}:\")\n", " for word_idx, score in enumerate(doc):\n", " print(f\"Word: {feature_names[word_idx]}, TF-IDF: {score:.4f}\")\n", " print(\"\\n\")\n", "\n", "# Sonucu yazdırma\n", "print(f\"Keywords ile metin arasındaki benzerlik: {similarity_scores[0][0]}\")\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "\n", "A module that was compiled using NumPy 1.x cannot be run in\n", "NumPy 2.1.0 as it may crash. To support both 1.x and 2.x\n", "versions of NumPy, modules must be compiled with NumPy 2.0.\n", "Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.\n", "\n", "If you are a user of the module, the easiest solution will be to\n", "downgrade to 'numpy<2' or try to upgrade the affected module.\n", "We expect that some modules will need time to support NumPy 2.\n", "\n", "Traceback (most recent call last): File \"C:\\Users\\info\\AppData\\Local\\Programs\\Python\\Python310\\lib\\runpy.py\", line 196, in _run_module_as_main\n", " return _run_code(code, main_globals, None,\n", " File \"C:\\Users\\info\\AppData\\Local\\Programs\\Python\\Python310\\lib\\runpy.py\", line 86, in _run_code\n", " exec(code, run_globals)\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel_launcher.py\", line 18, in \n", " app.launch_new_instance()\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\traitlets\\config\\application.py\", line 1075, in launch_instance\n", " app.start()\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel\\kernelapp.py\", line 739, in start\n", " self.io_loop.start()\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\tornado\\platform\\asyncio.py\", line 205, in start\n", " self.asyncio_loop.run_forever()\n", " File \"C:\\Users\\info\\AppData\\Local\\Programs\\Python\\Python310\\lib\\asyncio\\base_events.py\", line 603, in run_forever\n", " self._run_once()\n", " File \"C:\\Users\\info\\AppData\\Local\\Programs\\Python\\Python310\\lib\\asyncio\\base_events.py\", line 1909, in _run_once\n", " handle._run()\n", " File \"C:\\Users\\info\\AppData\\Local\\Programs\\Python\\Python310\\lib\\asyncio\\events.py\", line 80, in _run\n", " self._context.run(self._callback, *self._args)\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 545, in dispatch_queue\n", " await self.process_one()\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 534, in process_one\n", " await dispatch(*args)\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 437, in dispatch_shell\n", " await result\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel\\ipkernel.py\", line 362, in execute_request\n", " await super().execute_request(stream, ident, parent)\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel\\kernelbase.py\", line 778, in execute_request\n", " reply_content = await reply_content\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel\\ipkernel.py\", line 449, in do_execute\n", " res = shell.run_cell(\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\ipykernel\\zmqshell.py\", line 549, in run_cell\n", " return super().run_cell(*args, **kwargs)\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3075, in run_cell\n", " result = self._run_cell(\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3130, in _run_cell\n", " result = runner(coro)\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\IPython\\core\\async_helpers.py\", line 128, in _pseudo_sync_runner\n", " coro.send(None)\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3334, in run_cell_async\n", " has_raised = await self.run_ast_nodes(code_ast.body, cell_name,\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3517, in run_ast_nodes\n", " if await self.run_code(code, result, async_=asy):\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\IPython\\core\\interactiveshell.py\", line 3577, in run_code\n", " exec(code_obj, self.user_global_ns, self.user_ns)\n", " File \"C:\\Users\\info\\AppData\\Local\\Temp\\ipykernel_17960\\3105833283.py\", line 7, in \n", " from transformers import BertTokenizer, BertModel\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\transformers\\__init__.py\", line 26, in \n", " from . import dependency_versions_check\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\transformers\\dependency_versions_check.py\", line 16, in \n", " from .utils.versions import require_version, require_version_core\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\transformers\\utils\\__init__.py\", line 34, in \n", " from .generic import (\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\transformers\\utils\\generic.py\", line 462, in \n", " import torch.utils._pytree as _torch_pytree\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\torch\\__init__.py\", line 2120, in \n", " from torch._higher_order_ops import cond\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\torch\\_higher_order_ops\\__init__.py\", line 1, in \n", " from .cond import cond\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\torch\\_higher_order_ops\\cond.py\", line 5, in \n", " import torch._subclasses.functional_tensor\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\torch\\_subclasses\\functional_tensor.py\", line 42, in \n", " class FunctionalTensor(torch.Tensor):\n", " File \"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\torch\\_subclasses\\functional_tensor.py\", line 258, in FunctionalTensor\n", " cpu = _conversion_method_template(device=torch.device(\"cpu\"))\n", "c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\torch\\_subclasses\\functional_tensor.py:258: UserWarning: Failed to initialize NumPy: _ARRAY_API not found (Triggered internally at C:\\actions-runner\\_work\\pytorch\\pytorch\\builder\\windows\\pytorch\\torch\\csrc\\utils\\tensor_numpy.cpp:84.)\n", " cpu = _conversion_method_template(device=torch.device(\"cpu\"))\n" ] }, { "ename": "NameError", "evalue": "name 'texts' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[1], line 62\u001b[0m\n\u001b[0;32m 59\u001b[0m tfidf_vectorizer \u001b[38;5;241m=\u001b[39m TfidfVectorizer()\n\u001b[0;32m 61\u001b[0m \u001b[38;5;66;03m# TF-IDF anahtar kelimelerini çıkar\u001b[39;00m\n\u001b[1;32m---> 62\u001b[0m keywords \u001b[38;5;241m=\u001b[39m extract_keywords_tfidf(\u001b[43mtexts\u001b[49m, stop_words_list)\n\u001b[0;32m 63\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTF-IDF Keywords:\u001b[39m\u001b[38;5;124m\"\u001b[39m, keywords)\n\u001b[0;32m 65\u001b[0m \u001b[38;5;66;03m# Transform the text and keywords into TF-IDF representations\u001b[39;00m\n", "\u001b[1;31mNameError\u001b[0m: name 'texts' is not defined" ] } ], "source": [ "from sklearn.feature_extraction.text import TfidfVectorizer\n", "import numpy as np\n", "import re\n", "import pandas as pd\n", "from nltk.stem import WordNetLemmatizer\n", "from nltk.corpus import stopwords as nltk_stopwords\n", "from transformers import BertTokenizer, BertModel\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "import torch\n", "import torch.nn.functional as F\n", "\n", "# BERT Tokenizer ve Model'i yükleyin\n", "tokenizer = BertTokenizer.from_pretrained('dbmdz/bert-base-turkish-cased')\n", "model = BertModel.from_pretrained('dbmdz/bert-base-turkish-cased')\n", "\n", "#-------------------------- burada turkish_stop_words'ü alıyoruz\n", "def load_stop_words(file_path):\n", " \"\"\"Stop words'leri dosyadan okuyarak bir liste oluşturur.\"\"\"\n", " with open(file_path, 'r', encoding='utf-8') as file:\n", " stop_words = [line.strip() for line in file if line.strip()]\n", " return stop_words\n", "\n", "# Keywords çıkarma fonksiyonu\n", "def extract_keywords_tfidf(corpus, stop_words_list):\n", " \"\"\"TF-IDF ile anahtar kelimeleri çıkarır, stop words listesi ile birlikte kullanır.\"\"\"\n", " vectorizer = TfidfVectorizer(stop_words=stop_words_list)\n", " X = vectorizer.fit_transform(corpus)\n", " feature_names = vectorizer.get_feature_names_out()\n", " sorted_keywords = [feature_names[i] for i in X.sum(axis=0).argsort()[0, ::-1]]\n", " return sorted_keywords\n", "\n", "# Türkçe stop words dosyasını yükleyin\n", "stop_words_list = load_stop_words('turkish_stop_words.txt')\n", "# Define the text\n", "text = \"\"\"Biyografi\n", "İsim \n", "Pşıqo ismi Ahecaqo soy ismidir. Çerkeslerin \"-qo\" soneki ile biten hem soyadları hem de lakapları vardı. Bu ek Türkçe adlardaki \"-oğlu\" ekiyle eş anlamlıdır. Pşıqo Türkçe \"Beyoğlu\" anlamına gelen bir lakaptır.\n", "\n", "Erken dönem \n", "Çerkesler tarihlerini yazmadıkları ve tüm bilgiler Rus kaynaklarından geldiği için Ahecaqo hakkında pek bir şey kaydedilmedi. 1777'de Çerkesya'nın Bjeduğ bölgesinde doğdu. Askerî eğitim ile büyütüldü.\n", "\n", "Rus-Çerkes Savaşına Katılımı \n", "Birkaç kaynak, Ahecaqo'nun tüm Çerkesya'da saygı duyulan bir kişi olduğunu belirtir. En az 6.000 atlıdan oluşan kalıcı bir ordusu vardı ve çatışmalar sırasında müfrezesi 12.000 atlıya ulaşıyordu. Rus birliklerine karşı kazandığı zaferlerle ünlüydü. Askeri becerisinin yanı sıra yetenekli bir devlet adamıydı.\n", "\n", "Ölüm \n", "1837 yılında Rus tarafına geçti ve bir yıl sonra hastalıktan öldü.\n", "\n", "Kaynakça \n", "\n", "Çerkes soylular\n", "1777 doğumlular\n", "1838 yılında ölenler\n", "Kafkas Savaşı'nda kişiler \"\"\"\n", "\n", "# Define the keywords\n", "#keywords = [\"rus\", \"ahecaqo\", \"türkçe\", \"pşıqo\", \"1777\", \"çerkes\", \"000\", \"çerkesya\", \"ölenler\", \"ünlüydü\"]\n", "\n", "# Create a TfidfVectorizer instance\n", "tfidf_vectorizer = TfidfVectorizer()\n", "\n", "# TF-IDF anahtar kelimelerini çıkar\n", "keywords = extract_keywords_tfidf(texts, stop_words_list)\n", "print(\"TF-IDF Keywords:\", keywords)\n", "\n", "# Transform the text and keywords into TF-IDF representations\n", "text_tfidf = tfidf_vectorizer.fit_transform([text]) #burada text'i de vetörize ediyoruz.\n", "keywords_tfidf = tfidf_vectorizer.transform(keywords)\n", "\n", "# Calculate the cosine similarity between the text and each keyword\n", "similarities = []\n", "for i in range(keywords_tfidf.shape[0]): #keyword_tfidf matrisinin satırları üzerinde dönfü tanımlıyoruz \n", " keyword_tfidf = keywords_tfidf[i, :] # matrisin i. değerini alıyoruz \n", " # `text_tfidf` ile `keyword_tfidf` arasındaki kosinüs benzerliğini hesaplıyoruz\n", " similarity = np.dot(text_tfidf, keyword_tfidf.T).toarray()[0][0]\n", " similarities.append((keywords[i], similarity))\n", "\n", "# Sort the similarities in descending order\n", "keyword_similarities = sorted(similarities, key=lambda x: x[1], reverse=True)\n", "\n", "\n", "\n", "# Print the top 10 keywords with their similarities\n", "print(\"Top 10 Keywords with Similarities:\")\n", "for keyword, similarity in keyword_similarities[:10]:\n", " print(f\"{keyword}: {similarity:.4f}\")" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'list' object has no attribute 'lower'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[24], line 14\u001b[0m\n\u001b[0;32m 12\u001b[0m tfidf_vectorizer \u001b[38;5;241m=\u001b[39m TfidfVectorizer(stop_words\u001b[38;5;241m=\u001b[39mstop_words_list)\n\u001b[0;32m 13\u001b[0m corpus \u001b[38;5;241m=\u001b[39m [text, keywords]\n\u001b[1;32m---> 14\u001b[0m tfidf_matrix \u001b[38;5;241m=\u001b[39m \u001b[43mtfidf_vectorizer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcorpus\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 16\u001b[0m \u001b[38;5;66;03m# Anahtar kelimeler vektörünü ve diğer metin vektörünü ayırma\u001b[39;00m\n\u001b[0;32m 17\u001b[0m keywords_vector \u001b[38;5;241m=\u001b[39m tfidf_matrix[\u001b[38;5;241m1\u001b[39m]\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:2091\u001b[0m, in \u001b[0;36mTfidfVectorizer.fit_transform\u001b[1;34m(self, raw_documents, y)\u001b[0m\n\u001b[0;32m 2084\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_params()\n\u001b[0;32m 2085\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf \u001b[38;5;241m=\u001b[39m TfidfTransformer(\n\u001b[0;32m 2086\u001b[0m norm\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mnorm,\n\u001b[0;32m 2087\u001b[0m use_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39muse_idf,\n\u001b[0;32m 2088\u001b[0m smooth_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msmooth_idf,\n\u001b[0;32m 2089\u001b[0m sublinear_tf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msublinear_tf,\n\u001b[0;32m 2090\u001b[0m )\n\u001b[1;32m-> 2091\u001b[0m X \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mraw_documents\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 2092\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf\u001b[38;5;241m.\u001b[39mfit(X)\n\u001b[0;32m 2093\u001b[0m \u001b[38;5;66;03m# X is already a transformed view of raw_documents so\u001b[39;00m\n\u001b[0;32m 2094\u001b[0m \u001b[38;5;66;03m# we set copy to False\u001b[39;00m\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\base.py:1473\u001b[0m, in \u001b[0;36m_fit_context..decorator..wrapper\u001b[1;34m(estimator, *args, **kwargs)\u001b[0m\n\u001b[0;32m 1466\u001b[0m estimator\u001b[38;5;241m.\u001b[39m_validate_params()\n\u001b[0;32m 1468\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m config_context(\n\u001b[0;32m 1469\u001b[0m skip_parameter_validation\u001b[38;5;241m=\u001b[39m(\n\u001b[0;32m 1470\u001b[0m prefer_skip_nested_validation \u001b[38;5;129;01mor\u001b[39;00m global_skip_validation\n\u001b[0;32m 1471\u001b[0m )\n\u001b[0;32m 1472\u001b[0m ):\n\u001b[1;32m-> 1473\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m fit_method(estimator, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:1372\u001b[0m, in \u001b[0;36mCountVectorizer.fit_transform\u001b[1;34m(self, raw_documents, y)\u001b[0m\n\u001b[0;32m 1364\u001b[0m warnings\u001b[38;5;241m.\u001b[39mwarn(\n\u001b[0;32m 1365\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mUpper case characters found in\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1366\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m vocabulary while \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlowercase\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1367\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m is True. These entries will not\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1368\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m be matched with any documents\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1369\u001b[0m )\n\u001b[0;32m 1370\u001b[0m \u001b[38;5;28;01mbreak\u001b[39;00m\n\u001b[1;32m-> 1372\u001b[0m vocabulary, X \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_count_vocab\u001b[49m\u001b[43m(\u001b[49m\u001b[43mraw_documents\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfixed_vocabulary_\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 1374\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mbinary:\n\u001b[0;32m 1375\u001b[0m X\u001b[38;5;241m.\u001b[39mdata\u001b[38;5;241m.\u001b[39mfill(\u001b[38;5;241m1\u001b[39m)\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:1259\u001b[0m, in \u001b[0;36mCountVectorizer._count_vocab\u001b[1;34m(self, raw_documents, fixed_vocab)\u001b[0m\n\u001b[0;32m 1257\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m doc \u001b[38;5;129;01min\u001b[39;00m raw_documents:\n\u001b[0;32m 1258\u001b[0m feature_counter \u001b[38;5;241m=\u001b[39m {}\n\u001b[1;32m-> 1259\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m feature \u001b[38;5;129;01min\u001b[39;00m \u001b[43manalyze\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdoc\u001b[49m\u001b[43m)\u001b[49m:\n\u001b[0;32m 1260\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m 1261\u001b[0m feature_idx \u001b[38;5;241m=\u001b[39m vocabulary[feature]\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:108\u001b[0m, in \u001b[0;36m_analyze\u001b[1;34m(doc, analyzer, tokenizer, ngrams, preprocessor, decoder, stop_words)\u001b[0m\n\u001b[0;32m 106\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m 107\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m preprocessor \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m--> 108\u001b[0m doc \u001b[38;5;241m=\u001b[39m \u001b[43mpreprocessor\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdoc\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 109\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m tokenizer \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m 110\u001b[0m doc \u001b[38;5;241m=\u001b[39m tokenizer(doc)\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:66\u001b[0m, in \u001b[0;36m_preprocess\u001b[1;34m(doc, accent_function, lower)\u001b[0m\n\u001b[0;32m 47\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Chain together an optional series of text preprocessing steps to\u001b[39;00m\n\u001b[0;32m 48\u001b[0m \u001b[38;5;124;03mapply to a document.\u001b[39;00m\n\u001b[0;32m 49\u001b[0m \n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 63\u001b[0m \u001b[38;5;124;03m preprocessed string\u001b[39;00m\n\u001b[0;32m 64\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m 65\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m lower:\n\u001b[1;32m---> 66\u001b[0m doc \u001b[38;5;241m=\u001b[39m \u001b[43mdoc\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mlower\u001b[49m()\n\u001b[0;32m 67\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m accent_function \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m 68\u001b[0m doc \u001b[38;5;241m=\u001b[39m accent_function(doc)\n", "\u001b[1;31mAttributeError\u001b[0m: 'list' object has no attribute 'lower'" ] } ], "source": [ "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "import numpy as np\n", "\n", "#metin ile keywordslerin benzerlik oranını hesaplama \n", "text,keywords\n", "\n", "# Metinleri birleştirip TF-IDF matrisini oluşturma\n", "# TF-IDF vektörleştirici oluşturma\n", "# Türkçe stop words dosyasını yükleyin\n", "stop_words_list = load_stop_words('turkish_stop_words.txt')\n", "tfidf_vectorizer = TfidfVectorizer(stop_words=stop_words_list)\n", "corpus = [text, keywords]\n", "tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)\n", "\n", "# Anahtar kelimeler vektörünü ve diğer metin vektörünü ayırma\n", "keywords_vector = tfidf_matrix[1]\n", "text_vector = tfidf_matrix[0]\n", "\n", "# Anahtar kelimeler ve metin arasındaki cosine similarity hesaplama\n", "similarity_score = cosine_similarity(keywords_vector, text_vector)\n", "\n", "# Sonucu yazdırma\n", "print(f\"Keywords ile metin arasındaki benzerlik: {similarity_score[0][0]}\")\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'function' object is not subscriptable", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[19], line 18\u001b[0m\n\u001b[0;32m 15\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m embeddings\n\u001b[0;32m 17\u001b[0m \u001b[38;5;66;03m# Compute BERT embeddings for the top 10 keywords\u001b[39;00m\n\u001b[1;32m---> 18\u001b[0m top_keywords \u001b[38;5;241m=\u001b[39m [keyword \u001b[38;5;28;01mfor\u001b[39;00m keyword, _ \u001b[38;5;129;01min\u001b[39;00m \u001b[43mextract_keywords_tfidf\u001b[49m\u001b[43m[\u001b[49m\u001b[43m:\u001b[49m\u001b[38;5;241;43m10\u001b[39;49m\u001b[43m]\u001b[49m]\n\u001b[0;32m 19\u001b[0m bert_embeddings \u001b[38;5;241m=\u001b[39m compute_bert_embeddings(top_keywords)\n\u001b[0;32m 21\u001b[0m \u001b[38;5;66;03m# Define a function to compute the similarity between two embeddings\u001b[39;00m\n", "\u001b[1;31mTypeError\u001b[0m: 'function' object is not subscriptable" ] } ], "source": [ "#------------------------------ tf-ıdf ve embedding benzerlik \n", "# Define a function to compute BERT embeddings for a list of keywords\n", "\n", "def compute_bert_embeddings(keywords):\n", " embeddings = []\n", " for keyword in keywords:\n", " inputs = tokenizer.encode_plus(\n", " keyword,\n", " add_special_tokens=True,\n", " max_length=512,\n", " return_attention_mask=True,\n", " return_tensors='pt'\n", " )\n", " outputs = model(inputs['input_ids'], attention_mask=inputs['attention_mask'])\n", " embeddings.append(outputs.last_hidden_state[:, 0, :]) # Take the embedding of the [CLS] token\n", " return embeddings\n", "\n", "# Compute BERT embeddings for the top 10 keywords\n", "top_keywords = [keyword for keyword, score in extract_keywords_tfidf[:10]]\n", "bert_embeddings = compute_bert_embeddings(top_keywords)\n", "\n", "# Define a function to compute the similarity between two embeddings\n", "def compute_similarity(embedding1, embedding2):\n", " return F.cosine_similarity(embedding1, embedding2)\n", "\n", "# Compute the similarity between the text and each keyword\n", "similarities = []\n", "for keyword_embedding in enumerate(bert_embeddings):\n", "\n", " keyword= top_keywords[i]\n", " score = extract_keywords_tfidf[i][1]\n", " similarity = compute_similarity(positive_avg_embedding, keyword_embedding)\n", " similarities.append(keyword,similarity.item()*score)\n", "\n", "# Combine the top 10 keywords with their similarities\n", "keyword_similarities = sorted(similarities, key=lambda x: x[1], reverse=True)\n", "# Combine the top 10 keywords with their similarities\n", "#keyword_similarities = list(zip(top_keywords, similarities))" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Keywords without stop words:\n", "[('bir', np.float64(0.5)), ('bu', np.float64(0.5)), ('cümledir', np.float64(0.5)), ('örnek', np.float64(0.5)), ('anahtar', np.float64(0.3779644730092272)), ('kelimeleri', np.float64(0.3779644730092272)), ('kullanarak', np.float64(0.3779644730092272)), ('stop', np.float64(0.3779644730092272)), ('türkçe', np.float64(0.3779644730092272)), ('words', np.float64(0.3779644730092272)), ('çıkarıyoruz', np.float64(0.3779644730092272))]\n", "\n", "Keywords with stop words:\n", "[('cümledir', np.float64(0.7071067811865476)), ('örnek', np.float64(0.7071067811865476)), ('anahtar', np.float64(0.3779644730092272)), ('kelimeleri', np.float64(0.3779644730092272)), ('kullanarak', np.float64(0.3779644730092272)), ('stop', np.float64(0.3779644730092272)), ('türkçe', np.float64(0.3779644730092272)), ('words', np.float64(0.3779644730092272)), ('çıkarıyoruz', np.float64(0.3779644730092272))]\n", "\n", "Keywords removed by stop words list:\n", "{'bu', 'bir'}\n", "\n", "New keywords added by stop words list:\n", "set()\n" ] } ], "source": [ "from sklearn.feature_extraction.text import TfidfVectorizer\n", "\n", "def test_stop_words_effectiveness(corpus, stop_words_list):\n", " \"\"\"Stop words listesinin etkisini test eder.\"\"\"\n", " # İlk olarak, stop words olmadan TF-IDF hesaplayın\n", " vectorizer_no_stop_words = TfidfVectorizer()\n", " X_no_stop_words = vectorizer_no_stop_words.fit_transform(corpus)\n", " feature_names_no_stop_words = vectorizer_no_stop_words.get_feature_names_out()\n", " scores_no_stop_words = np.asarray(X_no_stop_words.sum(axis=0)).flatten()\n", " keywords_no_stop_words = {feature_names_no_stop_words[i]: scores_no_stop_words[i] for i in range(len(feature_names_no_stop_words))}\n", " sorted_keywords_no_stop_words = sorted(keywords_no_stop_words.items(), key=lambda x: x[1], reverse=True)\n", "\n", " # Şimdi, stop words ile TF-IDF hesaplayın\n", " vectorizer_with_stop_words = TfidfVectorizer(stop_words=stop_words_list)\n", " X_with_stop_words = vectorizer_with_stop_words.fit_transform(corpus)\n", " feature_names_with_stop_words = vectorizer_with_stop_words.get_feature_names_out()\n", " scores_with_stop_words = np.asarray(X_with_stop_words.sum(axis=0)).flatten()\n", " keywords_with_stop_words = {feature_names_with_stop_words[i]: scores_with_stop_words[i] for i in range(len(feature_names_with_stop_words))}\n", " sorted_keywords_with_stop_words = sorted(keywords_with_stop_words.items(), key=lambda x: x[1], reverse=True)\n", " \n", " # Stop words listesi etkisini gözlemleyin\n", " print(\"Keywords without stop words:\")\n", " print(sorted_keywords_no_stop_words)\n", " \n", " print(\"\\nKeywords with stop words:\")\n", " print(sorted_keywords_with_stop_words)\n", " \n", " # Farklılıkları göster\n", " all_keywords_no_stop_words = set([kw[0] for kw in sorted_keywords_no_stop_words])\n", " all_keywords_with_stop_words = set([kw[0] for kw in sorted_keywords_with_stop_words])\n", " \n", " print(\"\\nKeywords removed by stop words list:\")\n", " print(all_keywords_no_stop_words - all_keywords_with_stop_words)\n", " \n", " print(\"\\nNew keywords added by stop words list:\")\n", " print(all_keywords_with_stop_words - all_keywords_no_stop_words)\n", "\n", "# Test verisi ve stop words listesi kullanarak test edin\n", "test_stop_words_effectiveness(texts, stop_words_list)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "K-nn ile Cosine Similarity " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#tf-ıdf değeleri arasınadki en çok metinde tekrarlanan ve anlam ilşikisi en yüksek olan kelimeleri kıyaslama \n", "model.most_similar(positive=[\"rus\",])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.metrics.pairwise import cosine_similarity\n", "\n", "# TF-IDF ile vektörleri oluştur\n", "vectorizer = TfidfVectorizer(stop_words=stop_words_list)\n", "tfidf_matrix = vectorizer.fit_transform(texts)\n", "\n", "# BERT ile elde edilen pozitif embedding'leri TF-IDF vektörlerine dönüştür\n", "# Bu adımda, her kelimenin veya metnin TF-IDF ağırlıklarıyla karşılaştırılması yapılacak\n", "\n", "def get_tfidf_vector_for_query(query, vectorizer):\n", " \"\"\"Sorgu metni için TF-IDF vektörü alır\"\"\"\n", " return vectorizer.transform([query])\n", "\n", "def calculate_similarity(tfidf_vector, embeddings):\n", " \"\"\"TF-IDF vektörü ile embeddings arasındaki cosine similarity hesaplar\"\"\"\n", " return cosine_similarity(tfidf_vector, embeddings)\n", "\n", "# Sorgu metnini tanımlayın ve TF-IDF vektörünü alın\n", "query_text = \"Nasılsın?\"\n", "query_tfidf_vector = get_tfidf_vector_for_query(query_text, vectorizer)\n", "\n", "# Cosine similarity hesaplayın\n", "similarity_scores = calculate_similarity(query_tfidf_vector, tfidf_matrix)\n", "\n", "# Sonuçları yazdırın\n", "print(\"Cosine Similarity Scores:\", similarity_scores)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.neighbors import NearestNeighbors\n", "\n", "def fit_knn_model(embeddings,n_neighbors=5):\n", " knn = NearestNeighbors(n_neighbors=n_neighbors, metric='cosine')\n", " knn.fit(embeddings)\n", " return knn\n", "\n", "embeddings= np.array([get_bert_embeddings(text) for text in texts])\n", "#knn\n", "knn_model=fit_knn_model(embeddings)\n", "\n", "\n", "#tf-ıdf değelriyle bert üzerinden elde ettiğimiz verlerin benzerliğini hesaplayacağız \n", "keywords" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "[nltk_data] Downloading package wordnet to\n", "[nltk_data] C:\\Users\\info\\AppData\\Roaming\\nltk_data...\n", "[nltk_data] Package wordnet is already up-to-date!\n", "[nltk_data] Downloading package omw-1.4 to\n", "[nltk_data] C:\\Users\\info\\AppData\\Roaming\\nltk_data...\n", "[nltk_data] Package omw-1.4 is already up-to-date!\n", "[nltk_data] Downloading package stopwords to\n", "[nltk_data] C:\\Users\\info\\AppData\\Roaming\\nltk_data...\n", "[nltk_data] Package stopwords is already up-to-date!\n" ] }, { "ename": "ValueError", "evalue": "empty vocabulary; perhaps the documents only contain stop words", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[20], line 100\u001b[0m\n\u001b[0;32m 97\u001b[0m documents, document_count \u001b[38;5;241m=\u001b[39m Database\u001b[38;5;241m.\u001b[39mget_input_documents()\n\u001b[0;32m 99\u001b[0m \u001b[38;5;66;03m# Calculate TF-IDF and get feature names\u001b[39;00m\n\u001b[1;32m--> 100\u001b[0m tfidf_matrix, feature_names \u001b[38;5;241m=\u001b[39m \u001b[43mDatabase\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcalculate_tfidf\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mturkish_stop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 102\u001b[0m \u001b[38;5;66;03m# Extract keywords\u001b[39;00m\n\u001b[0;32m 103\u001b[0m keywords \u001b[38;5;241m=\u001b[39m Database\u001b[38;5;241m.\u001b[39mextract_keywords(tfidf_matrix, feature_names, stop_words\u001b[38;5;241m=\u001b[39mturkish_stop_words)\n", "Cell \u001b[1;32mIn[20], line 43\u001b[0m, in \u001b[0;36mDatabase.calculate_tfidf\u001b[1;34m(documents, stop_words)\u001b[0m\n\u001b[0;32m 40\u001b[0m \u001b[38;5;129m@staticmethod\u001b[39m\n\u001b[0;32m 41\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcalculate_tfidf\u001b[39m(documents, stop_words):\n\u001b[0;32m 42\u001b[0m vectorizer \u001b[38;5;241m=\u001b[39m TfidfVectorizer(stop_words\u001b[38;5;241m=\u001b[39mstop_words, max_features\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m10000\u001b[39m,min_df\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m2\u001b[39m)\n\u001b[1;32m---> 43\u001b[0m tfidf_matrix \u001b[38;5;241m=\u001b[39m \u001b[43mvectorizer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 44\u001b[0m feature_names \u001b[38;5;241m=\u001b[39m vectorizer\u001b[38;5;241m.\u001b[39mget_feature_names_out()\n\u001b[0;32m 45\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m tfidf_matrix, feature_names\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:2091\u001b[0m, in \u001b[0;36mTfidfVectorizer.fit_transform\u001b[1;34m(self, raw_documents, y)\u001b[0m\n\u001b[0;32m 2084\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_params()\n\u001b[0;32m 2085\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf \u001b[38;5;241m=\u001b[39m TfidfTransformer(\n\u001b[0;32m 2086\u001b[0m norm\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mnorm,\n\u001b[0;32m 2087\u001b[0m use_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39muse_idf,\n\u001b[0;32m 2088\u001b[0m smooth_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msmooth_idf,\n\u001b[0;32m 2089\u001b[0m sublinear_tf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msublinear_tf,\n\u001b[0;32m 2090\u001b[0m )\n\u001b[1;32m-> 2091\u001b[0m X \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mraw_documents\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 2092\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf\u001b[38;5;241m.\u001b[39mfit(X)\n\u001b[0;32m 2093\u001b[0m \u001b[38;5;66;03m# X is already a transformed view of raw_documents so\u001b[39;00m\n\u001b[0;32m 2094\u001b[0m \u001b[38;5;66;03m# we set copy to False\u001b[39;00m\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\base.py:1473\u001b[0m, in \u001b[0;36m_fit_context..decorator..wrapper\u001b[1;34m(estimator, *args, **kwargs)\u001b[0m\n\u001b[0;32m 1466\u001b[0m estimator\u001b[38;5;241m.\u001b[39m_validate_params()\n\u001b[0;32m 1468\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m config_context(\n\u001b[0;32m 1469\u001b[0m skip_parameter_validation\u001b[38;5;241m=\u001b[39m(\n\u001b[0;32m 1470\u001b[0m prefer_skip_nested_validation \u001b[38;5;129;01mor\u001b[39;00m global_skip_validation\n\u001b[0;32m 1471\u001b[0m )\n\u001b[0;32m 1472\u001b[0m ):\n\u001b[1;32m-> 1473\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m fit_method(estimator, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:1372\u001b[0m, in \u001b[0;36mCountVectorizer.fit_transform\u001b[1;34m(self, raw_documents, y)\u001b[0m\n\u001b[0;32m 1364\u001b[0m warnings\u001b[38;5;241m.\u001b[39mwarn(\n\u001b[0;32m 1365\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mUpper case characters found in\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1366\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m vocabulary while \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlowercase\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1367\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m is True. These entries will not\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1368\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m be matched with any documents\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1369\u001b[0m )\n\u001b[0;32m 1370\u001b[0m \u001b[38;5;28;01mbreak\u001b[39;00m\n\u001b[1;32m-> 1372\u001b[0m vocabulary, X \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_count_vocab\u001b[49m\u001b[43m(\u001b[49m\u001b[43mraw_documents\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfixed_vocabulary_\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 1374\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mbinary:\n\u001b[0;32m 1375\u001b[0m X\u001b[38;5;241m.\u001b[39mdata\u001b[38;5;241m.\u001b[39mfill(\u001b[38;5;241m1\u001b[39m)\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:1278\u001b[0m, in \u001b[0;36mCountVectorizer._count_vocab\u001b[1;34m(self, raw_documents, fixed_vocab)\u001b[0m\n\u001b[0;32m 1276\u001b[0m vocabulary \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mdict\u001b[39m(vocabulary)\n\u001b[0;32m 1277\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m vocabulary:\n\u001b[1;32m-> 1278\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[0;32m 1279\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mempty vocabulary; perhaps the documents only contain stop words\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 1280\u001b[0m )\n\u001b[0;32m 1282\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m indptr[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m] \u001b[38;5;241m>\u001b[39m np\u001b[38;5;241m.\u001b[39miinfo(np\u001b[38;5;241m.\u001b[39mint32)\u001b[38;5;241m.\u001b[39mmax: \u001b[38;5;66;03m# = 2**31 - 1\u001b[39;00m\n\u001b[0;32m 1283\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m _IS_32BIT:\n", "\u001b[1;31mValueError\u001b[0m: empty vocabulary; perhaps the documents only contain stop words" ] } ], "source": [ "#---------------------------güncel en yeni \n", "from pymongo import MongoClient\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from textblob import TextBlob as tb\n", "import numpy as np\n", "import math\n", "from tqdm.auto import tqdm, trange\n", "import tensorflow as tf\n", "import nltk\n", "import re \n", "from nltk.stem import WordNetLemmatizer\n", "from nltk.corpus import stopwords\n", "\n", "turkish_stop_words = stopwords.words('turkish')\n", "\n", "nltk.download('wordnet')\n", "nltk.download('omw-1.4')\n", "nltk.download('stopwords')\n", "\n", "\n", "import matplotlib.pyplot as plt \n", "\n", "class Database:\n", " @staticmethod\n", " def get_mongodb():\n", " return 'mongodb://localhost:27017/', 'combined', 'combined_output'\n", "\n", " # Get input documents from MongoDB\n", " @staticmethod\n", " def get_input_documents(limit=1000):\n", " mongo_url, db_name, collection_name = Database.get_mongodb()\n", " client = MongoClient(mongo_url)\n", " db = client[db_name]\n", " collection = db[collection_name]\n", " cursor = collection.find().limit(limit)\n", " combined_text = [doc['text'] for doc in cursor]\n", " document_count = len(combined_text)\n", " return combined_text, document_count\n", " \n", "\n", " \n", " nltk.download('turkish_stop_words')\n", " data_without_stopwords = []\n", " for i in range(0, len(response)):\n", " doc = re.sub('[^a-zA-Z]', ' ', response[i])\n", " doc = doc.lower()\n", " doc = doc.split()\n", " doc = [lemmatizer.lemmatize(word) for word in doc if not word in set(stopwords)]\n", " doc = ' '.join(doc)\n", " data_without_stopwords.append(doc)\n", "\n", " #print ilk satır orjinal datasetteki\n", " print(data.response[0])\n", "\n", " # Calculate TF-IDF and get feature names\n", " @staticmethod\n", " def calculate_tfidf(documents, stop_words):\n", " vectorizer = TfidfVectorizer(stop_words=stop_words, max_features=10000,min_df=2)\n", " vectors = vectorizer.fit_transform(data_without_stopwords)\n", " tfidf_matrix = vectorizer.fit_transform(documents)\n", " feature_names = vectorizer.get_feature_names_out()\n", " return tfidf_matrix, feature_names\n", "\n", " # Extract keywords using TF-IDF\n", " def extract_keywords(tfidf_matrix, feature_names, top_n=10):\n", " keywords = {}\n", " for doc_idx, row in enumerate(tfidf_matrix):\n", " filtered_feature_names = [name for name in feature_names if name.lower() not in stop_words]\n", " scores = np.asarray(row.T.todense()).flatten()\n", " sorted_indices = np.argsort(scores)[::-1]\n", " top_features = sorted_indices[:top_n]\n", " doc_keywords = [(filtered_feature_names[idx], scores[idx]) for idx in top_features]\n", " keywords[f'document_{doc_idx+1}'] = doc_keywords\n", " return keywords\n", " \n", " #zip keywords and combined text \n", " \n", " # Identify low TF-IDF words\n", " @staticmethod\n", " def identify_low_tfidf_words(tfidf_matrix, feature_names, threshold=0.001):\n", " avg_scores = np.mean(tfidf_matrix, axis=0).A1\n", " low_tfidf_words = [feature_names[i] for i, score in enumerate(avg_scores) if score < threshold]\n", " return low_tfidf_words\n", " \n", " # Update stop words with low TF-IDF words\n", " @staticmethod\n", " def update_stop_words(existing_stop_words, low_tfidf_words):\n", " updated_stop_words = set(existing_stop_words) | set(low_tfidf_words)\n", " return list(updated_stop_words)\n", "\n", "\n", "#tf-ıdf ile döküman içerisinden kelime seçme \n", "#Term Frequency (TF): Bir kelimenin belli bir dökümanda tekrar etme değeri\n", "#Inverse Document Frequency (IDF):bir kelimenin tüm dökümanlar arasındaki yaygınlığı Nadir bulunan kelimeler, daha yüksek IDF değerine sahip olur.\n", "#tf-ıdf skoru ise bu ikisinin çarpımıdır.\n", "\n", " #buraya eşik değer belirlenmeli\n", "\n", "\n", "turkish_stop_words = [\n", " 'ah', 'ama', 'an', 'ancak', 'araba', 'aralar', 'aslında', \n", " 'b', 'başlayan', 'bağlı', 'bazı', 'belirli', 'ben', 'bence', \n", " 'birkaç', 'birlikte', 'bunu', 'burada', 'biten', 'biz', \n", " 'bu', 'buna', 'çünkü', 'da', 'de', 'demek', 'den', 'derken', \n", " 'değil', 'daha', 'dolayı', 'edilir', 'eğer', 'en', 'fakat', \n", " 'genellikle', 'gibi', 'hem', 'her', 'herhangi', 'hiç', 'ise', \n", " 'işte', 'itibaren', 'iyi', 'kadar', 'karşı', 'ki', 'kime', \n", " 'kısaca', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'niye', 'o', \n", " 'olasılıkla', 'olabilir', 'oluşur', 'önce', 'şu', 'sadece', \n", " 'se', 'şey', 'şimdi', 'tabi', 'tüm', 've', 'ya', 'ya da', \n", " 'yanı', 'yani', 'yılında', 'yetenekli', 'yine'\n", "]\n", "# Get input documents\n", "documents, document_count = Database.get_input_documents()\n", "\n", "# Calculate TF-IDF and get feature names\n", "tfidf_matrix, feature_names = Database.calculate_tfidf(documents, turkish_stop_words)\n", "\n", "# Extract keywords\n", "keywords = Database.extract_keywords(tfidf_matrix, feature_names, stop_words=turkish_stop_words)\n", "print(keywords)\n", "\n", "# Identify low TF-IDF words\n", "low_tfidf_words = Database.identify_low_tfidf_words(tfidf_matrix, feature_names)\n", "print(low_tfidf_words)\n", "\n", "# Update stop words\n", "updated_stop_words = Database.update_stop_words(turkish_stop_words, low_tfidf_words)\n", "print(updated_stop_words) " ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unhashable type: 'set'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[15], line 162\u001b[0m\n\u001b[0;32m 159\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m tfidf_matrix, feature_names,keywords\n\u001b[0;32m 161\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;18m__name__\u001b[39m\u001b[38;5;241m==\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m__main__\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n\u001b[1;32m--> 162\u001b[0m tfidf_matrix, feature_names,keywords\u001b[38;5;241m=\u001b[39m \u001b[43mmain\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 164\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mAnahtar Kelimler:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 165\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m doc, words \u001b[38;5;129;01min\u001b[39;00m keywords\u001b[38;5;241m.\u001b[39mitems():\n", "Cell \u001b[1;32mIn[15], line 148\u001b[0m, in \u001b[0;36mmain\u001b[1;34m()\u001b[0m\n\u001b[0;32m 146\u001b[0m initial_stop_words \u001b[38;5;241m=\u001b[39m turkish_stop_words\n\u001b[0;32m 147\u001b[0m \u001b[38;5;66;03m# Stop-words listesini iteratif olarak güncelleyin\u001b[39;00m\n\u001b[1;32m--> 148\u001b[0m final_stop_words \u001b[38;5;241m=\u001b[39m \u001b[43miterative_update\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments_list\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minitial_stop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 149\u001b[0m \u001b[38;5;66;03m#tf-ıdf hesaplama\u001b[39;00m\n\u001b[0;32m 150\u001b[0m tfidf_matrix, feature_names\u001b[38;5;241m=\u001b[39mcalculate_tfidf(documents_list,final_stop_words)\n", "Cell \u001b[1;32mIn[15], line 127\u001b[0m, in \u001b[0;36miterative_update\u001b[1;34m(documents, initial_stop_words, iterations)\u001b[0m\n\u001b[0;32m 126\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21miterative_update\u001b[39m(documents, initial_stop_words, iterations\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m5\u001b[39m):\n\u001b[1;32m--> 127\u001b[0m stop_words \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mset\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43minitial_stop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 128\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m _ \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(iterations):\n\u001b[0;32m 129\u001b[0m tfidf_matrix, feature_names \u001b[38;5;241m=\u001b[39m calculate_tfidf(documents, stop_words)\n", "\u001b[1;31mTypeError\u001b[0m: unhashable type: 'set'" ] } ], "source": [ "\n", "\n", "\"\"\"class Tf:\n", " @staticmethod\n", " def tf(word, blob):\n", " return blob.words.count(word) / len(blob.words)\n", "\n", " @staticmethod\n", " def n_containing(word, bloblist):\n", " return sum(1 for blob in bloblist if word in blob.words)\n", "\n", " @staticmethod\n", " def idf(word, bloblist):\n", " return math.log(len(bloblist) / (1 + Tf.n_containing(word, bloblist)))\n", "\n", " @staticmethod\n", " def tfidf(word, blob, bloblist):\n", " return Tf.tf(word, blob) * Tf.idf(word, bloblist)\n", "\n", " @staticmethod\n", " def get_input_documents(limit=1000):\n", " return Database.get_input_documents(limit)\"\"\"\n", "\n", "\n", "\n", "\n", "\n", " \"\"\"\n", " Her döküman için anahtar kelimeleri seç.\n", " :param tfidf_matrix: TF-IDF matris\n", " :param feature_names: TF-IDF özellik isimleri\n", " :param top_n: Her döküman için seçilecek anahtar kelime sayısı\n", " :return: Anahtar kelimeler ve skorlari\n", " \"\"\"\n", " \n", "\n", "#--------------------------------------------------------------- burada aldığımız dökümanları listeliyoruz\n", "# Dokümanları işleyerek TF-IDF hesaplama\n", "#bloblist dökümanların bir listesi\n", "\"\"\"bloblist = []\n", "for i, blob in enumerate(bloblist):\n", " print(\"Top words in document {}\".format(i + 1))\n", " scores = {word: Tf.tfidf(word, blob, bloblist) for word in blob.words} #dökümanların içerisinde bulunan kelimeleri alır.\n", " sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)\n", " for word, score in sorted_words[:3]:\n", " print(\"\\tWord: {}, TF-IDF: {}\".format(word, round(score, 5)))\"\"\"\n", "\n", "\n", "# Dökümanları isimlendir\n", "#named_documents = {f'döküman {i+1}': doc for i, doc in enumerate(combined_text)}\n", "\n", "#features olarak top_keywordsleri belirleyerek metnin bu kelimelerin etrafında olması sağlanmalı \n", "def calculate_tfidf(documents, stop_words):\n", " vectorizer = TfidfVectorizer(stop_words=stop_words, max_features=10000)\n", " tfidf_matrix = vectorizer.fit_transform(documents)\n", " feature_names = vectorizer.get_feature_names_out()\n", " return tfidf_matrix, feature_names\n", "\n", "#---------------------------------------------------------------------------------\n", "#kelimelerin ortalama skorlarını hesaplama \n", "def identify_low_tfidf_words(tfidf_matrix, feature_names, threshold=0.001):\n", " # TF-IDF skorlarını toplayarak her kelimenin ortalama skorunu hesaplayın\n", " avg_scores = np.mean(tfidf_matrix, axis=0).A1\n", " low_tfidf_words = [feature_names[i] for i, score in enumerate(avg_scores) if score < threshold]\n", " return low_tfidf_words\n", "\n", "#kelimelerin yeni geliştirilen eşik değere göre güncellenmesi \n", "def update_stop_words(existing_stop_words, low_tfidf_words):\n", " updated_stop_words = set(existing_stop_words) | set(low_tfidf_words)\n", " return list(updated_stop_words)\n", "\n", "\n", "#bu kısım detaylandırılmalı \n", "def iterative_update(documents, initial_stop_words, iterations=5):\n", " stop_words = set(initial_stop_words)\n", " for _ in range(iterations):\n", " tfidf_matrix, feature_names = calculate_tfidf(documents, stop_words)\n", " low_tfidf_words = identify_low_tfidf_words(tfidf_matrix, feature_names)\n", " stop_words = update_stop_words(stop_words, low_tfidf_words)\n", " return list(stop_words)\n", "\n", "\n", "\n", "def main ():\n", "\n", " \n", "#anlam ilişkisini de kontrol edecek bir yapı oluşpturulacak title ile benzerlik kontrol ederek yüksek benzerlik içeren kelimler sıralnacak .\n", "\n", "# Dökümanları liste olarak al\n", " named_documents, _ = Tf.get_input_documents(limit=1000)\n", " documents_list = [doc.get('text', '') if isinstance(doc, dict) else doc for doc in list(named_documents.values())]\n", "\n", " #başlangıç stop değerleriyle yeni olanları arasında değişim yapma \n", " initial_stop_words = turkish_stop_words\n", " # Stop-words listesini iteratif olarak güncelleyin\n", " final_stop_words = iterative_update(documents_list, initial_stop_words)\n", " #tf-ıdf hesaplama\n", " tfidf_matrix, feature_names=calculate_tfidf(documents_list,final_stop_words)\n", " keywords=extract_keywords(tfidf_matrix,feature_names,top_n=10)\n", "\n", " \n", "\n", " print(\"Güncellenmiş Stop-Words Listesi:\", final_stop_words)\n", " print(\"TF-IDF Matrix Shape:\", tfidf_matrix.shape)\n", " print(\"Feature Names Sample:\", feature_names[:10]) # İlk 10 feature adını gösterir\n", "\n", " return tfidf_matrix, feature_names,keywords\n", "\n", "if __name__==\"__main__\":\n", " tfidf_matrix, feature_names,keywords= main()\n", "\n", " print(\"Anahtar Kelimler:\")\n", " for doc, words in keywords.items():\n", " print(f\"{doc}: {words}\")\n", " \n", "\n", "#---------------------------------------------------------\n", " \"\"\"blobs = [tb(doc) for doc in documents_list] # veya 'title' kullanarak başlıkları işleyebilirsiniz\n", " all_words = set(word for blob in blobs for word in blob.words)\n", "\n", " tfidf_scores = {}\n", " for word in all_words:\n", " tfidf_scores[word] = [Tf.tfidf(word, blob, blobs) for blob in blobs]\n", "\n", " print(\"TF-IDF Skorları:\")\n", " for word, scores in tfidf_scores.items():\n", " print(f\"Kelime: {word}, Skorlar: {scores}\")\"\"\"\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "ename": "InvalidParameterError", "evalue": "The 'stop_words' parameter of TfidfVectorizer must be a str among {'english'}, an instance of 'list' or None. Got {'o', 'den', 'an', 'şey', 'burada', 've', 'ah', 'ise', 'hiç', 'yine', 'biz', 'bu', 'da', 'genellikle', 'yılında', 'belirli', 'se', 'ne', 'kadar', 'neden', 'hem', 'aralar', 'yani', 'daha', 'araba', 'derken', 'dolayı', 'kısaca', 'karşı', 'niye', 'ki', 'bunu', 'buna', 'de', 'herhangi', 'önce', 'tabi', 'kime', 'biten', 'ben', 'ya', 'ya da', 'çünkü', 'mu', 'b', 'demek', 'fakat', 'şimdi', 'birlikte', 'her', 'bağlı', 'nasıl', 'şu', 'sadece', 'tüm', 'aslında', 'edilir', 'ama', 'bence', 'en', 'işte', 'gibi', 'ancak', 'birkaç', 'itibaren', 'mü', 'olabilir', 'bazı', 'oluşur', 'başlayan', 'yanı', 'olasılıkla', 'iyi', 'değil', 'eğer', 'yetenekli'} instead.", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mInvalidParameterError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[2], line 155\u001b[0m\n\u001b[0;32m 152\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m tfidf_matrix, feature_names,documents_list \n\u001b[0;32m 154\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;18m__name__\u001b[39m\u001b[38;5;241m==\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m__main__\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n\u001b[1;32m--> 155\u001b[0m tfidf_matrix, feature_names,documents_list\u001b[38;5;241m=\u001b[39m \u001b[43mmain\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 158\u001b[0m \u001b[38;5;66;03m# Sonuçları yazdır\u001b[39;00m\n\u001b[0;32m 159\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mİsimlendirilmiş Dökümanlar:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n", "Cell \u001b[1;32mIn[2], line 142\u001b[0m, in \u001b[0;36mmain\u001b[1;34m()\u001b[0m\n\u001b[0;32m 140\u001b[0m initial_stop_words \u001b[38;5;241m=\u001b[39m turkish_stop_words\n\u001b[0;32m 141\u001b[0m \u001b[38;5;66;03m# Stop-words listesini iteratif olarak güncelleyin\u001b[39;00m\n\u001b[1;32m--> 142\u001b[0m final_stop_words \u001b[38;5;241m=\u001b[39m \u001b[43miterative_update\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments_list\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minitial_stop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 143\u001b[0m \u001b[38;5;66;03m#tf-ıdf hesaplama\u001b[39;00m\n\u001b[0;32m 144\u001b[0m tfidf_matrix, feature_names\u001b[38;5;241m=\u001b[39mcalculate_tfidf(documents_list,final_stop_words)\n", "Cell \u001b[1;32mIn[2], line 124\u001b[0m, in \u001b[0;36miterative_update\u001b[1;34m(documents, initial_stop_words, iterations)\u001b[0m\n\u001b[0;32m 122\u001b[0m stop_words \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mset\u001b[39m(initial_stop_words)\n\u001b[0;32m 123\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m _ \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(iterations):\n\u001b[1;32m--> 124\u001b[0m tfidf_matrix, feature_names \u001b[38;5;241m=\u001b[39m \u001b[43mcalculate_tfidf\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstop_words\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 125\u001b[0m low_tfidf_words \u001b[38;5;241m=\u001b[39m identify_low_tfidf_words(tfidf_matrix, feature_names)\n\u001b[0;32m 126\u001b[0m stop_words \u001b[38;5;241m=\u001b[39m update_stop_words(stop_words, low_tfidf_words)\n", "Cell \u001b[1;32mIn[2], line 103\u001b[0m, in \u001b[0;36mcalculate_tfidf\u001b[1;34m(documents, stop_words)\u001b[0m\n\u001b[0;32m 101\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcalculate_tfidf\u001b[39m(documents, stop_words):\n\u001b[0;32m 102\u001b[0m vectorizer \u001b[38;5;241m=\u001b[39m TfidfVectorizer(stop_words\u001b[38;5;241m=\u001b[39mstop_words, max_features\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m10000\u001b[39m)\n\u001b[1;32m--> 103\u001b[0m tfidf_matrix \u001b[38;5;241m=\u001b[39m \u001b[43mvectorizer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 104\u001b[0m feature_names \u001b[38;5;241m=\u001b[39m vectorizer\u001b[38;5;241m.\u001b[39mget_feature_names_out()\n\u001b[0;32m 105\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m tfidf_matrix, feature_names\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\feature_extraction\\text.py:2091\u001b[0m, in \u001b[0;36mTfidfVectorizer.fit_transform\u001b[1;34m(self, raw_documents, y)\u001b[0m\n\u001b[0;32m 2084\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_check_params()\n\u001b[0;32m 2085\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf \u001b[38;5;241m=\u001b[39m TfidfTransformer(\n\u001b[0;32m 2086\u001b[0m norm\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mnorm,\n\u001b[0;32m 2087\u001b[0m use_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39muse_idf,\n\u001b[0;32m 2088\u001b[0m smooth_idf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msmooth_idf,\n\u001b[0;32m 2089\u001b[0m sublinear_tf\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msublinear_tf,\n\u001b[0;32m 2090\u001b[0m )\n\u001b[1;32m-> 2091\u001b[0m X \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfit_transform\u001b[49m\u001b[43m(\u001b[49m\u001b[43mraw_documents\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 2092\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_tfidf\u001b[38;5;241m.\u001b[39mfit(X)\n\u001b[0;32m 2093\u001b[0m \u001b[38;5;66;03m# X is already a transformed view of raw_documents so\u001b[39;00m\n\u001b[0;32m 2094\u001b[0m \u001b[38;5;66;03m# we set copy to False\u001b[39;00m\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\base.py:1466\u001b[0m, in \u001b[0;36m_fit_context..decorator..wrapper\u001b[1;34m(estimator, *args, **kwargs)\u001b[0m\n\u001b[0;32m 1461\u001b[0m partial_fit_and_fitted \u001b[38;5;241m=\u001b[39m (\n\u001b[0;32m 1462\u001b[0m fit_method\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__name__\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mpartial_fit\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01mand\u001b[39;00m _is_fitted(estimator)\n\u001b[0;32m 1463\u001b[0m )\n\u001b[0;32m 1465\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m global_skip_validation \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m partial_fit_and_fitted:\n\u001b[1;32m-> 1466\u001b[0m \u001b[43mestimator\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_validate_params\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 1468\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m config_context(\n\u001b[0;32m 1469\u001b[0m skip_parameter_validation\u001b[38;5;241m=\u001b[39m(\n\u001b[0;32m 1470\u001b[0m prefer_skip_nested_validation \u001b[38;5;129;01mor\u001b[39;00m global_skip_validation\n\u001b[0;32m 1471\u001b[0m )\n\u001b[0;32m 1472\u001b[0m ):\n\u001b[0;32m 1473\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m fit_method(estimator, \u001b[38;5;241m*\u001b[39margs, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\base.py:666\u001b[0m, in \u001b[0;36mBaseEstimator._validate_params\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m 658\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_validate_params\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[0;32m 659\u001b[0m \u001b[38;5;250m \u001b[39m\u001b[38;5;124;03m\"\"\"Validate types and values of constructor parameters\u001b[39;00m\n\u001b[0;32m 660\u001b[0m \n\u001b[0;32m 661\u001b[0m \u001b[38;5;124;03m The expected type and values must be defined in the `_parameter_constraints`\u001b[39;00m\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 664\u001b[0m \u001b[38;5;124;03m accepted constraints.\u001b[39;00m\n\u001b[0;32m 665\u001b[0m \u001b[38;5;124;03m \"\"\"\u001b[39;00m\n\u001b[1;32m--> 666\u001b[0m \u001b[43mvalidate_parameter_constraints\u001b[49m\u001b[43m(\u001b[49m\n\u001b[0;32m 667\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_parameter_constraints\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 668\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mget_params\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdeep\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 669\u001b[0m \u001b[43m \u001b[49m\u001b[43mcaller_name\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[38;5;18;43m__class__\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[38;5;18;43m__name__\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[0;32m 670\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n", "File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sklearn\\utils\\_param_validation.py:95\u001b[0m, in \u001b[0;36mvalidate_parameter_constraints\u001b[1;34m(parameter_constraints, params, caller_name)\u001b[0m\n\u001b[0;32m 89\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m 90\u001b[0m constraints_str \u001b[38;5;241m=\u001b[39m (\n\u001b[0;32m 91\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m, \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;241m.\u001b[39mjoin([\u001b[38;5;28mstr\u001b[39m(c)\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mfor\u001b[39;00m\u001b[38;5;250m \u001b[39mc\u001b[38;5;250m \u001b[39m\u001b[38;5;129;01min\u001b[39;00m\u001b[38;5;250m \u001b[39mconstraints[:\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m]])\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m or\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 92\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mconstraints[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 93\u001b[0m )\n\u001b[1;32m---> 95\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m InvalidParameterError(\n\u001b[0;32m 96\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mThe \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mparam_name\u001b[38;5;132;01m!r}\u001b[39;00m\u001b[38;5;124m parameter of \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcaller_name\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m must be\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 97\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mconstraints_str\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m. Got \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mparam_val\u001b[38;5;132;01m!r}\u001b[39;00m\u001b[38;5;124m instead.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m 98\u001b[0m )\n", "\u001b[1;31mInvalidParameterError\u001b[0m: The 'stop_words' parameter of TfidfVectorizer must be a str among {'english'}, an instance of 'list' or None. Got {'o', 'den', 'an', 'şey', 'burada', 've', 'ah', 'ise', 'hiç', 'yine', 'biz', 'bu', 'da', 'genellikle', 'yılında', 'belirli', 'se', 'ne', 'kadar', 'neden', 'hem', 'aralar', 'yani', 'daha', 'araba', 'derken', 'dolayı', 'kısaca', 'karşı', 'niye', 'ki', 'bunu', 'buna', 'de', 'herhangi', 'önce', 'tabi', 'kime', 'biten', 'ben', 'ya', 'ya da', 'çünkü', 'mu', 'b', 'demek', 'fakat', 'şimdi', 'birlikte', 'her', 'bağlı', 'nasıl', 'şu', 'sadece', 'tüm', 'aslında', 'edilir', 'ama', 'bence', 'en', 'işte', 'gibi', 'ancak', 'birkaç', 'itibaren', 'mü', 'olabilir', 'bazı', 'oluşur', 'başlayan', 'yanı', 'olasılıkla', 'iyi', 'değil', 'eğer', 'yetenekli'} instead." ] } ], "source": [ "from pymongo import MongoClient\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "from textblob import TextBlob as tb\n", "import numpy as np\n", "import math\n", "import nltk \n", "import matplotlib.pyplot as plt \n", "\n", "class Database:\n", " @staticmethod\n", " def get_mongodb():\n", " return 'mongodb://localhost:27017/', 'EgitimDatabase', 'train'\n", "\n", "#--------------------------------------------------------------------------\n", "#combined_text eklenmeli \n", " @staticmethod\n", " def get_input_documents(limit=3):\n", " mongo_url, db_name, collection_name = Database.get_mongodb()\n", " client = MongoClient(mongo_url)\n", " db = client[db_name]\n", " collection = db[collection_name]\n", " cursor = collection.find().limit(limit)\n", " combined_text = [doc for doc in cursor]\n", " document_count = len(combined_text)\n", " \n", " # Dökümanları isimlendir\n", " named_documents = {f'döküman {i+1}': doc for i, doc in enumerate(combined_text)}\n", " \n", " return named_documents, document_count\n", "\n", "\n", "class Tf:\n", " @staticmethod\n", " def tf(word, blob):\n", " return blob.words.count(word) / len(blob.words)\n", "\n", " @staticmethod\n", " def n_containing(word, bloblist):\n", " return sum(1 for blob in bloblist if word in blob.words)\n", "\n", " @staticmethod\n", " def idf(word, bloblist):\n", " return math.log(len(bloblist) / (1 + Tf.n_containing(word, bloblist)))\n", "\n", " @staticmethod\n", " def tfidf(word, blob, bloblist):\n", " return Tf.tf(word, blob) * Tf.idf(word, bloblist)\n", "\n", " @staticmethod\n", " def get_input_documents(limit=3):\n", " return Database.get_input_documents(limit)\n", "\n", "# Kullanım örneği\n", "named_documents, document_count = Tf.get_input_documents(limit=1000)\n", "\n", "#tf-ıdf ile döküman içerisinden kelime seçme \n", "\n", "def extract_keywords(tfidf_matrix, feature_names, top_n=10):\n", " \"\"\"\n", " Her döküman için anahtar kelimeleri seç.\n", " :param tfidf_matrix: TF-IDF matris\n", " :param feature_names: TF-IDF özellik isimleri\n", " :param top_n: Her döküman için seçilecek anahtar kelime sayısı\n", " :return: Anahtar kelimeler ve skorlari\n", " \"\"\"\n", " keywords = {}\n", " for doc_idx, row in enumerate(tfidf_matrix):\n", " # TF-IDF değerlerini ve özellik isimlerini al\n", " scores = np.asarray(row.T.todense()).flatten()\n", " sorted_indices = np.argsort(scores)[::-1] # Skorları azalan sırada\n", " top_features = sorted_indices[:top_n]\n", " \n", " doc_keywords = [(feature_names[idx], scores[idx]) for idx in top_features]\n", " keywords[f'document_{doc_idx+1}'] = doc_keywords\n", " \n", " return keywords\n", "\n", "# Dokümanları işleyerek TF-IDF hesaplama\n", "#bloblist dökümanların bir listesi\n", "bloblist = []\n", "for i, blob in enumerate(bloblist):\n", " print(\"Top words in document {}\".format(i + 1))\n", " scores = {word: Tf.tfidf(word, blob, bloblist) for word in blob.words} #dökümanların içerisinde bulunan kelimeleri alır.\n", " sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)\n", " for word, score in sorted_words[:3]:\n", " print(\"\\tWord: {}, TF-IDF: {}\".format(word, round(score, 5)))\n", "\n", "\n", "#buraya eşik değer belirlenmeli\n", "turkish_stop_words = [\n", " 'ah', 'ama', 'an', 'ancak', 'araba', 'aralar', 'aslında', \n", " 'b', 'başlayan', 'bağlı', 'bazı', 'belirli', 'ben', 'bence', \n", " 'birkaç', 'birlikte', 'bunu', 'burada', 'biten', 'biz', \n", " 'bu', 'buna', 'çünkü', 'da', 'de', 'demek', 'den', 'derken', \n", " 'değil', 'daha', 'dolayı', 'edilir', 'eğer', 'en', 'fakat', \n", " 'genellikle', 'gibi', 'hem', 'her', 'herhangi', 'hiç', 'ise', \n", " 'işte', 'itibaren', 'iyi', 'kadar', 'karşı', 'ki', 'kime', \n", " 'kısaca', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'niye', 'o', \n", " 'olasılıkla', 'olabilir', 'oluşur', 'önce', 'şu', 'sadece', \n", " 'se', 'şey', 'şimdi', 'tabi', 'tüm', 've', 'ya', 'ya da', \n", " 'yanı', 'yani', 'yılında', 'yetenekli', 'yine'\n", "]\n", "\n", "#features olarak top_keywordsleri belirleyerek metnin bu kelimelerin etrafında olması sağlanmalı \n", "def calculate_tfidf(combined_text, stop_words):\n", " vectorizer = TfidfVectorizer(stop_words=stop_words, max_features=10000)\n", " tfidf_matrix = vectorizer.fit_transform(combined_text)\n", " feature_names = vectorizer.get_feature_names_out()\n", " return tfidf_matrix, feature_names\n", "\n", "#---------------------------------------------------------------------------------\n", "#kelimelerin ortalama skorlarını hesaplama \n", "def identify_low_tfidf_words(tfidf_matrix, feature_names, threshold=0.001):\n", " # TF-IDF skorlarını toplayarak her kelimenin ortalama skorunu hesaplayın\n", " avg_scores = np.mean(tfidf_matrix, axis=0).A1\n", " low_tfidf_words = [feature_names[i] for i, score in enumerate(avg_scores) if score < threshold]\n", " return low_tfidf_words\n", "\n", "#kelimelerin yeni geliştirilen eşik değere göre güncellenmesi \n", "def update_stop_words(existing_stop_words, low_tfidf_words):\n", " updated_stop_words = set(existing_stop_words) | set(low_tfidf_words)\n", " return list(updated_stop_words)\n", "\n", "\n", "#bu kısım detaylandırılmalı \n", "def iterative_update(combined_text, initial_stop_words, iterations=5):\n", " stop_words = set(initial_stop_words)\n", " for _ in range(iterations):\n", " tfidf_matrix, feature_names = calculate_tfidf(combined_text, stop_words)\n", " low_tfidf_words = identify_low_tfidf_words(tfidf_matrix, feature_names)\n", " stop_words = update_stop_words(stop_words, low_tfidf_words)\n", " return list(stop_words)\n", "\n", "\n", "\n", "def main ():\n", "\n", " \n", "#anlam ilişkisini de kontrol edecek bir yapı oluşpturulacak title ile benzerlik kontrol ederek yüksek benzerlik içeren kelimler sıralnacak .\n", "\n", "# Dökümanları liste olarak al\n", " documents_list = [doc.get('text', '') if isinstance(doc, dict) else doc for doc in list(named_documents.values())]\n", "\n", " #başlangıç stop değerleriyle yeni olanları arasında değişim yapma \n", " initial_stop_words = turkish_stop_words\n", " # Stop-words listesini iteratif olarak güncelleyin\n", " final_stop_words = iterative_update(documents_list, initial_stop_words)\n", " #tf-ıdf hesaplama\n", " tfidf_matrix, feature_names=calculate_tfidf(documents_list,final_stop_words)\n", "\n", " \n", "\n", " print(\"Güncellenmiş Stop-Words Listesi:\", final_stop_words)\n", " print(\"TF-IDF Matrix Shape:\", tfidf_matrix.shape)\n", " print(\"Feature Names Sample:\", feature_names[:10]) # İlk 10 feature adını gösterir\n", "\n", " return tfidf_matrix, feature_names,documents_list \n", "\n", "if __name__==\"__main__\":\n", " tfidf_matrix, feature_names,documents_list= main()\n", "\n", "\n", "# Sonuçları yazdır\n", "print(\"İsimlendirilmiş Dökümanlar:\")\n", "for name, doc in named_documents.items():\n", " print(f\"{name}: {doc}\")\n", "\n", " print(\"\\nDökümanlar Listesi:\")\n", " print(documents_list)\n", "\n", "#---------------------------------------------------------\n", " blobs = [tb(doc) for doc in documents_list] # veya 'title' kullanarak başlıkları işleyebilirsiniz\n", " all_words = set(word for blob in blobs for word in blob.words)\n", "\n", " tfidf_scores = {}\n", " for word in all_words:\n", " tfidf_scores[word] = [Tf.tfidf(word, blob, blobs) for blob in blobs]\n", "\n", " print(\"TF-IDF Skorları:\")\n", " for word, scores in tfidf_scores.items():\n", " print(f\"Kelime: {word}, Skorlar: {scores}\")\n", "\n", "\n", "\n", "\n", "\n", "#----------------------------------------------\n", "\n", "\n", "\n", "\n", "\n", "#alternatif keywordleri belirleme \n", "#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n", "\"\"\"turkish_stop_words = set([\n", " 'ad', 'adım', 'ah', 'ama', 'an', 'ancak', 'araba', 'aralar', 'aslında', \n", " 'b', 'bazı', 'belirli', 'ben', 'bence', 'bunu', 'burada', 'biz', 'bu', 'buna', 'çünkü', \n", " 'da', 'de', 'demek', 'den', 'derken', 'değil', 'daha', 'dolayı', 'edilir', 'eğer', 'en', 'fakat', \n", " 'genellikle', 'gibi', 'hem', 'her', 'herhangi', 'hiç', 'ise', 'işte', 'itibaren', 'iyi', 'kadar', \n", " 'karşı', 'ki', 'kime', 'kısaca', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'niye', 'o', 'olabilir', 'oluşur', \n", " 'önce', 'şu', 'sadece', 'se', 'şey', 'şimdi', 'tabi', 'tüm', 've', 'ya', 'ya da', 'yani', 'yine'\n", "])\n", "def calculate_tfidf(documents):\n", " vectorizer = TfidfVectorizer(stop_words=turkish_stop_words, max_features=10000) # max_features ile özellik sayısını sınırlıyoruz\n", " tfidf_matrix = vectorizer.fit_transform(documents)\n", " feature_names = vectorizer.get_feature_names_out()\n", " return tfidf_matrix, feature_names\n", "\n", "#feature_names lerin belirlenmesi grekir \n", "tfidf_matrix, feature_names=calculate_tfidf(documents)\n", "\n", "\n", "\n", "# En yüksek TF-IDF skorlarına sahip anahtar kelimeleri çıkarın\n", "#sıkışık format kullanmarak tf-ıdf matrisini işleme \n", "def get_top_n_keywords_sparse(n=10):\n", "\n", " # TF-IDF hesaplayıcı oluşturun\n", " vectorizer = TfidfVectorizer()\n", "\n", " # Başlıklar ve metinler ile TF-IDF matrisini oluşturun\n", " texts = Database.get_input_texts()\n", " titles = Database.get_input_titles()\n", " \n", "\n", " #title ve text değerlerini alarak vektörleştirdik.\n", " tfidf_matrix = vectorizer.fit_transform(documents)\n", "\n", " # Özellik adlarını (kelimeleri) alın\n", "\n", " feature_names = vectorizer.get_feature_names_out()\n", "\n", " # TF-IDF sonuçlarını DataFrame'e dönüştürün\n", " df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)\n", " print(df)\n", " keywords = {}\n", " for i in range(tfidf_matrix.shape[0]):\n", " row = tfidf_matrix[i].toarray().flatten() #list yapısından çıkarma \n", " sorted_indices = row.argsort()[::-1] # Büyükten küçüğe sıralama\n", " top_indices = sorted_indices[:n]\n", " top_keywords = [feature_names[idx] for idx in top_indices]\n", " keywords[i] = top_keywords\n", " return keywords\"\"\"\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'TfidfVectorizer' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[1], line 41\u001b[0m\n\u001b[0;32m 31\u001b[0m turkish_stop_words \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mset\u001b[39m([\n\u001b[0;32m 32\u001b[0m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124ma\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mabide\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mabi\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mabla\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mad\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124madım\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mah\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mama\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124man\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mancak\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maraba\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maralar\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maslında\u001b[39m\u001b[38;5;124m'\u001b[39m, \n\u001b[0;32m 33\u001b[0m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maşşağı\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124maz\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mb\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbazı\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbelirli\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mben\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbence\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbunu\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mburada\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbiz\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbu\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mbuna\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mçünkü\u001b[39m\u001b[38;5;124m'\u001b[39m, \n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 37\u001b[0m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mönce\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mşu\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124msadece\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124msana\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mse\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mşey\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mşimdi\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mtabi\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mtüm\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mve\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mya\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mya da\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124myani\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124myine\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[0;32m 38\u001b[0m ])\n\u001b[0;32m 40\u001b[0m \u001b[38;5;66;03m# TF-IDF hesaplayıcı oluşturun ve Türkçe durak kelimelerini dahil edin\u001b[39;00m\n\u001b[1;32m---> 41\u001b[0m vectorizer \u001b[38;5;241m=\u001b[39m \u001b[43mTfidfVectorizer\u001b[49m(stop_words\u001b[38;5;241m=\u001b[39mturkish_stop_words)\n\u001b[0;32m 44\u001b[0m \u001b[38;5;124;03m\"\"\"IDF, derlemedeki belge sayısının,\u001b[39;00m\n\u001b[0;32m 45\u001b[0m \u001b[38;5;124;03mincelenen anahtar kelimeyi içeren topluluktaki belge sayısına \u001b[39;00m\n\u001b[0;32m 46\u001b[0m \u001b[38;5;124;03mbölünmesiyle elde edilen algoritmadır. \u001b[39;00m\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 49\u001b[0m \u001b[38;5;124;03mkülliyat yani incelenen tüm belgelerin adedi 10 ise ve test edilen anahtar kelime,\u001b[39;00m\n\u001b[0;32m 50\u001b[0m \u001b[38;5;124;03mkülliyattaki üç belgede görünüyorsa, bu durumda IDF değeri 0.52’dir (log (10/3)).\"\"\"\u001b[39;00m\n\u001b[0;32m 51\u001b[0m \u001b[38;5;66;03m#TF-IDF puanı; Naive Bayes ve Destek Vektör Makineleri gibi algoritmalara aktarılabilir. Böylece kelime sayısı gibi daha temel yöntemlerin sonuçları büyük ölçüde iyileştirilebilir.\u001b[39;00m\n\u001b[0;32m 52\u001b[0m \u001b[38;5;66;03m#IDF = log ( Dokuman Sayısı / Terimin Geçtiği Dokuman Sayısı )\u001b[39;00m\n\u001b[0;32m 53\u001b[0m \u001b[38;5;66;03m#dokuman sayısılarını almakla başlayacağız.\u001b[39;00m\n\u001b[0;32m 54\u001b[0m \u001b[38;5;66;03m# : titlelerın sayısı / terimler ise \u001b[39;00m\n", "\u001b[1;31mNameError\u001b[0m: name 'TfidfVectorizer' is not defined" ] } ], "source": [ "\n", "#---------------------------------------------------------------------------------------------------------------------------------\n", "#transformers kütüphanesine ait generation fonksiyonu özellikleri ,PyTorch generate() is implemented in GenerationMixin. \n", "\n", "\n", "\"\"\"from transformers import GenerationConfig\n", "\n", "# Download configuration from huggingface.co and cache.\n", "generation_config = GenerationConfig.from_pretrained(\"openai-community/gpt2\")\n", "\n", "# E.g. config was saved using *save_pretrained('./test/saved_model/')*\n", "generation_config.save_pretrained(\"./test/saved_model/\")\n", "generation_config = GenerationConfig.from_pretrained(\"./test/saved_model/\")\n", "\n", "# You can also specify configuration names to your generation configuration file\n", "generation_config.save_pretrained(\"./test/saved_model/\", config_file_name=\"my_configuration.json\")\n", "generation_config = GenerationConfig.from_pretrained(\"./test/saved_model/\", \"my_configuration.json\")\n", "\n", "# If you'd like to try a minor variation to an existing configuration, you can also pass generation\n", "# arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored\n", "generation_config, unused_kwargs = GenerationConfig.from_pretrained(\n", " \"openai-community/gpt2\", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True\n", ")\n", "generation_config.top_k\n", "\n", "unused_kwargs\n", "\"\"\"\n", "\n", "\n", "#tf-ıdf hesaplama (anahtar kelimeler için) #Bir kelimenin TF IDF puanı ne kadar yüksekse, kelime bulunduğu belgeyle o kadar alakalıdır.\n", "\n", "turkish_stop_words = set([\n", " 'a', 'abide', 'abi', 'abla', 'ad', 'adım', 'ah', 'ama', 'an', 'ancak', 'araba', 'aralar', 'aslında', \n", " 'aşşağı', 'az', 'b', 'bazı', 'belirli', 'ben', 'bence', 'bunu', 'burada', 'biz', 'bu', 'buna', 'çünkü', \n", " 'da', 'de', 'demek', 'den', 'derken', 'değil', 'daha', 'dolayı', 'e', 'edilir', 'eğer', 'en', 'fakat', \n", " 'genellikle', 'gibi', 'hem', 'her', 'herhangi', 'hiç', 'i', 'ise', 'işte', 'itibaren', 'iyi', 'kadar', \n", " 'karşı', 'ki', 'kime', 'kısaca', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'niye', 'o', 'olabilir', 'oluşur', \n", " 'önce', 'şu', 'sadece', 'sana', 'se', 'şey', 'şimdi', 'tabi', 'tüm', 've', 'ya', 'ya da', 'yani', 'yine'\n", "])\n", "\n", "# TF-IDF hesaplayıcı oluşturun ve Türkçe durak kelimelerini dahil edin\n", "vectorizer = TfidfVectorizer(stop_words=turkish_stop_words)\n", "\n", "\n", "\"\"\"IDF, derlemedeki belge sayısının,\n", "incelenen anahtar kelimeyi içeren topluluktaki belge sayısına \n", "bölünmesiyle elde edilen algoritmadır. \n", "Yani ters belge sıklığı bir terimin önemini ölçer,\n", "toplam belge sayısının, terimi içeren belge sayısına bölünmesiyle elde edilir.\n", "külliyat yani incelenen tüm belgelerin adedi 10 ise ve test edilen anahtar kelime,\n", "külliyattaki üç belgede görünüyorsa, bu durumda IDF değeri 0.52’dir (log (10/3)).\"\"\"\n", "#TF-IDF puanı; Naive Bayes ve Destek Vektör Makineleri gibi algoritmalara aktarılabilir. Böylece kelime sayısı gibi daha temel yöntemlerin sonuçları büyük ölçüde iyileştirilebilir.\n", "#IDF = log ( Dokuman Sayısı / Terimin Geçtiği Dokuman Sayısı )\n", "#dokuman sayısılarını almakla başlayacağız.\n", "# : titlelerın sayısı / terimler ise \n", "\n", "document_number=416434\n", "\"\"\"Sonuç olarak TF IDF’nin, SEO’da pratik ve önemli bir kullanım alanına sahip olduğunu söylenebilir,\n", " özellikle yüksek kaliteli içeriğin optimize edilmesinde ve oluşturulmasında yararlıdır. \n", " Ancak TF IDF, içerik optimizasyonu için tek başına kullanıldığında ciddi sınırlamalarla karşı karşıya kalır:\"\"\"\n", "\n", "# TF-IDF hesaplayıcı oluşturun\n", "vectorizer = TfidfVectorizer()\n", "\n", "# Başlıklar ve metinler ile TF-IDF matrisini oluşturun\n", "texts = Database.get_input_texts()\n", "titles,title_count = Database.get_input_titles()\n", "documents = titles + texts # Başlıklar ve metinleri birleştir\n", "\n", "#title ve text değerlerini alarak vektörleştirdik.\n", "tfidf_matrix = vectorizer.fit_transform(documents)\n", "\n", "# Özellik adlarını (kelimeleri) alın\n", "\n", "feature_names = vectorizer.get_feature_names_out()\n", "\n", "# TF-IDF sonuçlarını DataFrame'e dönüştürün\n", "df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)\n", "\n", "\n", "\"\"\"def get_top_n_keywords(df, n=10):\n", " keywords = {}\n", " for i, row in df.iterrows():\n", " sorted_row = row.sort_values(ascending=False)\n", " top_keywords = sorted_row.head(n).index\n", " keywords[i] = top_keywords.tolist()\n", " return keywords\"\"\"\n", "\n", "# En yüksek TF-IDF skorlarına sahip anahtar kelimeleri çıkarın\n", "#sıkışık format kullanmarak tf-ıdf matrisini işleme \n", "def get_top_n_keywords_sparse(n=10):\n", "\n", " # TF-IDF hesaplayıcı oluşturun\n", " vectorizer = TfidfVectorizer()\n", "\n", " # Başlıklar ve metinler ile TF-IDF matrisini oluşturun\n", " texts = Database.get_input_texts()\n", " titles = Database.get_input_titles()\n", " \n", "\n", " #title ve text değerlerini alarak vektörleştirdik.\n", " tfidf_matrix = vectorizer.fit_transform(documents)\n", "\n", " # Özellik adlarını (kelimeleri) alın\n", "\n", " feature_names = vectorizer.get_feature_names_out()\n", "\n", " # TF-IDF sonuçlarını DataFrame'e dönüştürün\n", " df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)\n", " print(df)\n", " keywords = {}\n", " for i in range(tfidf_matrix.shape[0]):\n", " row = tfidf_matrix[i].toarray().flatten() #list yapısından çıkarma \n", " sorted_indices = row.argsort()[::-1] # Büyükten küçüğe sıralama\n", " top_indices = sorted_indices[:n]\n", " top_keywords = [feature_names[idx] for idx in top_indices]\n", " keywords[i] = top_keywords\n", " return keywords\n", "\n", "\n", "top_keywords = get_top_n_keywords_sparse(tfidf_matrix, feature_names)\n", "print(top_keywords)\n", "print(f\"Başlıklar: {titles}\")\n", "print(f\"Başlık sayısı: {title_count}\")\n", "print(f\"Metinler: {texts}\")\n", "print(f\"Metin sayısı: {len(texts)}\")\n", "print(f\"Birleştirilmiş Belgeler: {documents[:5]}\") # İlk birkaç belgeyi kontrol etme\n", "\n", "def calculate_tfidf(docs):\n", " vectorizer = TfidfVectorizer(stop_words=turkish_stop_words)\n", " tfidf_matrix = vectorizer.fit_transform(docs)\n", " feature_names = vectorizer.get_feature_names_out()\n", " return tfidf_matrix, feature_names\n", "\n", "# İşlem için dökümanları parçalayarak kullanın\n", "def process_documents_in_batches(docs, batch_size=1000, top_n=5):\n", " all_keywords = {}\n", " for start in range(0, len(docs), batch_size):\n", " end = min(start + batch_size, len(docs))\n", " batch_docs = docs[start:end]\n", " tfidf_matrix, feature_names = calculate_tfidf(batch_docs)\n", " batch_keywords = get_top_n_keywords_sparse(tfidf_matrix, feature_names, n=top_n)\n", " all_keywords.update(batch_keywords)\n", " return all_keywords\n", "\n", "#buraya mango db üzerindeki tüm dökümanlar gelmewli \n", "keywords= process_documents_in_batches(documents,batch_size=1000,top_n=5)\n", "\n", "documents = titles + texts # Başlıklar ve metinleri birleştir\n", "print(f\"en yüksek tf-ıdf skoruna sahip anahtar kelimeler:{keywords}\")\n", "\n", "\n", "# Belgeleri TF-IDF matrisine dönüştürün\n", "\"\"\"tfidf_matrix = vectorizer.fit_transform(documents)\n", "\n", "# Özellik adlarını (kelimeleri) alın\n", "feature_names = vectorizer.get_feature_names_out()\n", "\n", "# TF-IDF sonuçlarını DataFrame'e dönüştürün\n", "df = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)\n", "\n", "print(df)\"\"\"\n", "\n", "#text ve title a göre keywords belirlenmesi\n", "\n", "#------------------------------------------------------------------------------\n", "\n", "\n", "#sbert ile alt başlıkların oluşturulması\n", "\n", "#kümelenme ile alt başlıkların belirlenmesi \n", "\n", "#-------------------------------------------------------------------------------\n", "\n", "#anahatar kelime ve alt başlıkların veri tabnaına eklnemesi " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#benzerlik hesaplaması için kullanılacak \n", "from sentence_transformers import SentenceTransformer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarity Sentences " ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#prompt oluştururak generate etmek için hazırlık" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bert Modeliyle tokenizer atama" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tokenizer= BertTokenizer.from_pretrained('bert-base-uncased')\n", "model=BertForMaskedLM.from_pretrained('bert-base-uncased')\n", "\n", "\"\"\"BERT MODELİNİ AYARLAMA\n", "\n", "input_file: Modelin işlem yapacağı giriş dosyasının yolunu belirtir. Bu dosya, metin verilerini içermelidir.\n", "-----------------------------------------------------------------------------------------------------------------\n", "output_file: Modelin çıktılarının kaydedileceği dosyanın yolunu belirtir.\n", "------------------------------------------------------------------------------------------------------------------\n", "layers: Hangi BERT katmanlarının kullanılacağını belirler. Örneğin, \"-1,-2,-3,-4\" son dört katmanı ifade eder.\n", "----------------------------------------------------------------------------------------------------------------------\n", "bert_config_file: Önceden eğitilmiş BERT modelinin yapılandırma dosyasının yolu. Bu dosya modelin mimarisini belirler.\n", "--------------------------------------------------------------------------------------------------------------------------\n", "max_seq_length: Giriş sekanslarının maksimum uzunluğu. Sekanslar bu uzunluktan uzunsa kesilir, kısa ise sıfır ile doldurulur.\n", "--------------------------------------------------------------------------------------------------------------------------------\n", "init_checkpoint: Başlangıç ağırlıkları. Genellikle önceden eğitilmiş bir BERT modelinin ağırlıkları buradan yüklenir.\n", "----------------------------------------------------------------------------------------------------------------------------\n", "vocab_file: BERT modelinin eğitildiği kelime dağarcığının (vocabulary) dosya yolu. Modelin kelime parçacıklarını tanıması için gereklidir.\n", "--------------------------------------------------------------------------------------------------------------------------------------------------\n", "do_lower_case: Giriş metinlerinin küçük harfe mi dönüştürüleceğini belirler. Küçük harfli model için True, büyük harfli model için False olmalıdır.\n", "-----------------------------------------------------------------------------------------------------------------------------------------------------------\n", "batch_size: Tahminler sırasında kullanılacak veri kümesi boyutu.\n", "--------------------------------------------------------------------------------------------------------------------------------------\n", "use_tpu: TPU (Tensor Processing Unit) kullanılıp kullanılmayacağını belirler. True ise TPU, False ise GPU/CPU kullanılır.\n", "--------------------------------------------------------------------------------------------------------------------------------\n", "master: TPU kullanılıyorsa, TPU'nun ana makinesinin adresi.\n", "---------------------------------------------------------------------------------------------------------------------------------------\n", "num_tpu_cores: TPU kullanılacaksa, toplam TPU çekirdek sayısını belirtir.\n", "-----------------------------------------------------------------------------------------------------------------------------------------\n", "use_one_hot_embeddings: TPUs'da genellikle True olarak ayarlanır çünkü bu, tf.one_hot fonksiyonunu kullanarak embedding lookup işlemlerini hızlandırır. GPU/CPU kullanılıyorsa False tercih edilir.\"\"\"\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "t5 Modeli" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from transformers import pipeline\n", "from dotenv import load_dotenv\n", "import os \n", "# Load model directly\n", "from transformers import AutoTokenizer, AutoModelForSeq2SeqLM\n", "\n", "\n", "#tokenizer ve modelin yüklenmesi\n", "tokenizer = AutoTokenizer.from_pretrained(\"google/flan-t5-small\")\n", "model = AutoModelForSeq2SeqLM.from_pretrained(\"google/flan-t5-small\")\n", "prompt = \"Write an article about Machine Learning in Healthcare focusing on Introduction to ML and Applications in Healthcare.\"\n", "#api anahtarını çevresel değişken al\n", "api_key= os.getenv('HUGGINGFACE_API_KEY')\n", "#env dosyasını yükleme\n", "load_dotenv()\n", "\n", "#---------------------------------------------------------------------------------\n", "if api_key is None:\n", " raise ValueError(\"Apı anahtarı .env dosyasında bulunamadı\")\n", "\n", "# Başlıkları oluştur\n", "headers = {\"Authorization\": f\"Bearer {api_key}\"}\n", "\n", "inputs=tokenizer(prompt, return_tensors=\"pt\")\n", "input_sequence = \"[CLS] Machine Learning in Healthcare [SEP] Introduction to ML [SEP] Applications in Healthcare [SEP] machine learning, healthcare, AI [SEP]\"\n", "#deneme data parçası\n", "data = {\n", " \"title\": \"Machine Learning in Healthcare\",\n", " \"sub_headings\": [\"Introduction to ML\", \"Applications in Healthcare\"],\n", " \"keywords\": [\"machine learning\", \"healthcare\", \"AI\"]\n", "}\n", "\n", "# Girdiyi oluşturma\n", "prompt = (\n", " f\"Title: {data['title']}\\n\"\n", " f\"Sub-headings: {', '.join(data['sub_headings'])}\\n\"\n", " f\"Keywords: {', '.join(data['keywords'])}\\n\"\n", " f\"Content: {input_sequence}\\n\"\n", " \"Please generate a detailed article based on the above information.\"\n", ")\n", "\n", "#metin üretimi \n", "output_sequences = model.generate(\n", " inputs['input_ids'],\n", " max_length=300, # Üretilecek metnin maksimum uzunluğu\n", " min_length=150, # Üretilecek metnin minimum uzunluğu\n", " num_return_sequences=1, # Döndürülecek metin sayısı\n", " do_sample=True, # Örneklemeye izin ver\n", " top_k=50, # Top-k sampling kullan\n", " top_p=0.95, # Top-p sampling kullan\n", " repetition_penalty=1.2, # Anlamsız tekrarları önlemek için ceza\n", " eos_token_id=tokenizer.eos_token_id # Tam cümlelerin oluşturulmasını sağla\n", ")\n", "\n", "\n", "# Üretilen metni token'lardan çözüp string'e çevir\n", "generated_text = tokenizer.decode(output_sequences[0], skip_special_tokens=True)\n", "\n", "print(generated_text)\n" ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 2 }