{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":81933,"databundleVersionId":9643020,"sourceType":"competition"}],"dockerImageVersionId":30787,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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_count":null,"outputs":[]},{"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\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.preprocessing import StandardScaler\n\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\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\")\nid = df_test['id']\ndf = df.drop(columns=['id', 'sii'])\ndf_test = df_test.drop(columns=['id'])\ndf = encode_string_columns(df)\ndf.fillna(0, inplace=True)\ndf_test = encode_string_columns(df_test)\ndf_test.fillna(0, inplace=True)\n\ncommon_columns = df.columns.intersection(df_test.columns)\nprint(common_columns)\n\n# Set up features and target\nX = df[common_columns]\ny = df.drop(columns=common_columns)\n\n# Split data 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# Define the neural network model for regression\nmodel = MLPRegressor(hidden_layer_sizes=(10, 5), max_iter=1000, random_state=42)\n\n# Train the model\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)\ny_test_predict_df = pd.DataFrame(y_test_predict, columns=y.columns)\n\n# Concatenate the predicted values with the original test DataFrame\ndf_test_with_predictions = pd.concat([df_test.reset_index(drop=True), y_test_predict_df], axis=1)\n\n# Reorder columns to match train DataFrame\ndf_test_with_predictions = df_test_with_predictions[df.columns]\n\nprint(df_test_with_predictions.head())\n\n\n\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\n\n\n# Load 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\n\n\n\ndf = pd.DataFrame(df)\ndf_test = pd.DataFrame(df_test)\n\nprint(df.shape)\ncol = df.columns\n\n\n\n\nprint(id)\ndf = df.drop(columns = [\"id\",'sii'])\n\n# df_test = df_test.drop(columns = [\"id\"])\n\n# Show the first few rows and the data types of the columns\n# print(df.head())\n# print(df[col].dtypes)\n\nstring_columns = df.select_dtypes(include='object').columns\nprint(df)\nprint(df_test)\n# Encode the string columns in DataFrame\nencoded_df = encode_string_columns(df)\n# print(encoded_df.head())\nencoded_df_test = encode_string_columns(df_test)\nencoded_df_test.fillna(0, inplace=True)\nencoded_df.fillna(0, inplace=True)\n\nprint(encoded_df.shape)\nprint(encoded_df_test.shape)\ndef choose_optimal_components(explained_variance_ratio, threshold=0.95):\n    cumulative_variance = explained_variance_ratio.cumsum()\n    optimal_components = (cumulative_variance >= threshold).argmax() + 1\n    return optimal_components, cumulative_variance\n\n\ndef perform_pca(data, data_2, threshold=0.95):\n    \"\"\"\n    Performs PCA on a given DataFrame excluding the last column.\n\n    Parameters:\n    data (pd.DataFrame): The input data.\n    threshold (float): The desired level of explained variance. Default is 0.95 (95%).\n\n    Returns:\n    pd.DataFrame: Transformed data with principal components.\n    int: Optimal number of components.\n    \"\"\"\n    # Excluding the last column\n    features = data.iloc[:, :-1]\n    features_test = data_2.iloc[:,:-1]\n\n    # Standardize the features\n    scaler = StandardScaler()\n    standardized_data = scaler.fit_transform(features)\n    standardized_data_test = scaler.transform(features_test)\n\n    # Perform PCA without specifying the number of components\n    pca = PCA()\n    pca.fit(standardized_data)\n\n    # Determine the optimal number of components\n    optimal_components, cumulative_variance = choose_optimal_components(pca.explained_variance_ratio_, threshold)\n\n    # Perform PCA with the optimal number of components\n    pca = PCA(n_components=optimal_components)\n    principal_components = pca.fit_transform(standardized_data)\n\n    # Create a DataFrame with the principal components\n    columns = [f\"PC{i+1}\" for i in range(optimal_components)]\n    pca_df = pd.DataFrame(data=principal_components, columns=columns)\n    \n    principle_components_test= pca.transform(standardized_data_test)\n    columns_test = [f\"PC{i+1}\" for i in range(optimal_components)]\n    pca_test_df = pd.DataFrame(data = principle_components_test, columns = columns_test)\n\n    return pca_df, optimal_components, cumulative_variance, pca_test_df\n\n\n    \ndata = encoded_df\ndata_2 = encoded_df_test\n\n    # Perform PCA excluding the last column\nthreshold = 0.95  # Desired level of explained variance\npca_result, optimal_components, cumulative_variance, pca_test_df= perform_pca(data, data_2, threshold)\n\n   \n    \nprint(pca_result)\n\npca_result.fillna(0, inplace=True)\nprint(pca_result)\n\n    \n    \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n\nX = pca_result\nX.fillna(method = 'ffill', inplace = True)\ndf_test = pca_test_df\ndf_test.fillna(method = 'ffill', inplace = True)\n\ny = pd.read_csv(\"/kaggle/input/child-mind-institute-problematic-internet-use/train.csv\")\n# Features and target\n\ny = y['sii']\ny.fillna(0, inplace = True)\nprint(X)\nprint(y)\n\n# Split data 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)\nX_test = df_test\n\n# Standardize features\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_val = scaler.transform(X_val)\nX_test = scaler.transform(X_test)\n\n# Define the neural network model\nmodel = MLPClassifier(hidden_layer_sizes=(10, 5), max_iter=1000, random_state=42)\n\n# Train the model\nmodel.fit(X_train, y_train)\n\n# Predict on validation set\ny_pred = model.predict(X_val)\n\nmse = mean_squared_error(y_val, y_pred)\nr2 = r2_score(y_val, y_pred)\n\n# Evaluate the model\naccuracy = accuracy_score(y_val, y_pred)\nprint(f'Validation Accuracy: {accuracy:.2f}')\nprint(mse)\nprint(r2)\n\n\ny_test_predict = model.predict(X_test)\nprint(y_test_predict)\n\ny_test_predict = pd.DataFrame(y_test_predict.astype(int), columns = [\"sii\"])\n\n# Concatenate the predicted values with the original test DataFrame\nsubmission = pd.concat([id, y_test_predict], axis=1)\n\nprint(submission.head())\n\nsubmission.to_csv(\"/kaggle/working/submission.csv\", index=False)\n\n\n\n\n    \n","metadata":{"execution":{"iopub.status.busy":"2024-10-30T12:14:33.246894Z","iopub.execute_input":"2024-10-30T12:14:33.247369Z","iopub.status.idle":"2024-10-30T12:14:48.002226Z","shell.execute_reply.started":"2024-10-30T12:14:33.247331Z","shell.execute_reply":"2024-10-30T12:14:48.001283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}