{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import pandas as pd\n", "import numpy as np\n", "from tqdm import tqdm\n", "import matplotlib\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "C:\\PROGRAMY\\Anaconda3\\envs\\ium\\lib\\site-packages\\ipykernel_launcher.py:2: MatplotlibDeprecationWarning: Support for setting an rcParam that expects a str value to a non-str value is deprecated since 3.5 and support will be removed two minor releases later.\n", " \n" ] } ], "source": [ "matplotlib.rc('text', usetex=True)\n", "matplotlib.rcParams['text.latex.preamble']=[r\"\\usepackage{amsmath}\"]\n", "sns.set_style(\"darkgrid\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "train_dataset = pd.read_csv('../train_dataset.csv')\n", "test_dataset = pd.read_csv('../test_dataset.csv')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "X_train = train_dataset.drop(columns=['No-show']).to_numpy()\n", "X_test = test_dataset.drop(columns=['No-show']).to_numpy()\n", "y_train = train_dataset['No-show'].to_numpy()\n", "y_test = test_dataset['No-show'].to_numpy()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "class LogisticRegression(torch.nn.Module):\n", " def __init__(self, input_dim, output_dim):\n", " super(LogisticRegression, self).__init__()\n", " self.linear = torch.nn.Linear(input_dim, output_dim) \n", " def forward(self, x):\n", " outputs = torch.sigmoid(self.linear(x))\n", " return outputs" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "epochs = 50_000\n", "input_dim = 9\n", "output_dim = 1\n", "learning_rate = 0.01" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "model = LogisticRegression(input_dim, output_dim)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "criterion = torch.nn.BCELoss()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "X_train, X_test = torch.Tensor(X_train),torch.Tensor(X_test)\n", "y_train, y_test = torch.Tensor(y_train),torch.Tensor(y_test)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Training Epochs: 100%|██████████| 50000/50000 [02:01<00:00, 411.29it/s]\n" ] } ], "source": [ "losses = []\n", "losses_test = []\n", "Iterations = []\n", "iter = 0\n", "for epoch in tqdm(range(int(epochs)), desc='Training Epochs'):\n", " x = X_train\n", " labels = y_train\n", " optimizer.zero_grad() # Setting our stored gradients equal to zero\n", " outputs = model(X_train)\n", " loss = criterion(torch.squeeze(outputs), labels) \n", " \n", " loss.backward() # Computes the gradient of the given tensor w.r.t. the weights/bias\n", " \n", " optimizer.step() # Updates weights and biases with the optimizer (SGD)\n", " \n", " iter+=1\n", " if iter%10000==0:\n", " with torch.no_grad():\n", " # Calculating the loss and accuracy for the test dataset\n", " correct_test = 0\n", " total_test = 0\n", " outputs_test = torch.squeeze(model(X_test))\n", " loss_test = criterion(outputs_test, y_test)\n", " \n", " predicted_test = outputs_test.round().detach().numpy()\n", " total_test += y_test.size(0)\n", " correct_test += np.sum(predicted_test == y_test.detach().numpy())\n", " accuracy_test = 100 * correct_test/total_test\n", " losses_test.append(loss_test.item())\n", " \n", " # Calculating the loss and accuracy for the train dataset\n", " total = 0\n", " correct = 0\n", " total += y_train.size(0)\n", " correct += np.sum(torch.squeeze(outputs).round().detach().numpy() == y_train.detach().numpy())\n", " accuracy = 100 * correct/total\n", " losses.append(loss.item())\n", " Iterations.append(iter)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Iteration: 50000. \n", "Test - Loss: 0.480914831161499. Accuracy: 79.76567447751742\n", "Train - Loss: 0.48352959752082825. Accuracy: 79.37570685365301\n", "\n" ] } ], "source": [ "print(f\"Iteration: {iter}. \\nTest - Loss: {loss_test.item()}. Accuracy: {accuracy_test}\")\n", "print(f\"Train - Loss: {loss.item()}. Accuracy: {accuracy}\\n\")" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "with open(\"logs.txt\", \"a\") as myfile:\n", " myfile.write(f\"loss={loss.item()}, accuracy={accuracy}\\n\")" ] } ], "metadata": { "interpreter": { "hash": "3c12dc341c1078754dffca0e61bfc548ab04f96cfe0a82a85a936b702c4881ab" }, "kernelspec": { "display_name": "Python 3.7.11 ('ium')", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.11" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }