Spaces:
Build error
Build error
File size: 23,755 Bytes
7d245b9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Kütüphaneler eklenmesi"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"c:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
}
],
"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": 3,
"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": 4,
"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": 5,
"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": 6,
"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": 7,
"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": 7,
"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\\\\bert\\\\datasets\\\\train_Egitim\\\\merged_train.parquet'\n",
"test_file_path = 'C:\\\\gitProjects\\\\bert\\\\datasets\\\\test_Egitim\\\\merged_test.parquet'\n",
"\n",
"train_collection, test_collection = dataset_read(train_file_path, test_file_path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similarity Sentences "
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'torch.amp'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[8], line 3\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m#datasete similarity sentence yardımıyla keywords ve subheadings tanımlama \u001b[39;00m\n\u001b[0;32m 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01msklearn\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mfeature_extraction\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mtext\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m TfidfVectorizer\n\u001b[1;32m----> 3\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01msentence_transformers\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m SentenceTransformer\n\u001b[0;32m 6\u001b[0m model \u001b[38;5;241m=\u001b[39m SentenceTransformer(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124memrecan/bert-base-turkish-cased-mean-nli-stsb-tr\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 7\u001b[0m \u001b[38;5;66;03m#text dosyasını koleksiyon üzerinden çekme \u001b[39;00m\n\u001b[0;32m 8\u001b[0m \u001b[38;5;66;03m# Database sınıfı: Veritabanı bağlantıları ve verileri çekme işlevleri\u001b[39;00m\n",
"File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sentence_transformers\\__init__.py:7\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mimportlib\u001b[39;00m\n\u001b[0;32m 5\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mos\u001b[39;00m\n\u001b[1;32m----> 7\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01msentence_transformers\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mcross_encoder\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mCrossEncoder\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m CrossEncoder\n\u001b[0;32m 8\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01msentence_transformers\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mdatasets\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m ParallelSentencesDataset, SentencesDataset\n\u001b[0;32m 9\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01msentence_transformers\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mLoggingHandler\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m LoggingHandler\n",
"File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sentence_transformers\\cross_encoder\\__init__.py:1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mCrossEncoder\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m CrossEncoder\n\u001b[0;32m 3\u001b[0m __all__ \u001b[38;5;241m=\u001b[39m [\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCrossEncoder\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n",
"File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\sentence_transformers\\cross_encoder\\CrossEncoder.py:7\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mtyping\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Callable, Dict, List, Literal, Optional, Tuple, Type, Union\n\u001b[0;32m 6\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mnumpy\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m \u001b[38;5;21;01mnp\u001b[39;00m\n\u001b[1;32m----> 7\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mtorch\u001b[39;00m\n\u001b[0;32m 8\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mtorch\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Tensor, nn\n\u001b[0;32m 9\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mtorch\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01moptim\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Optimizer\n",
"File \u001b[1;32mc:\\gitProjects\\yeni\\.venv\\lib\\site-packages\\torch\\__init__.py:1686\u001b[0m\n\u001b[0;32m 1683\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mRuntimeError\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mUnable to find torch_shm_manager at \u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;241m+\u001b[39m path)\n\u001b[0;32m 1684\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m path\u001b[38;5;241m.\u001b[39mencode(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mutf-8\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[1;32m-> 1686\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mtorch\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mamp\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m autocast, GradScaler\n\u001b[0;32m 1688\u001b[0m \u001b[38;5;66;03m# Initializing the extension shadows the built-in python float / int classes;\u001b[39;00m\n\u001b[0;32m 1689\u001b[0m \u001b[38;5;66;03m# store them for later use by SymInt / SymFloat.\u001b[39;00m\n\u001b[0;32m 1690\u001b[0m py_float \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mfloat\u001b[39m\n",
"\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'torch.amp'"
]
}
],
"source": [
"#datasete similarity sentence yardımıyla keywords ve subheadings tanımlama \n",
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"from sentence_transformers import SentenceTransformer\n",
"\n",
"\n",
"model = SentenceTransformer(\"emrecan/bert-base-turkish-cased-mean-nli-stsb-tr\")\n",
"#text dosyasını koleksiyon üzerinden çekme \n",
"# Database sınıfı: Veritabanı bağlantıları ve verileri çekme işlevleri\n",
"class Database:\n",
" @staticmethod\n",
" def get_mongodb():\n",
" # MongoDB bağlantı bilgilerini döndürecek şekilde tanımlanmıştır.\n",
" return 'mongodb://localhost:27017/', 'EgitimDatabase', 'train'\n",
"\n",
" @staticmethod\n",
" def get_input_titles():\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",
" query = {\"title\": {\"$exists\": True}}\n",
" cursor = collection.find(query, {\"title\": 1, \"_id\": 0})\n",
" title_from_db = [doc['title'] for doc in cursor]\n",
" return title_from_db\n",
" \n",
" @staticmethod\n",
" def get_input_texts():\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",
" query = {\"text\": {\"$exists\": True}}\n",
" cursor = collection.find(query, {\"text\": 1, \"_id\": 0})\n",
" text_from_db = [doc['text'] for doc in cursor]\n",
" return text_from_db\n",
"\n",
"\n",
"#tf-ıdf hesaplama (anahtar kelimeler için)\n",
"\n",
"\n",
"#IDF = log ( Dokuman Sayısı / Terimin Geçtiği Dokuman Sayısı )\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": "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
}
|