Last active
September 19, 2022 14:16
-
-
Save Astroneko404/7649174a4172f08ea51600c42438b677 to your computer and use it in GitHub Desktop.
Linear regression (and logistic regression) in PyTorch from scratch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 10, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import torch\n", | |
"import torch.nn as nn\n", | |
"from sklearn.datasets import load_breast_cancer\n", | |
"import numpy as np" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"## Data Preparation" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 11, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"from sklearn.model_selection import train_test_split\n", | |
"\n", | |
"# Load data\n", | |
"data = load_breast_cancer()\n", | |
"X, y = data.data, data.target\n", | |
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n", | |
"\n", | |
"n_samples, n_features = X.shape\n", | |
"\n", | |
"# Scale\n", | |
"from sklearn.preprocessing import StandardScaler\n", | |
"\n", | |
"sc = StandardScaler()\n", | |
"X_train = sc.fit_transform(X_train)\n", | |
"X_test = sc.transform(X_test)\n", | |
"\n", | |
"X_train = torch.from_numpy(X_train.astype(np.float32))\n", | |
"X_test = torch.from_numpy(X_test.astype(np.float32))\n", | |
"y_train = torch.from_numpy(y_train.astype(np.float32))\n", | |
"y_test = torch.from_numpy(y_test.astype(np.float32))\n", | |
"\n", | |
"y_train = y_train.view(y_train.shape[0], 1)\n", | |
"y_test = y_test.view(y_test.shape[0], 1)" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"## Model" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 15, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"epoch: 50, loss = 0.1129\n", | |
"epoch: 100, loss = 0.0599\n", | |
"epoch: 150, loss = 0.0566\n", | |
"epoch: 200, loss = 0.0552\n", | |
"accuracy = 0.9561\n" | |
] | |
} | |
], | |
"source": [ | |
"class LinearRegression(nn.Module):\n", | |
" def __init__(self, n_input_features) -> None:\n", | |
" super(LinearRegression, self).__init__()\n", | |
" self.linear = nn.Linear(n_input_features, 1)\n", | |
" def forward(self, x):\n", | |
" return self.linear(x)\n", | |
"\n", | |
"class LogisticRegression(nn.Module):\n", | |
" def __init__(self, n_input_features) -> None:\n", | |
" super(LogisticRegression, self).__init__()\n", | |
" self.linear = nn.Linear(n_input_features, 1)\n", | |
" def forward(self, x):\n", | |
" return torch.sigmoid(self.linear(x))\n", | |
"\n", | |
"model = LinearRegression(n_features)\n", | |
"if torch.cuda.is_available():\n", | |
" model.cuda()\n", | |
" \n", | |
"# Loss\n", | |
"criterion = nn.MSELoss()\n", | |
"optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n", | |
"\n", | |
"for epoch in range(200):\n", | |
" # Forward pass and loss\n", | |
" y_pred = model(X_train)\n", | |
" loss = criterion(y_pred, y_train)\n", | |
"\n", | |
" # Backward pass\n", | |
" loss.backward()\n", | |
"\n", | |
" # Update weight\n", | |
" optimizer.step()\n", | |
"\n", | |
" # Zero gradients\n", | |
" optimizer.zero_grad()\n", | |
"\n", | |
" if (epoch + 1) % 50 == 0:\n", | |
" print(f'epoch: {epoch+1}, loss = {loss.item():.4f}')\n", | |
"\n", | |
"with torch.no_grad():\n", | |
" y_pred = model(X_test)\n", | |
" y_pred_cls = y_pred.round()\n", | |
" acc = y_pred_cls.eq(y_test).sum() / float(y_test.shape[0])\n", | |
" print(f'accuracy = {acc:.4f}')" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3.9.6 64-bit", | |
"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.9.6" | |
}, | |
"orig_nbformat": 4, | |
"vscode": { | |
"interpreter": { | |
"hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" | |
} | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment