{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceType":"competition","sourceId":131653,"databundleVersionId":15802687}],"dockerImageVersionId":31286,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:25:43.423675Z","iopub.execute_input":"2026-03-20T13:25:43.424449Z","iopub.status.idle":"2026-03-20T13:25:43.434032Z","shell.execute_reply.started":"2026-03-20T13:25:43.424404Z","shell.execute_reply":"2026-03-20T13:25:43.432452Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport pandas as pd\nimport numpy as np\n\n# Görselleştirme kütüphaneleri\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\nimport warnings\nwarnings.filterwarnings('ignore') \n\n\nfile_path = \"/kaggle/input/competitions/ai-emergency-medicine-turkiye/train.csv\" \ndf = pd.read_csv(file_path)\n\n\nprint(\"--- Veri Setinin İlk 5 Satırı ---\")\ndisplay(df.head())\n\n\nprint(f\"\\nVeri Seti Boyutu: {df.shape[0]} satır, {df.shape[1]} sütun\")\n\n\nprint(\"\\n--- Veri Seti Bilgileri ---\")\ndf.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:25:44.625639Z","iopub.execute_input":"2026-03-20T13:25:44.62598Z","iopub.status.idle":"2026-03-20T13:25:59.332504Z","shell.execute_reply.started":"2026-03-20T13:25:44.625959Z","shell.execute_reply":"2026-03-20T13:25:59.33127Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ADIM 2: Down Casting\nBu adım datayı daha optimize kullanmamızı sağlıyor. Mesela - ve + 120'li değerler arasında değer alan bir sütun int8 tipi ile tutulabilir. Ama gereksiz yere çok daha fazla değer tutmak için kullanılan int64 tipinde olabilir. Bu gereksiz tipleri düzelterek datayı optimize edebiliriz.","metadata":{}},{"cell_type":"code","source":"def reduce_mem_usage(df):\n    \"\"\"Veri setindeki sayısal sütunların tiplerini küçülterek bellek kullanımını optimize eder.\"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print(f'Başlangıç bellek kullanımı: {start_mem:.2f} MB')\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        \n        # Sadece sayısal (integer ve float) sütunları optimize et\n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        # Metin (object) sütunlarında eşsiz değer sayısı azsa, \"category\" tipine çevir\n        else:\n            if df[col].nunique() / len(df) < 0.5: # Eşsiz değer oranı %50'den azsa\n                df[col] = df[col].astype('category')\n\n    end_mem = df.memory_usage().sum() / 1024**2\n    print(f'Optimizasyon sonrası bellek kullanımı: {end_mem:.2f} MB')\n    print(f'Azalma oranı: {100 * (start_mem - end_mem) / start_mem:.1f}%')\n    \n    return df\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:25:59.334526Z","iopub.execute_input":"2026-03-20T13:25:59.334852Z","iopub.status.idle":"2026-03-20T13:25:59.345272Z","shell.execute_reply.started":"2026-03-20T13:25:59.334827Z","shell.execute_reply":"2026-03-20T13:25:59.344474Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"numeric_cols = df.select_dtypes(include=['int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64']).columns\ncategorical_cols = df.select_dtypes(include=['category', 'object']).columns\n\nprint(f\"Sayısal Sütun Sayısı: {len(numeric_cols)}\")\nprint(f\"Kategorik/Metin Sütun Sayısı: {len(categorical_cols)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:09.143831Z","iopub.execute_input":"2026-03-20T13:26:09.144136Z","iopub.status.idle":"2026-03-20T13:26:09.413372Z","shell.execute_reply.started":"2026-03-20T13:26:09.144115Z","shell.execute_reply":"2026-03-20T13:26:09.411954Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# Fonksiyonu çalıştırarak verimizi hafifletelim\ndf = reduce_mem_usage(df)\n\nprint(\"\\n--- Sütun Tiplerinin Dağılımı ---\")\n# 135 sütunu tiplerine göre gruplayalım\nnumeric_cols = df.select_dtypes(include=['int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64']).columns\ncategorical_cols = df.select_dtypes(include=['category', 'object']).columns\n\n\n\n# ID gibi eşsiz değer içeren sütunları tespit edelim (Bunlar genellikle analize katılmaz)\nprint(\"\\n--- Potansiyel ID veya Gereksiz Sütunlar ---\")\nfor col in categorical_cols:\n    if df[col].nunique() == df.shape[0]:\n        print(f\"- {col} (Her satırda benzersiz değer var, muhtemelen bir ID)\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:12.100562Z","iopub.execute_input":"2026-03-20T13:26:12.100884Z","iopub.status.idle":"2026-03-20T13:26:14.514697Z","shell.execute_reply.started":"2026-03-20T13:26:12.100859Z","shell.execute_reply":"2026-03-20T13:26:14.512968Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ADIM 3: Eksik Veri Tespiti\nÇok fazla Nan yani eksik olan değerlere sahip olan sütun modeli geliştimesi mümkün değil. Bu yüzdend  bu sütunların tespit edilerek silinmesi ya da doldurulması gerekmektedir.Çok fazla Nan yani eksik olan değerlere sahip olan sütun modeli geliştimesi mümkün değil. Bu yüzdend  bu sütunların tespit edilerek silinmesi ya da doldurulması gerekmektedir.","metadata":{}},{"cell_type":"code","source":"missing_percentages = (df.isnull().sum() / len(df)) * 100","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:14.693321Z","iopub.execute_input":"2026-03-20T13:26:14.693636Z","iopub.status.idle":"2026-03-20T13:26:14.880577Z","shell.execute_reply.started":"2026-03-20T13:26:14.693611Z","shell.execute_reply":"2026-03-20T13:26:14.879193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"missing_percentages","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:15.883431Z","iopub.execute_input":"2026-03-20T13:26:15.883791Z","iopub.status.idle":"2026-03-20T13:26:15.893058Z","shell.execute_reply.started":"2026-03-20T13:26:15.883768Z","shell.execute_reply":"2026-03-20T13:26:15.892093Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Yüzde  yüz dolu olanları bu df den at\nmissing_df = missing_percentages[missing_percentages > 0].sort_values(ascending=False).reset_index()\nmissing_df.columns = ['Sütun_Adı', 'Eksik_Veri_Oranı_%']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:16.603477Z","iopub.execute_input":"2026-03-20T13:26:16.603781Z","iopub.status.idle":"2026-03-20T13:26:16.615649Z","shell.execute_reply.started":"2026-03-20T13:26:16.603752Z","shell.execute_reply":"2026-03-20T13:26:16.614617Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"missing_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:18.791167Z","iopub.execute_input":"2026-03-20T13:26:18.791477Z","iopub.status.idle":"2026-03-20T13:26:18.802691Z","shell.execute_reply.started":"2026-03-20T13:26:18.79145Z","shell.execute_reply":"2026-03-20T13:26:18.800803Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if len(missing_df) > 0:\n    print(\"--- En Çok Eksik Veriye Sahip İlk 20 Sütun ---\")\n    display(missing_df.head(20))\n\n    # Grafiği Çizdirelim\n    plt.figure(figsize=(12, 10))\n    \n    # Çok fazla sütun varsa grafiğin okunabilirliği için sadece en kötü ilk 40 sütunu çizdirelim\n    sns.barplot(x='Eksik_Veri_Oranı_%', y='Sütun_Adı', data=missing_df.head(40), palette='Reds_r')\n    \n    plt.title('Kritik Eksik Veri Haritası (En Yüksek Orana Sahip Sütunlar)', fontsize=14, fontweight='bold')\n    plt.xlabel('Eksik Veri Oranı (%)', fontsize=12)\n    plt.ylabel('Sütun Adı', fontsize=12)\n    \n    # Karar vermemizi kolaylaştıracak eşik çizgilerini (Thresholds) çekelim\n    plt.axvline(x=20, color='green', linestyle='--', linewidth=2, label='%20 Sınırı (Kabul Edilebilir)')\n    plt.axvline(x=50, color='orange', linestyle='--', linewidth=2, label='%50 Sınırı (Kritik/İncele)')\n    plt.axvline(x=80, color='red', linestyle='--', linewidth=2, label='%80 Sınırı (Muhtemelen Çöp)')\n    \n    plt.legend(loc='lower right')\n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:19.102939Z","iopub.execute_input":"2026-03-20T13:26:19.103247Z","iopub.status.idle":"2026-03-20T13:26:19.514136Z","shell.execute_reply.started":"2026-03-20T13:26:19.103225Z","shell.execute_reply":"2026-03-20T13:26:19.512648Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"ADIM 4: Target Column Analizi\nBurada tahmin ettirmek istediğim target sütunu analizini yaparak tanıyoruz.\n","metadata":{}},{"cell_type":"code","source":"target_col = 'adverse_outcome'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:23.214509Z","iopub.execute_input":"2026-03-20T13:26:23.214833Z","iopub.status.idle":"2026-03-20T13:26:23.222272Z","shell.execute_reply.started":"2026-03-20T13:26:23.214807Z","shell.execute_reply":"2026-03-20T13:26:23.220435Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nprint(f\"--- '{target_col}' Hedef Değişken Analizi ---\")\n\n\ntarget_counts = df[target_col].value_counts(dropna=False)\ntarget_percentages = df[target_col].value_counts(normalize=True, dropna=False) * 100\n\n\nsummary_df = pd.DataFrame({\n'Kişi Sayısı': target_counts, \n'Yüzde Oranı (%)': target_percentages.round(2)\n})\ndisplay(summary_df)\n    \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:24.986773Z","iopub.execute_input":"2026-03-20T13:26:24.987075Z","iopub.status.idle":"2026-03-20T13:26:25.008633Z","shell.execute_reply.started":"2026-03-20T13:26:24.987055Z","shell.execute_reply":"2026-03-20T13:26:25.007283Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Görselleştirme (Pasta ve Çubuk Grafiği Yan Yana)\nfig, axes = plt.subplots(1, 2, figsize=(14, 6))\n\n# 1. Pasta Grafiği (Oranları Görmek İçin)\ncolors = ['#66b3ff', '#ff9999', '#99ff99'] # Renk paleti\naxes[0].pie(target_counts, labels=target_counts.index, autopct='%1.1f%%', \n            startangle=90, colors=colors, shadow=True, explode=[0.05]*len(target_counts))\naxes[0].set_title(f\"'{target_col}' Dağılımı (Pasta Grafiği)\", fontsize=14, fontweight='bold')\n\n# 2. Çubuk Grafiği (Net Sayıları Görmek İçin)\nsns.countplot(x=target_col, data=df, palette='pastel', ax=axes[1])\naxes[1].set_title(f\"'{target_col}' Vaka Sayıları\", fontsize=14, fontweight='bold')\naxes[1].set_ylabel(\"Kişi Sayısı\", fontsize=12)\naxes[1].set_xlabel(target_col, fontsize=12)\n\n# Çubukların üzerine sayıları yazdıralım\nfor p in axes[1].patches:\n    axes[1].annotate(f'{int(p.get_height())}', (p.get_x() + p.get_width() / 2., p.get_height()), \n                     ha='center', va='center', xytext=(0, 9), textcoords='offset points')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:25.643275Z","iopub.execute_input":"2026-03-20T13:26:25.643549Z","iopub.status.idle":"2026-03-20T13:26:26.868012Z","shell.execute_reply.started":"2026-03-20T13:26:25.64353Z","shell.execute_reply":"2026-03-20T13:26:26.867375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- ADIM 4.5: İKİ HEDEFİN İLİŞKİSİ ---\ntarget_main = 'adverse_outcome'\ntarget_sec = 'readmission_30d' # Kendi veri setindeki tam adıyla değiştirdiğinden emin ol\n\nprint(f\"--- '{target_main}' ve '{target_sec}' Arasındaki İlişki ---\")\n\n# İki hedefin çapraz tablosunu (Crosstab) oluşturalım\ncross_tab = pd.crosstab(df[target_main], df[target_sec], normalize='all') * 100\n\n# Çapraz tabloyu Isı Haritası (Heatmap) ile görselleştirelim\nplt.figure(figsize=(8, 6))\nsns.heatmap(cross_tab, annot=True, fmt=\".2f\", cmap=\"YlGnBu\", cbar=False,\n            annot_kws={\"size\": 14, \"weight\": \"bold\"})\nplt.title('İki Hedefin Kesişim Oranları (%)', fontsize=14, fontweight='bold')\nplt.xlabel(f'İkincil Hedef: {target_sec}', fontsize=12)\nplt.ylabel(f'Ana Hedef: {target_main}', fontsize=12)\nplt.show()\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:26:27.423305Z","iopub.execute_input":"2026-03-20T13:26:27.423599Z","iopub.status.idle":"2026-03-20T13:26:27.589891Z","shell.execute_reply.started":"2026-03-20T13:26:27.423575Z","shell.execute_reply":"2026-03-20T13:26:27.588458Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\nimport math\n\nprint(\"--- ADIM 5: SAF KATEGORİK DEĞİŞKENLERİN RÖNTGENİ ---\")\n\n# 1. Sütunları belirle\npure_categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()\ncols_to_exclude = ['adverse_outcome', 'readmission_30d', 'encounter_id']\ncat_cols_clean = [col for col in pure_categorical_cols if col in df.columns and col not in cols_to_exclude]\n\nprint(f\"Analiz edilecek Saf Kategorik Sütun Sayısı: {len(cat_cols_clean)}\\n\")\n\n# 2. Dinamik Subplot Ayarı (Sütun sayısına göre satır sayısını hesapla)\nn_cols = 2\nn_rows = math.ceil(len(cat_cols_clean) / n_cols)\n\nfig, axes = plt.subplots(n_rows, n_cols, figsize=(16, n_rows * 4))\naxes = axes.flatten()\n\nfor i, col in enumerate(cat_cols_clean):\n    # En çok tekrar eden 10 kategoriyi alalım\n    top_cats = df[col].value_counts().nlargest(10).index\n    plot_data = df[df[col].isin(top_cats)]\n    \n    # Grafiği çiz\n    sns.countplot(y=col, data=plot_data, ax=axes[i], palette='Set2', order=top_cats)\n    \n    # Görseli Güzelleştirme\n    axes[i].set_title(f\"'{col}' Sütunu Dağılımı (Top 10)\", fontweight='bold', fontsize=12)\n    axes[i].set_xlabel('Kayıt Sayısı')\n    axes[i].set_ylabel('')\n    \n    # Yüzdelik oranları yazdıralım\n    total = len(df[df[col].notnull()])\n    for p in axes[i].patches:\n        width = p.get_width()\n        percentage = f'{100 * width / total:.1f}%'\n        axes[i].annotate(percentage, \n                         (width + (total * 0.005), p.get_y() + p.get_height() / 2), \n                         va='center', fontsize=10)\n\n# Boş kalan eksenleri temizle (Eğer sütun sayısı tek ise son grafik boş kalmasın)\nfor j in range(i + 1, len(axes)):\n    fig.delaxes(axes[j])\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:27:50.885895Z","iopub.execute_input":"2026-03-20T13:27:50.886347Z","iopub.status.idle":"2026-03-20T13:28:11.893979Z","shell.execute_reply.started":"2026-03-20T13:27:50.886316Z","shell.execute_reply":"2026-03-20T13:28:11.892304Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ADIM 6: Preprocess","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\n# 1. Adım: Çöp Sütunları Ayıklama\n# %80'den fazla eksik verisi olanları ve ID sütununu listeden çıkarıyoruz\ncols_to_drop = missing_df[missing_df['Eksik_Veri_Oranı_%'] > 80]['Sütun_Adı'].tolist()\ncols_to_drop.append('encounter_id') # Analize girmemesi gereken benzersiz ID\n\ndf_clean = df.drop(columns=cols_to_drop)\nprint(f\"Silinen sütun sayısı: {len(cols_to_drop)}\")\nprint(f\"Kalan sütun sayısı: {df_clean.shape[1]}\")\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:29:26.505354Z","iopub.execute_input":"2026-03-20T13:29:26.505689Z","iopub.status.idle":"2026-03-20T13:29:26.721933Z","shell.execute_reply.started":"2026-03-20T13:29:26.505669Z","shell.execute_reply":"2026-03-20T13:29:26.72083Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 2. Adım: Hedef Değişkenleri Ayırma (X ve y)\n# İki hedefimiz olduğu için y1 ve y2 olarak ayırıyoruz\ntarget_main = 'adverse_outcome'\ntarget_sec = 'readmission_30d'\n\ny_main = df_clean[target_main]\ny_sec = df_clean[target_sec]\n\n# Özellikler (X) içinden hedefleri çıkarıyoruz\nX = df_clean.drop(columns=[target_main, target_sec])\n\n# 3. Adım: Kategorik Verileri Sayısallaştırma (Label Encoding)\n# Sadece 'object' ve 'category' tipindeki sütunları seçelim\ncat_cols = X.select_dtypes(include=['object', 'category']).columns\n\nle = LabelEncoder()\n\nfor col in cat_cols:\n    # Boş değerleri 'Unknown' olarak işaretleyip öyle encode edelim\n    X[col] = X[col].astype(str).fillna('Unknown')\n    X[col] = le.fit_transform(X[col])\n\nprint(\"\\n--- Preprocessing Tamamlandı ---\")\nprint(f\"X (Özellikler) Boyutu: {X.shape}\")\nprint(f\"y (Hedefler) Hazır.\")\ndisplay(X.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:29:27.439113Z","iopub.execute_input":"2026-03-20T13:29:27.439384Z","iopub.status.idle":"2026-03-20T13:29:32.363767Z","shell.execute_reply.started":"2026-03-20T13:29:27.439365Z","shell.execute_reply":"2026-03-20T13:29:32.361686Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\ncat_cols = X.select_dtypes(include=['object', 'category']).columns\n\nle = LabelEncoder()\n\nfor col in cat_cols:\n    # Boş değerleri 'Unknown' olarak işaretleyip öyle encode edelim\n    X[col] = X[col].astype(str).fillna('Unknown')\n    X[col] = le.fit_transform(X[col])\n\nprint(\"\\n--- Preprocessing Tamamlandı ---\")\nprint(f\"X (Özellikler) Boyutu: {X.shape}\")\nprint(f\"y (Hedefler) Hazır.\")\ndisplay(X.head())# Veriyi zaman bazlı bölmek için 'arrival_year' sütununu kullanıyoruz\n# 2024 verilerini 'Validation' (doğrulama), öncesini 'Train' (eğitim) yapalım\n\ntrain_idx = X[X['arrival_year'] < 2024].index\nval_idx = X[X['arrival_year'] == 2024].index\n\nX_train, X_val = X.loc[train_idx], X.loc[val_idx]\ny_main_train, y_main_val = y_main.loc[train_idx], y_main.loc[val_idx]\ny_sec_train, y_sec_val = y_sec.loc[train_idx], y_sec.loc[val_idx]\n\nprint(f\"Eğitim Seti (2019-2023): {X_train.shape[0]} satır\")\nprint(f\"Doğrulama Seti (2024): {X_val.shape[0]} satır\")\n\n# Kontrol: Hedef değişkenlerin dağılımı her iki sette de benzer mi?\nprint(\"\\n--- Hedef Değişken Dağılım Kontrolü (Main Target) ---\")\nprint(f\"Train Oranı: \\n{y_main_train.value_counts(normalize=True).round(3)}\")\nprint(f\"Val Oranı: \\n{y_main_val.value_counts(normalize=True).round(3)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:29:37.070861Z","iopub.execute_input":"2026-03-20T13:29:37.07113Z","iopub.status.idle":"2026-03-20T13:29:37.937669Z","shell.execute_reply.started":"2026-03-20T13:29:37.071112Z","shell.execute_reply":"2026-03-20T13:29:37.936155Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\ntrain_idx = X[X['arrival_year'] < 2024].index\nval_idx = X[X['arrival_year'] == 2024].index\n\nX_train, X_val = X.loc[train_idx], X.loc[val_idx]\ny_main_train, y_main_val = y_main.loc[train_idx], y_main.loc[val_idx]\ny_sec_train, y_sec_val = y_sec.loc[train_idx], y_sec.loc[val_idx]\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:29:40.168536Z","iopub.execute_input":"2026-03-20T13:29:40.168935Z","iopub.status.idle":"2026-03-20T13:29:41.229838Z","shell.execute_reply.started":"2026-03-20T13:29:40.168902Z","shell.execute_reply":"2026-03-20T13:29:41.228064Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Özellik Mühendisliği (Yeni Sütunlar Üretme)\ndef create_new_features(df):\n    # Yaş ve Triyaj Etkileşimi (Yaş grubu sayısallaştırılmış olmalı)\n    # Varsayalım age_group 0-5 arası, triage 0-4 arası değerler.\n    df['age_triage_risk'] = df['age_group'].astype(int) * (5 - df['triage_label'].astype(int))\n    \n    # Kritik Mesai (Gece + Hafta Sonu)\n    df['is_critical_shift'] = df['is_night_shift'] * df['is_weekend']\n    \n    # Varış saati gruplama (Örn: 18-24 arası yoğun saat)\n    df['is_rush_hour'] = df['arrival_hour'].apply(lambda x: 1 if 18 <= x <= 23 else 0)\n    \n    return df\n\nX_train_ext = create_new_features(X_train.copy())\nX_val_ext = create_new_features(X_val.copy())\n\n#Target Encoding (Yüksek Çeşitlilik İçin)\n# 'city' ve 'primary_diagnosis' gibi sütunları hedefin ortalamasına\nhigh_card_cols = ['city', 'primary_diagnosis', 'primary_icd10_code']\n\nfor col in high_card_cols:\n    # Train üzerinden oranları hesapla\n    target_mean = y_main_train.groupby(X_train_ext[col]).mean()\n    \n    # Bu oranları hem Train hem de Validation setine haritalandır\n    X_train_ext[col + '_te'] = X_train_ext[col].map(target_mean)\n    X_val_ext[col + '_te'] = X_val_ext[col].map(target_mean)\n    \n    # Eğer Validation'da yeni bir kategori gelirse (Train'de olmayan), \n    # genel ortalama ile doldur (Sızıntı olmaması için)\n    X_val_ext[col + '_te'] = X_val_ext[col + '_te'].fillna(y_main_train.mean())\n\nprint(\"Yeni özellikler ve Target Encoding başarıyla eklendi.\")\ndisplay(X_train_ext[['age_triage_risk', 'is_critical_shift', 'city_te']].head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:29:41.390862Z","iopub.execute_input":"2026-03-20T13:29:41.391214Z","iopub.status.idle":"2026-03-20T13:29:41.75443Z","shell.execute_reply.started":"2026-03-20T13:29:41.391187Z","shell.execute_reply":"2026-03-20T13:29:41.753325Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"Eğitim Seti (2019-2023): {X_train.shape[0]} satır\")\nprint(f\"Doğrulama Seti (2024): {X_val.shape[0]} satır\")\n\n\nprint(\"\\n--- Hedef Değişken Dağılım Kontrolü (Main Target) ---\")\nprint(f\"Train Oranı: \\n{y_main_train.value_counts(normalize=True).round(3)}\")\nprint(f\"Val Oranı: \\n{y_main_val.value_counts(normalize=True).round(3)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:29:44.595684Z","iopub.execute_input":"2026-03-20T13:29:44.596097Z","iopub.status.idle":"2026-03-20T13:29:44.611202Z","shell.execute_reply.started":"2026-03-20T13:29:44.596068Z","shell.execute_reply":"2026-03-20T13:29:44.610092Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ADINM 7: Model Eğitimi","metadata":{}},{"cell_type":"code","source":"import lightgbm as lgb\nfrom sklearn.metrics import classification_report, roc_auc_score, confusion_matrix\n\n\ndtrain = lgb.Dataset(X_train, label=y_main_train)\ndval = lgb.Dataset(X_val, label=y_main_val, reference=dtrain)\n\nparams = {\n    'objective': 'binary',        # İkili sınıflandırma\n    'metric': 'auc',             # Başarı metriği olarak AUC (Alan Altındaki Eğri)\n    'boosting_type': 'gbdt',\n    'learning_rate': 0.01,       # Adım büyüklüğü (Küçük olması daha garantidir)\n    'num_leaves': 62,            # Ağaç genişliği\n    'feature_fraction': 0.8,     # Her ağaçta sütunların %80'ini rastgele seç (Overfitting'i önler)\n    'bagging_fraction': 0.8,      # Verinin %80'ini rastgele seç\n    'bagging_freq': 5,\n    'verbose': -1,\n    'seed': 42\n}\n\n\nprint(\"--- Ana Hedef (adverse_outcome) Eğitimi Başlıyor ---\")\nmodel_main = lgb.train(\n    params,\n    dtrain,\n    num_boost_round=1000,\n    valid_sets=[dtrain, dval],\n    valid_names=['train', 'valid'],\n    callbacks=[\n        lgb.early_stopping(stopping_rounds=50),\n        lgb.log_evaluation(period=100)\n    ]\n)\n\n\nval_preds = model_main.predict(X_val)\n\nval_classes = [1 if x >= 0.5 else 0 for x in val_preds]\n\nprint(\"\\n--- Model Performans Özeti (Validation: 2024) ---\")\nprint(f\"ROC-AUC Skoru: {roc_auc_score(y_main_val, val_preds):.4f}\")\nprint(\"\\nSınıflandırma Raporu:\")\nprint(classification_report(y_main_val, val_classes))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:29:46.356073Z","iopub.execute_input":"2026-03-20T13:29:46.356404Z","iopub.status.idle":"2026-03-20T13:33:11.146146Z","shell.execute_reply.started":"2026-03-20T13:29:46.356379Z","shell.execute_reply":"2026-03-20T13:33:11.145331Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Modelin en çok önem verdiği ilk 20 özelliği görelim\nfeature_imp = pd.DataFrame(sorted(zip(model_main.feature_importance(), X.columns)), columns=['Değer','Özellik'])\n\nplt.figure(figsize=(12, 10))\nsns.barplot(x=\"Değer\", y=\"Özellik\", data=feature_imp.sort_values(by=\"Değer\", ascending=False).head(20), palette='magma')\nplt.title('Modeli En Çok Etkileyen İlk 20 Özellik (Feature Importance)', fontsize=14, fontweight='bold')\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:33:11.147529Z","iopub.execute_input":"2026-03-20T13:33:11.147786Z","iopub.status.idle":"2026-03-20T13:33:11.522361Z","shell.execute_reply.started":"2026-03-20T13:33:11.147766Z","shell.execute_reply":"2026-03-20T13:33:11.521028Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. İkinci Hedef İçin Veri Formatı\ndtrain_sec = lgb.Dataset(X_train_ext, label=y_sec_train)\ndval_sec = lgb.Dataset(X_val_ext, label=y_sec_val, reference=dtrain_sec)\n\nprint(\"--- İkinci Hedef (readmission_30d) Eğitimi Başlıyor ---\")\nmodel_sec = lgb.train(\n    params, # Önceki adımdaki parametreleri aynen kullanabiliriz\n    dtrain_sec,\n    num_boost_round=1000,\n    valid_sets=[dtrain_sec, dval_sec],\n    valid_names=['train', 'valid'],\n    callbacks=[\n        lgb.early_stopping(stopping_rounds=50),\n        lgb.log_evaluation(period=100)\n    ]\n)\n\n# Performans Kontrolü\nval_preds_sec = model_sec.predict(X_val_ext)\nprint(f\"\\nİkinci Hedef ROC-AUC: {roc_auc_score(y_sec_val, val_preds_sec):.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:33:20.028609Z","iopub.execute_input":"2026-03-20T13:33:20.028975Z","iopub.status.idle":"2026-03-20T13:33:59.182769Z","shell.execute_reply.started":"2026-03-20T13:33:20.028941Z","shell.execute_reply":"2026-03-20T13:33:59.181772Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\n# 1. Veri hizalama işlemi için pratik bir fonksiyon yazalım\ndef prepare_test_data(model, test_df):\n    expected_features = model.feature_name()\n    df_copy = test_df.copy()\n    \n    # Eksikleri 0 ile tamamla\n    missing_cols = set(expected_features) - set(df_copy.columns)\n    for c in missing_cols:\n        df_copy[c] = 0\n        \n    # Sadece modelin beklediği sütunları, beklediği sırayla geri dön\n    return df_copy[expected_features]\n\nprint(\"Modeller için test verileri hizalanıyor...\")\n\n# 2. Her iki model için test verisini kendi beklentilerine göre hizalayalım\ntest_final_main = prepare_test_data(model_main, test_final)\ntest_final_sec = prepare_test_data(model_sec, test_final)\n\nprint(f\"model_main için test verisi boyutu: {test_final_main.shape}\")\nprint(f\"model_sec için test verisi boyutu: {test_final_sec.shape}\")\n\n# 3. TAHMİNLER (İşte şimdi gerçekten hata vermesi imkansız!)\nprint(\"\\nTahminler üretiliyor...\")\npreds_main = model_main.predict(test_final_main)\npreds_sec = model_sec.predict(test_final_sec)\n\n# 4. SUBMISSION DOSYASI\nsubmission = pd.DataFrame({\n    'encounter_id': sub_id,\n    'adverse_outcome': preds_main,\n    'readmission_30d': preds_sec\n})\n\nsubmission.to_csv('submission.csv', index=False)\nprint(\"\\n--- BAŞARILI! ---\")\nprint(\"submission.csv dosyası hazır. Artık Submit edebilirsin.\")\ndisplay(submission.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-20T13:41:53.107088Z","iopub.execute_input":"2026-03-20T13:41:53.107366Z","iopub.status.idle":"2026-03-20T13:42:00.046934Z","shell.execute_reply.started":"2026-03-20T13:41:53.107346Z","shell.execute_reply":"2026-03-20T13:42:00.046249Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}