{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":17000,"databundleVersionId":895292,"sourceType":"competition"}],"dockerImageVersionId":30761,"isInternetEnabled":true,"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","execution":{"iopub.status.busy":"2024-09-25T06:40:56.479878Z","iopub.execute_input":"2024-09-25T06:40:56.480289Z","iopub.status.idle":"2024-09-25T06:40:56.944492Z","shell.execute_reply.started":"2024-09-25T06:40:56.480247Z","shell.execute_reply":"2024-09-25T06:40:56.943352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/cat-in-the-dat-ii/train.csv')","metadata":{"execution":{"iopub.status.busy":"2024-09-25T06:40:56.946925Z","iopub.execute_input":"2024-09-25T06:40:56.947628Z","iopub.status.idle":"2024-09-25T06:41:01.333888Z","shell.execute_reply.started":"2024-09-25T06:40:56.947570Z","shell.execute_reply":"2024-09-25T06:41:01.332630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\n# Load your data into a pandas DataFrame\ndf = pd.read_csv('/kaggle/input/cat-in-the-dat-ii/train.csv')\n\n# Replace 'target_column' with the actual column name\ntarget = df['target']\n\n# Set up the matplotlib figure\nplt.figure(figsize=(10, 6))\n\n# Plot histogram and density estimate using seaborn\nsns.histplot(target, kde=True, color='blue', stat=\"density\", bins=30)\n\n# Fit a normal distribution curve over the data\nmu, std = norm.fit(target)\nxmin, xmax = plt.xlim()\nx = np.linspace(xmin, xmax, 100)\np = norm.pdf(x, mu, std)\n\n# Plot the normal distribution curve\nplt.plot(x, p, 'k', linewidth=2)\nplt.title(f'Distribution of {target.name} with Normal Fit')\nplt.xlabel(f'{target.name}')\nplt.ylabel('Density')\n\n# Show the plot\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-09-25T06:41:01.335895Z","iopub.execute_input":"2024-09-25T06:41:01.336528Z","iopub.status.idle":"2024-09-25T06:41:08.370705Z","shell.execute_reply.started":"2024-09-25T06:41:01.336464Z","shell.execute_reply":"2024-09-25T06:41:08.369552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn import model_selection\n\nif __name__ == \"__main__\":\n\n   df = pd.read_csv('/kaggle/input/cat-in-the-dat-ii/train.csv')\n\n   df[\"kfold\"] = -1\n\n   df = df.sample(frac = 1).reset_index(drop = True)\n\n   y = df.target.values\n\n   kf = model_selection.StratifiedKFold(n_splits = 5)\n\n   for f,(t_, v_) in enumerate(kf.split (X=df, y=y)): \n    df.loc[v_, 'kfold'] = f\n    \n   df.to_csv('/kaggle/working/train_folds.csv', index=False)\n\n\n","metadata":{"execution":{"iopub.status.busy":"2024-09-25T06:41:08.373888Z","iopub.execute_input":"2024-09-25T06:41:08.374407Z","iopub.status.idle":"2024-09-25T06:41:23.082254Z","shell.execute_reply.started":"2024-09-25T06:41:08.374352Z","shell.execute_reply":"2024-09-25T06:41:23.080966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/working/train_folds.csv')\ndf.kfold.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-09-25T06:41:23.083733Z","iopub.execute_input":"2024-09-25T06:41:23.084123Z","iopub.status.idle":"2024-09-25T06:41:25.970512Z","shell.execute_reply.started":"2024-09-25T06:41:23.084082Z","shell.execute_reply":"2024-09-25T06:41:25.969399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn import linear_model\nfrom sklearn import metrics\nfrom sklearn import preprocessing","metadata":{"execution":{"iopub.status.busy":"2024-09-25T06:41:25.971872Z","iopub.execute_input":"2024-09-25T06:41:25.972205Z","iopub.status.idle":"2024-09-25T06:41:26.078103Z","shell.execute_reply.started":"2024-09-25T06:41:25.972167Z","shell.execute_reply":"2024-09-25T06:41:26.076675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd \nfrom sklearn import linear_model \nfrom sklearn import metrics \nfrom sklearn import preprocessing \n\ndef run(fold): \n    # load the full training data with folds \n    df = pd.read_csv('/kaggle/working/train_folds.csv') \n    \n    # all columns are features except id, target, and kfold columns \n    features = [f for f in df.columns if f not in (\"id\", \"target\", \"kfold\")] \n    \n    # fill all NaN values with 'NONE' and convert columns to strings \n    for col in features: \n        df[col] = df[col].astype(str).fillna(\"NONE\") \n    \n    # get training data using folds \n    df_train = df[df.kfold != fold].reset_index(drop=True) \n    # get validation data using folds \n    df_valid = df[df.kfold == fold].reset_index(drop=True) \n    \n    # initialize OneHotEncoder with handle_unknown to ignore unseen categories in validation \n    ohe = preprocessing.OneHotEncoder(handle_unknown='ignore') \n    \n    # fit ohe on combined training and validation features \n    full_data = pd.concat([df_train[features], df_valid[features]], axis=0) \n    ohe.fit(full_data[features]) \n    \n    # transform training and validation data \n    x_train = ohe.transform(df_train[features]) \n    x_valid = ohe.transform(df_valid[features]) \n    \n    # initialize Logistic Regression model \n    model = linear_model.LogisticRegression(solver='lbfgs', max_iter=500) \n    \n    # fit model on training data (ohe transformed) \n    model.fit(x_train, df_train.target.values) \n    \n    # predict on validation data \n    # we need the probability values as we are calculating AUC \n    valid_preds = model.predict_proba(x_valid)[:, 1] \n    \n    # calculate AUC score \n    auc = metrics.roc_auc_score(df_valid.target.values, valid_preds) \n    \n    # print AUC \n    print(f\"Fold {fold}, AUC = {auc}\")\n\n# run function for fold = 0 \nif __name__ == \"__main__\": \n    run(0)\n","metadata":{"execution":{"iopub.status.busy":"2024-09-25T06:41:26.079643Z","iopub.execute_input":"2024-09-25T06:41:26.080001Z","iopub.status.idle":"2024-09-25T06:42:21.731217Z","shell.execute_reply.started":"2024-09-25T06:41:26.079965Z","shell.execute_reply":"2024-09-25T06:42:21.730048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ohe_logres.py \n# initialize Logistic Regression model \ndef run(fold): \n    # load the full training data with folds \n    df = pd.read_csv('/kaggle/working/train_folds.csv') \n    \n    # all columns are features except id, target, and kfold columns \n    features = [f for f in df.columns if f not in (\"id\", \"target\", \"kfold\")] \n    \n    # fill all NaN values with 'NONE' and convert columns to strings \n    for col in features: \n        df[col] = df[col].astype(str).fillna(\"NONE\") \n    \n    # get training data using folds \n    df_train = df[df.kfold != fold].reset_index(drop=True) \n    # get validation data using folds \n    df_valid = df[df.kfold == fold].reset_index(drop=True) \n    \n    # initialize OneHotEncoder with handle_unknown to ignore unseen categories in validation \n    ohe = preprocessing.OneHotEncoder(handle_unknown='ignore') \n    \n    # fit ohe on combined training and validation features \n    full_data = pd.concat([df_train[features], df_valid[features]], axis=0) \n    ohe.fit(full_data[features]) \n    \n    # transform training and validation data \n    x_train = ohe.transform(df_train[features]) \n    x_valid = ohe.transform(df_valid[features]) \n \n    model = linear_model.LogisticRegression() \n    # fit model on training data (ohe) \n    model.fit(x_train, df_train.target.values) \n   # predict on validation data \n   # we need the probability values as we are calculating AUC \n   # we will use the probability of 1s \n    valid_preds = model.predict_proba(x_valid)[:, 1] \n   # get roc auc score \n    auc = metrics.roc_auc_score(df_valid.target.values, valid_preds) \n   # print auc \n    print(f\"Fold = {fold}, AUC = {auc}\") \n    \nif __name__ == \"__main__\": \n   for fold_ in range(5): \n       run(fold_) \n","metadata":{"execution":{"iopub.status.busy":"2024-09-25T06:42:21.732648Z","iopub.execute_input":"2024-09-25T06:42:21.733012Z","iopub.status.idle":"2024-09-25T06:44:16.558341Z","shell.execute_reply.started":"2024-09-25T06:42:21.732974Z","shell.execute_reply":"2024-09-25T06:44:16.557020Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd \nfrom sklearn import linear_model \nfrom sklearn import preprocessing \n\n# Function to train the model on one fold\ndef run(fold):\n    # Load the full training data with folds\n    df = pd.read_csv('/kaggle/working/train_folds.csv')\n    \n    # All columns are features except id, target, and kfold columns\n    features = [f for f in df.columns if f not in (\"id\", \"target\", \"kfold\")]\n    \n    # Fill all NaN values with 'NONE' and convert columns to strings\n    for col in features:\n        df[col] = df[col].astype(str).fillna(\"NONE\")\n    \n    # Get training and validation data using folds\n    df_train = df[df.kfold != fold].reset_index(drop=True)\n    df_valid = df[df.kfold == fold].reset_index(drop=True)\n    \n    # Initialize OneHotEncoder and fit on the combined training+validation features\n    ohe = preprocessing.OneHotEncoder(handle_unknown='ignore')\n    full_data = pd.concat([df_train[features], df_valid[features]], axis=0)\n    ohe.fit(full_data[features])\n    \n    # Transform the training and validation data\n    x_train = ohe.transform(df_train[features])\n    x_valid = ohe.transform(df_valid[features])\n    \n    # Initialize and train Logistic Regression model\n    model = linear_model.LogisticRegression(solver='lbfgs', max_iter=500)\n    model.fit(x_train, df_train.target.values)\n    \n    # Return the trained model, encoder, and features for later use\n    return model, ohe, features\n\n# Function to predict on test data\ndef predict_test(ohe, model, features):\n    # Load test data\n    df_test = pd.read_csv('/kaggle/input/cat-in-the-dat-ii/test.csv')\n    \n    # Fill NaNs and preprocess as done for training/validation data\n    for col in features:\n        df_test[col] = df_test[col].astype(str).fillna(\"NONE\")\n    \n    # Transform test data using the fitted encoder\n    x_test = ohe.transform(df_test[features])\n    \n    # Predict the class labels for test data\n    test_preds = model.predict(x_test)\n    \n    # Return test predictions\n    return test_preds\n\nif __name__ == \"__main__\":\n    # Train model on fold 0 (or any specific fold)\n    model, ohe, features = run(0)  # This trains the model and returns ohe, model, and features\n    \n    # Generate test predictions\n    test_preds = predict_test(ohe, model, features)\n    \n    # Load the sample submission file to get the 'id' column\n    submission_df = pd.read_csv('/kaggle/input/cat-in-the-dat-ii/sample_submission.csv')\n    \n    # Replace the 'target' column in the submission file with your predictions\n    submission_df['target'] = test_preds\n    \n    # Save to CSV file in the required format\n    submission_df.to_csv('submission.csv', index=False)\n    print(\"Submission file saved as submission.csv!\")\n","metadata":{"execution":{"iopub.status.busy":"2024-09-25T07:00:03.271034Z","iopub.execute_input":"2024-09-25T07:00:03.271560Z","iopub.status.idle":"2024-09-25T07:01:08.330582Z","shell.execute_reply.started":"2024-09-25T07:00:03.271514Z","shell.execute_reply":"2024-09-25T07:01:08.329278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}