{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":81933,"databundleVersionId":9643020,"sourceType":"competition"}],"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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.preprocessing import StandardScaler\nfrom imblearn.over_sampling import SMOTE\n\n# Load Dataset\ntrain = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/train.csv')\ntest = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/test.csv')\n\n# Feature Selection\nfeatures = ['Physical-BMI', 'Physical-Height', 'Physical-Weight', \n            'PreInt_EduHx-computerinternet_hoursday', \n            'PAQ_A-PAQ_A_Total', 'SDS-SDS_Total_Raw']\ntarget = 'sii'\n\n# Handle Missing Values\nfor col in features:\n    if col in train.columns:\n        train[col] = train[col].fillna(train[col].median())\n        if col in test.columns:\n            test[col] = test[col].fillna(test[col].median())\n\n# Isi nilai kosong di target\ntrain[target] = train[target].fillna(0).astype(int)\n\n# Normalize Features\nscaler = StandardScaler()\nX = scaler.fit_transform(train[features])\ny = train[target].values\n\n# Balance Data using SMOTE\nsmote = SMOTE(random_state=42)\nX, y = smote.fit_resample(X, y)\n\n# Split Data\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Modified Perceptron\nclass ModifiedPerceptron:\n    def __init__(self, learning_rate=0.01, epochs=2000, threshold=0.5, momentum=0.9, activation='relu'):\n        self.learning_rate = learning_rate\n        self.epochs = epochs\n        self.threshold = threshold\n        self.momentum = momentum\n        self.activation_type = activation\n        self.weights = None\n        self.bias = None\n        self.velocity_weights = None\n        self.velocity_bias = None\n\n    def activation_function(self, z):\n        if self.activation_type == 'sigmoid':\n            z = np.clip(z, -100, 100)  # Avoid overflow\n            return 1 / (1 + np.exp(-z))\n        elif self.activation_type == 'relu':\n            return np.maximum(0, z)\n        else:\n            raise ValueError(\"Unsupported activation function\")\n\n    def predict_label(self, z):\n        return 1 if z >= self.threshold else 0\n\n    def fit(self, X, y):\n        n_samples, n_features = X.shape\n        self.weights = np.zeros(n_features)\n        self.bias = 0\n        self.velocity_weights = np.zeros(n_features)\n        self.velocity_bias = 0\n\n        for epoch in range(self.epochs):\n            for idx, x_i in enumerate(X):\n                linear_output = np.dot(x_i, self.weights) + self.bias\n                activated_output = self.activation_function(linear_output)\n                y_predicted = activated_output if self.activation_type == 'relu' else activated_output\n\n                # Calculate error\n                error = y[idx] - y_predicted\n\n                # Update weights and bias with momentum\n                grad_weights = error * x_i\n                grad_bias = error\n\n                self.velocity_weights = (self.momentum * self.velocity_weights) + (self.learning_rate * grad_weights)\n                self.velocity_bias = (self.momentum * self.velocity_bias) + (self.learning_rate * grad_bias)\n\n                self.weights += self.velocity_weights\n                self.bias += self.velocity_bias\n\n    def predict(self, X):\n        linear_output = np.dot(X, self.weights) + self.bias\n        probabilities = self.activation_function(linear_output)\n        return np.array([self.predict_label(prob) for prob in probabilities])\n\n# Train Perceptron\nperceptron = ModifiedPerceptron(learning_rate=0.01, epochs=2000, threshold=0.5, activation='relu')\nperceptron.fit(X_train, y_train)\n\n# Evaluate Model\ny_pred = perceptron.predict(X_val)\nscore = cohen_kappa_score(y_val, y_pred, weights='quadratic')\nprint(\"Quadratic Weighted Kappa Score (Validation):\", score)\n\n# Predict on Test Data\nX_test = scaler.transform(test[features])\ntest['sii'] = perceptron.predict(X_test)\n\n# Save Submission File\nsubmission = test[['id', 'sii']]\nsubmission.to_csv('submission.csv', index=False)\nprint(\"Submission file saved as 'submission.csv'\")\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}