{"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":81933,"databundleVersionId":9643020,"sourceType":"competition"}],"dockerImageVersionId":30804,"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":"2024-12-07T10:22:30.197312Z","iopub.execute_input":"2024-12-07T10:22:30.197920Z","iopub.status.idle":"2024-12-07T10:22:30.884306Z","shell.execute_reply.started":"2024-12-07T10:22:30.197840Z","shell.execute_reply":"2024-12-07T10:22:30.882627Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split, RandomizedSearchCV\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport numpy as np\n\n# Function to encode string columns\ndef encode_string_columns(df):\n    for column in df.columns:\n        if df[column].dtype == object:\n            codes, _ = pd.factorize(df[column])\n            df[column] = codes\n    return df\n\n# Load train and test datasets\ndf = pd.read_csv(\"/kaggle/input/child-mind-institute-problematic-internet-use/train.csv\")\ndf_test = pd.read_csv(\"/kaggle/input/child-mind-institute-problematic-internet-use/test.csv\")\n\n# Store the 'id' for submission later\nid = df_test['id']\n\n# Drop irrelevant columns from the train and test datasets\ndf = df.drop(columns=['id', 'sii'])\ndf_test = df_test.drop(columns=['id'])\n\n# Encode string columns and fill missing values with 0\ndf = encode_string_columns(df)\ndf.fillna(0, inplace=True)\ndf_test = encode_string_columns(df_test)\ndf_test.fillna(0, inplace=True)\n\n# Ensure common columns between train and test sets\ncommon_columns = df.columns.intersection(df_test.columns)\nprint(\"Common columns:\", common_columns)\n\n# Split features and target\nX = df[common_columns]\ny = df.drop(columns=common_columns)\n\n# Split the dataset into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Standardize features\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_val = scaler.transform(X_val)\nX_test = scaler.transform(df_test)\n\n# Neural Network Model: Let's try increasing complexity\nmodel = MLPRegressor(hidden_layer_sizes=(100, 50, 25), max_iter=2000, solver='adam', random_state=42, activation='relu', alpha=0.0001, warm_start=True)\n\n# Hyperparameter tuning with RandomizedSearchCV\nparam_dist = {\n    'hidden_layer_sizes': [(100, 50), (100, 100), (200,)],\n    'alpha': np.logspace(-5, 0, 10),  # Logarithmic scale\n    'activation': ['relu', 'tanh'],\n    'max_iter': [1000, 2000],\n    'early_stopping': [True],\n    'validation_fraction': [0.1],\n    'n_iter_no_change': [10]\n}\n\n# RandomizedSearchCV to speed up hyperparameter tuning\nrandom_search = RandomizedSearchCV(estimator=model, param_distributions=param_dist, n_iter=5, cv=3, verbose=2, n_jobs=-1, scoring='neg_mean_squared_error', random_state=42)\nrandom_search.fit(X_train, y_train)\n\n# Get the best model from the random search\nbest_model = random_search.best_estimator_\n\n# Train the best model\nbest_model.fit(X_train, y_train)\n\n# Predict on validation set\ny_pred = best_model.predict(X_val)\n\n# Evaluate the model\nmse = mean_squared_error(y_val, y_pred)\nr2 = r2_score(y_val, y_pred)\nprint(f'Mean Squared Error: {mse:.2f}')\nprint(f'R2 Score: {r2:.2f}')\n\n# Predict on the test set\ny_test_predict = best_model.predict(X_test)\ny_test_predict_df = pd.DataFrame(y_test_predict, columns=y.columns)\n\n# Concatenate predictions with the test data\ndf_test_with_predictions = pd.concat([df_test.reset_index(drop=True), y_test_predict_df], axis=1)\ndf_test_with_predictions = df_test_with_predictions[df.columns]\n\n# Reload the CSV file into a DataFrame\ndf = pd.read_csv(\"/kaggle/input/child-mind-institute-problematic-internet-use/train.csv\")\ndf_test = df_test_with_predictions\ndf = pd.DataFrame(df)\ndf_test = pd.DataFrame(df_test)\n\nprint(df.shape)\n\n# Drop unnecessary columns\ndf = df.drop(columns=[\"id\", 'sii'])\n\n# Encode string columns in the DataFrame\nencoded_df = encode_string_columns(df)\nencoded_df_test = encode_string_columns(df_test)\n\n# Fill missing values with 0\nencoded_df.fillna(0, inplace=True)\nencoded_df_test.fillna(0, inplace=True)\n\n# Display the shapes of the encoded DataFrames\nprint(f\"Encoded train data shape: {encoded_df.shape}\")\nprint(f\"Encoded test data shape: {encoded_df_test.shape}\")\n\n# Function to choose the optimal number of PCA components based on variance threshold\ndef choose_optimal_components(explained_variance_ratio, threshold=0.90):\n    cumulative_variance = explained_variance_ratio.cumsum()  # Cumulative variance\n    optimal_components = (cumulative_variance >= threshold).argmax() + 1  # Optimal components\n    return optimal_components, cumulative_variance\n\n# Function to perform PCA\ndef perform_pca(data, test_data, threshold=0.90):\n    # Ensure columns in the test data match the training data\n    test_data = test_data[data.columns]  # Align test data columns with train data\n\n    # Standardize the features\n    scaler = StandardScaler()\n    X_train_scaled = scaler.fit_transform(data.iloc[:, :-1])  # Exclude target variable\n    X_test_scaled = scaler.transform(test_data.iloc[:, :-1])  # Ensure matching columns\n\n    # Fit PCA model\n    pca = PCA()\n    pca.fit(X_train_scaled)\n\n    # Calculate the optimal number of components based on the threshold of explained variance\n    cumulative_variance = pca.explained_variance_ratio_.cumsum()\n    optimal_components = (cumulative_variance >= threshold).argmax() + 1\n\n    # Apply PCA with optimal components\n    pca = PCA(n_components=optimal_components)\n    pca_train = pca.fit_transform(X_train_scaled)\n    pca_test = pca.transform(X_test_scaled)\n\n    pca_train_df = pd.DataFrame(pca_train, columns=[f\"PC{i+1}\" for i in range(optimal_components)])\n    pca_test_df = pd.DataFrame(pca_test, columns=[f\"PC{i+1}\" for i in range(optimal_components)])\n\n    return pca_train_df, pca_test_df\n\n# Run PCA on training and test data\npca_train_df, pca_test_df = perform_pca(encoded_df, encoded_df_test, threshold=0.90)\n\n# Now, use PCA-transformed features for the next steps\nX_pca = pca_train_df\nX_pca.ffill(inplace=True)  # Fill any missing values with forward fill\n\ndf_test = pca_test_df\ndf_test.ffill(inplace=True)\n\n# Load the target column 'sii' from the original train dataset\ny = pd.read_csv(\"/kaggle/input/child-mind-institute-problematic-internet-use/train.csv\")['sii']\ny.fillna(0, inplace=True)\n\nprint(\"PCA-transformed train data:\", X_pca)\nprint(\"Target variable y:\", y)\n\n# Split data into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X_pca, y, test_size=0.2, random_state=42)\nX_test = df_test\n\n# Standardize features again (since PCA has already been applied)\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_val = scaler.transform(X_val)\nX_test = scaler.transform(X_test)\n\n# Define and train the model with increased max_iter and solver='adam'\nmodel = MLPRegressor(hidden_layer_sizes=(100, 50, 25), max_iter=2000, solver='adam', random_state=42, activation='relu', alpha=0.0001)\nmodel.fit(X_train, y_train)\n\n# Predict on validation set\ny_pred = model.predict(X_val)\n\n# Evaluate the model\nmse = mean_squared_error(y_val, y_pred)\nr2 = r2_score(y_val, y_pred)\nprint(f'Mean Squared Error: {mse:.2f}')\nprint(f'R2 Score: {r2:.2f}')\n\n# Predict on the test set\ny_test_predict = model.predict(X_test)\nprint(\"Test predictions:\", y_test_predict)\n\n# Prepare submission\ny_test_predict_df = pd.DataFrame(y_test_predict.astype(int), columns=[\"sii\"])\nsubmission = pd.concat([id, y_test_predict_df], axis=1)\n\n# Display the first few rows of the submission\nprint(submission.head())\n\n# Save the submission to a CSV file\nsubmission.to_csv(\"/kaggle/working/submission.csv\", index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T10:22:30.885952Z","iopub.execute_input":"2024-12-07T10:22:30.886365Z"}},"outputs":[],"execution_count":null}]}